Decompiled source of PotatoHammer v1.0.6

plugins/PotatoHammer.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace PotatoHammer;

[BepInPlugin("potato.hammer", "Potato Hammer", "1.0.6")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Player), "SetPlaceMode")]
	internal static class TakeOutHammer
	{
		private static void Prefix(PieceTable buildPieces)
		{
			if (!Object.op_Implicit((Object)(object)buildPieces))
			{
				return;
			}
			if ((Object)(object)buildPieces != (Object)(object)Hammer())
			{
				try
				{
					Restore(buildPieces);
					return;
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("Couldn't restore that tool's tabs: " + ex));
					return;
				}
			}
			try
			{
				Include(buildPieces);
			}
			catch (Exception ex2)
			{
				Log.LogWarning((object)("Couldn't add other mods' hammer pieces: " + ex2));
			}
			try
			{
				Sort(buildPieces);
			}
			catch (Exception ex3)
			{
				Log.LogWarning((object)("Couldn't sort the hammer: " + ex3));
			}
		}
	}

	public const string Id = "potato.hammer";

	public const string Version = "1.0.6";

	private const string TabsSection = "2 - Tabs";

	internal static ManualLogSource Log;

	private static Plugin instance;

	private static ConfigEntry<bool> sortOn;

	private static ConfigEntry<bool> includeTools;

	private static ConfigEntry<string> leaveAlone;

	private static ConfigEntry<string> extraPieces;

	private static readonly Dictionary<string, ConfigEntry<string>> TabNames = new Dictionary<string, ConfigEntry<string>>();

	private static readonly Dictionary<Piece, PieceCategory> Original = new Dictionary<Piece, PieceCategory>();

	private static readonly Dictionary<Piece, UsageTagFlags> OriginalUsage = new Dictionary<Piece, UsageTagFlags>();

	private static readonly HashSet<GameObject> Added = new HashSet<GameObject>();

	private static readonly HashSet<string> VanillaTools = new HashSet<string> { "Hammer", "Hoe", "Cultivator" };

	private static readonly HashSet<string> VanillaTables = new HashSet<string> { "_HammerPieceTable", "_HoePieceTable", "_CultivatorPieceTable", "_FeasterPieceTable" };

	private static string lastSummary;

	private static string lastTools;

	private void Awake()
	{
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		sortOn = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Sort the hammer", true, "Move each mod's hammer pieces to a tab named after the mod. The game's own pieces stay where they are. Takes effect the next time you take out the hammer.");
		leaveAlone = ((BaseUnityPlugin)this).Config.Bind<string>("1 - General", "Mods to leave alone", "", "Mods whose pieces stay where the mod put them, separated by commas (mod name as in the tab list below, or its id).");
		extraPieces = ((BaseUnityPlugin)this).Config.Bind<string>("1 - General", "Extra pieces", "", "Pieces whose mod can't be told (they stay where they are; the log lists the hammer's pieces by tab), put on a tab by name: piece=Tab, separated by commas. Example: piece_mytable=My Mod.");
		includeTools = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Include other hammers", true, "Also put the pieces from other mods' own hammers (like Odin's Hammer) on the hammer, each on its mod's tab, so one hammer builds everything. Their own hammer still works. Mods in \"Mods to leave alone\" keep theirs separate. Takes effect the next time you take out the hammer.");
		try
		{
			SnapPoints.Bind(((BaseUnityPlugin)this).Config);
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Snap points are off: " + ex.Message));
		}
		ModQuery.Enable();
		new Harmony("potato.hammer").PatchAll(typeof(Plugin).Assembly);
	}

	private void Update()
	{
		SnapPoints.Update();
	}

	private static PieceTable Hammer()
	{
		GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab("Hammer") : null);
		if (!Object.op_Implicit((Object)(object)val))
		{
			return null;
		}
		return val.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces;
	}

	private static BepInPlugin SourceOf(GameObject prefab, Dictionary<string, BepInPlugin> jotunnPieces)
	{
		try
		{
			IModPrefab prefab2 = ModQuery.GetPrefab(((Object)prefab).name);
			BepInPlugin val = ((prefab2 != null) ? prefab2.SourceMod : null);
			if (val != null)
			{
				return val;
			}
		}
		catch (Exception)
		{
		}
		if (!jotunnPieces.TryGetValue(((Object)prefab).name, out var value))
		{
			return null;
		}
		return value;
	}

	private static string Clean(string name)
	{
		return new string(name.Where((char c) => c != '=' && c != '\n' && c != '\t' && c != '\\' && c != '"' && c != '\'' && c != '[' && c != ']').ToArray()).Trim();
	}

	private static string TabFor(BepInPlugin mod)
	{
		string text = Clean(mod.Name);
		if (text.Length == 0)
		{
			text = Clean(mod.GUID);
		}
		if (!TabNames.TryGetValue(text, out var value))
		{
			value = ((BaseUnityPlugin)instance).Config.Bind<string>("2 - Tabs", text, Spaced(text), "Tab for " + mod.Name + "'s hammer pieces (" + mod.GUID + "). Mods with the same tab name share it; empty = leave its pieces where the mod put them.");
			TabNames[text] = value;
		}
		if (LeftAlone(mod))
		{
			return null;
		}
		string text2 = value.Value.Trim();
		if (text2 == text)
		{
			text2 = Spaced(text);
		}
		if (text2.Length <= 0)
		{
			return null;
		}
		return text2;
	}

	private static bool LeftAlone(BepInPlugin mod)
	{
		string key = Clean(mod.Name);
		return (from part in leaveAlone.Value.Split(',')
			select part.Trim() into part
			where part.Length > 0
			select part).Any((string part) => part.Equals(key, StringComparison.OrdinalIgnoreCase) || part.Equals(Spaced(key), StringComparison.OrdinalIgnoreCase) || part.Equals(mod.GUID, StringComparison.OrdinalIgnoreCase));
	}

	private static void Include(PieceTable hammer)
	{
		hammer.m_pieces.RemoveAll((GameObject item) => Added.Contains(item));
		Added.Clear();
		if (!includeTools.Value || !sortOn.Value || !Object.op_Implicit((Object)(object)ObjectDB.instance))
		{
			return;
		}
		HashSet<GameObject> hashSet = new HashSet<GameObject>(hammer.m_pieces.Where((GameObject val3) => Object.op_Implicit((Object)(object)val3)));
		Dictionary<string, BepInPlugin> jotunnPieces = new Dictionary<string, BepInPlugin>();
		try
		{
			foreach (CustomPiece piece in ModRegistry.GetPieces())
			{
				if (Object.op_Implicit((Object)(object)((piece != null) ? piece.PiecePrefab : null)) && ((CustomEntity)piece).SourceMod != null)
				{
					jotunnPieces[((Object)piece.PiecePrefab).name] = ((CustomEntity)piece).SourceMod;
				}
			}
		}
		catch (Exception)
		{
		}
		List<string> list = new List<string>();
		foreach (GameObject item in ObjectDB.instance.m_items)
		{
			PieceTable val = ((!Object.op_Implicit((Object)(object)item)) ? null : item.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces);
			if (!Object.op_Implicit((Object)(object)val) || (Object)(object)val == (Object)(object)hammer || !val.m_canRemovePieces)
			{
				continue;
			}
			BepInPlugin val2 = null;
			try
			{
				IModPrefab prefab = ModQuery.GetPrefab(((Object)item).name);
				val2 = ((prefab != null) ? prefab.SourceMod : null);
			}
			catch (Exception)
			{
			}
			if (VanillaTools.Contains(((Object)item).name) || VanillaTables.Contains(((Object)val).name))
			{
				continue;
			}
			if (val2 == null)
			{
				val2 = (from prefab2 in val.m_pieces
					where Object.op_Implicit((Object)(object)prefab2)
					select SourceOf(prefab2, jotunnPieces) into owner
					where owner != null
					group owner by owner.GUID into @group
					orderby @group.Count() descending
					select @group.First()).FirstOrDefault();
			}
			if (val2 == null || LeftAlone(val2))
			{
				continue;
			}
			int num = 0;
			foreach (GameObject piece2 in val.m_pieces)
			{
				if (Object.op_Implicit((Object)(object)piece2) && hashSet.Add(piece2))
				{
					hammer.m_pieces.Add(piece2);
					Added.Add(piece2);
					num++;
				}
			}
			if (num > 0)
			{
				list.Add($"{((Object)item).name} from {val2.Name} ({num})");
			}
		}
		string text = ((list.Count == 0) ? "none" : string.Join(", ", list));
		if (!(text == lastTools))
		{
			lastTools = text;
			Log.LogInfo((object)("Pieces added from other mods' hammers: " + text));
		}
	}

	private static void Restore(PieceTable table)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: 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)
		foreach (GameObject piece in table.m_pieces)
		{
			Piece val = (Object.op_Implicit((Object)(object)piece) ? piece.GetComponent<Piece>() : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				if (Original.TryGetValue(val, out var value))
				{
					val.m_category = value;
				}
				if (OriginalUsage.TryGetValue(val, out var value2))
				{
					val.m_usage = value2;
				}
			}
		}
	}

	private static string Spaced(string name)
	{
		if (name.Contains(" "))
		{
			return name;
		}
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < name.Length; i++)
		{
			char c = name[i];
			if (c == '_' || c == '-')
			{
				stringBuilder.Append(' ');
				continue;
			}
			if (i > 0 && char.IsUpper(c) && (char.IsLower(name[i - 1]) || (i + 1 < name.Length && char.IsLower(name[i + 1]) && char.IsUpper(name[i - 1]))))
			{
				stringBuilder.Append(' ');
			}
			stringBuilder.Append(c);
		}
		return stringBuilder.ToString().Trim();
	}

	private static PieceCategory Category(string tab)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: 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_0014: 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_003e: Unknown result type (might be due to invalid IL or missing references)
		PieceCategory result = PieceManager.Instance.AddPieceCategory(tab);
		if (Listed(tab))
		{
			return result;
		}
		PieceCategory result2 = PieceManager.Instance.AddPieceCategory(tab + "\u200b");
		if (!Listed(tab + "\u200b"))
		{
			return result;
		}
		return result2;
	}

	private static bool Listed(string name)
	{
		try
		{
			return !(Traverse.Create((object)PieceManager.Instance).Field("PieceCategories").GetValue() is Dictionary<string, PieceCategory> dictionary) || dictionary.ContainsKey(name);
		}
		catch (Exception)
		{
			return true;
		}
	}

	private static Dictionary<string, string> Extras()
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		string[] array = extraPieces.Value.Split(',');
		foreach (string text in array)
		{
			int num = text.IndexOf('=');
			if (num > 0)
			{
				string text2 = text.Substring(0, num).Trim();
				string text3 = text.Substring(num + 1).Trim();
				if (text2.Length > 0 && text3.Length > 0)
				{
					dictionary[text2] = text3;
				}
			}
		}
		return dictionary;
	}

	internal static void Sort(PieceTable table)
	{
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		//IL_0103: 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_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Unknown result type (might be due to invalid IL or missing references)
		Dictionary<string, BepInPlugin> dictionary = new Dictionary<string, BepInPlugin>();
		try
		{
			foreach (CustomPiece piece in ModRegistry.GetPieces())
			{
				if (Object.op_Implicit((Object)(object)((piece != null) ? piece.PiecePrefab : null)) && ((CustomEntity)piece).SourceMod != null)
				{
					dictionary[((Object)piece.PiecePrefab).name] = ((CustomEntity)piece).SourceMod;
				}
			}
		}
		catch (Exception)
		{
		}
		Dictionary<string, string> dictionary2 = Extras();
		SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>();
		List<string> list = new List<string>();
		foreach (GameObject piece2 in table.m_pieces)
		{
			Piece val = (Object.op_Implicit((Object)(object)piece2) ? piece2.GetComponent<Piece>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				continue;
			}
			if (!Original.TryGetValue(val, out var value))
			{
				value = (Original[val] = val.m_category);
			}
			if (!OriginalUsage.TryGetValue(val, out var value2))
			{
				value2 = (OriginalUsage[val] = val.m_usage);
			}
			string text = null;
			if (sortOn.Value)
			{
				if (dictionary2.TryGetValue(((Object)piece2).name, out var value3))
				{
					text = value3;
				}
				else
				{
					BepInPlugin val2 = SourceOf(piece2, dictionary);
					if (val2 == null)
					{
						list.Add(((Object)piece2).name);
					}
					else if (val2.GUID != "com.jotunn.jotunn")
					{
						text = TabFor(val2);
					}
				}
			}
			if (text == null)
			{
				val.m_category = value;
				val.m_usage = value2;
				continue;
			}
			val.m_category = Category(text);
			val.m_usage = (UsageTagFlags)0;
			sortedDictionary.TryGetValue(text, out var value4);
			sortedDictionary[text] = value4 + 1;
		}
		string text2 = ((sortedDictionary.Count == 0) ? "no mod pieces moved" : string.Join(", ", sortedDictionary.Select((KeyValuePair<string, int> pair) => $"{pair.Key} ({pair.Value})")));
		if (text2 != lastSummary)
		{
			lastSummary = text2;
			Log.LogInfo((object)("Hammer tabs: " + text2));
			Log.LogInfo((object)("Pieces from the game or from a mod that can't be told, left where they were (use \"Extra pieces\" for a mod's): " + string.Join(", ", list)));
		}
	}
}
internal static class SnapPoints
{
	internal class Marker : MonoBehaviour
	{
	}

	private class Command : ConsoleCommand
	{
		public override string Name => "snappoints";

		public override string Help => "Look at a built piece with the hammer out: give every piece of its kind snap points, or take them away.";

		public override void Run(string[] args, Terminal context)
		{
			Pick(context);
		}
	}

	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	private static class RecordVanilla
	{
		[HarmonyPriority(800)]
		private static void Prefix(ZNetScene __instance)
		{
			try
			{
				Vanilla.Clear();
				Points.Clear();
				Automatic.Clear();
				Boxes.Clear();
				foreach (GameObject prefab in __instance.m_prefabs)
				{
					if (Object.op_Implicit((Object)(object)prefab))
					{
						Vanilla.Add(((Object)prefab).name);
					}
				}
				foreach (GameObject nonNetViewPrefab in __instance.m_nonNetViewPrefabs)
				{
					if (Object.op_Implicit((Object)(object)nonNetViewPrefab))
					{
						Vanilla.Add(((Object)nonNetViewPrefab).name);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't list the game's own pieces: " + ex.Message));
			}
		}
	}

	[HarmonyPatch(typeof(Player), "Message")]
	private static class SnapMessage
	{
		private static readonly FieldRef<Player, int> Manual = AccessTools.FieldRefAccess<Player, int>("m_manualSnapPoint");

		private static readonly FieldRef<Player, List<Transform>> Ghost = AccessTools.FieldRefAccess<Player, List<Transform>>("m_tempSnapPoints1");

		private static readonly FieldRef<Player, GameObject> Placement = AccessTools.FieldRefAccess<Player, GameObject>("m_placementGhost");

		private static void Prefix(Player __instance, ref string msg)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (plainNames == null || !plainNames.Value || msg == null || !msg.StartsWith("$msg_snapping "))
				{
					return;
				}
				int num = Manual.Invoke(__instance);
				List<Transform> list = Ghost.Invoke(__instance);
				GameObject val = Placement.Invoke(__instance);
				if (num >= 0 && list != null && num < list.Count && Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)list[num]) && !Object.op_Implicit((Object)(object)((Component)list[num]).GetComponent<Marker>()))
				{
					string text = Describe(Utils.GetPrefabName(val), list[num].localPosition);
					if (text != null)
					{
						msg = "$msg_snapping " + text;
					}
				}
			}
			catch (Exception)
			{
			}
		}
	}

	[HarmonyPatch(typeof(Piece), "Awake")]
	private static class AddToPiece
	{
		private static void Postfix(Piece __instance)
		{
			try
			{
				Refresh(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't add snap points: " + ex.Message));
			}
		}
	}

	private const string Section = "3 - Snap points";

	private static ConfigEntry<bool> on;

	private static ConfigEntry<bool> automatic;

	private static ConfigEntry<bool> plainNames;

	private static ConfigEntry<int> fewest;

	private static ConfigEntry<KeyboardShortcut> key;

	private static ConfigEntry<string> chosen;

	private static ConfigEntry<string> refused;

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

	private static readonly Dictionary<string, List<KeyValuePair<string, Vector3>>> Points = new Dictionary<string, List<KeyValuePair<string, Vector3>>>();

	private static readonly Dictionary<string, bool> Automatic = new Dictionary<string, bool>();

	private static readonly FieldRef<List<Piece>> AllPieces = AccessTools.StaticFieldRefAccess<List<Piece>>(AccessTools.Field(typeof(Piece), "s_allPieces"));

	private static readonly Dictionary<string, Bounds?> Boxes = new Dictionary<string, Bounds?>();

	internal static void Bind(ConfigFile config)
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Expected O, but got Unknown
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		on = config.Bind<bool>("3 - Snap points", "Add snap points", true, "Give pieces that lack them snap points from their shape: corners, edge middles, top and bottom centres. Only your own building changes.");
		automatic = config.Bind<bool>("3 - Snap points", "Automatic for mod pieces", true, "Mods' pieces with only one or two snap points of their own get them without asking. Pieces with none (usually decorations meant to go anywhere) and the game's own pieces only get them when you pick them.");
		plainNames = config.Bind<bool>("3 - Snap points", "Plain snap point names", true, "When you pick a snap point while building, name it by where it sits on the piece (Top front left corner, Bottom back edge, Left centre) instead of the name its mod gave it (_snappoint (5), Left 1).");
		fewest = config.Bind<int>("3 - Snap points", "Automatic up to", 2, new ConfigDescription("Mods' pieces with at least one and at most this many snap points of their own get them automatically.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), Array.Empty<object>()));
		key = config.Bind<KeyboardShortcut>("3 - Snap points", "Pick key", new KeyboardShortcut((KeyCode)107, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), "With the hammer out, look at a built piece and press this to give every piece of its kind snap points, or take them away again. The console command snappoints does the same.");
		chosen = config.Bind<string>("3 - Snap points", "Picked pieces", "", "Kept by the Pick key and the snappoints command (the pieces' internal names); no need to edit.");
		refused = config.Bind<string>("3 - Snap points", "Turned off pieces", "", "Kept by the Pick key and the snappoints command (the pieces' internal names); no need to edit.");
		on.SettingChanged += delegate
		{
			RefreshAll();
		};
		automatic.SettingChanged += delegate
		{
			Automatic.Clear();
			RefreshAll();
		};
		fewest.SettingChanged += delegate
		{
			Automatic.Clear();
			RefreshAll();
		};
		try
		{
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new Command());
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Couldn't add the snappoints command: " + ex.Message));
		}
	}

	private static HashSet<string> List(ConfigEntry<string> entry)
	{
		return new HashSet<string>(from part in entry.Value.Split(',')
			select part.Trim() into part
			where part.Length > 0
			select part);
	}

	private static void Save(ConfigEntry<string> entry, HashSet<string> names)
	{
		entry.Value = string.Join(",", names.OrderBy((string name) => name));
	}

	private static bool Wants(string prefab)
	{
		if (on == null || refused == null || !on.Value)
		{
			return false;
		}
		if (List(refused).Contains(prefab))
		{
			return false;
		}
		if (List(chosen).Contains(prefab))
		{
			return true;
		}
		if (automatic.Value)
		{
			return IsAutomatic(prefab);
		}
		return false;
	}

	private static bool IsAutomatic(string prefab)
	{
		if (Automatic.TryGetValue(prefab, out var value))
		{
			return value;
		}
		bool flag = false;
		GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(prefab) : null);
		if (Object.op_Implicit((Object)(object)val) && Vanilla.Count > 0 && !Vanilla.Contains(prefab) && Object.op_Implicit((Object)(object)val.GetComponent<Piece>()))
		{
			int count = Own(val.transform).Count;
			flag = count >= 1 && count <= fewest.Value;
		}
		Automatic[prefab] = flag;
		if (flag)
		{
			Plugin.Log.LogInfo((object)("Snap points added to " + prefab + " automatically (it had only a few of its own)."));
		}
		return flag;
	}

	private static List<Transform> Own(Transform root)
	{
		List<Transform> list = new List<Transform>();
		for (int i = 0; i < root.childCount; i++)
		{
			Transform child = root.GetChild(i);
			if (((Component)child).CompareTag("snappoint") && !Object.op_Implicit((Object)(object)((Component)child).GetComponent<Marker>()))
			{
				list.Add(child);
			}
		}
		return list;
	}

	private static List<KeyValuePair<string, Vector3>> PointsFor(string prefab)
	{
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0219: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Unknown result type (might be due to invalid IL or missing references)
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_026c: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_0187: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		if (Points.TryGetValue(prefab, out var value))
		{
			return value;
		}
		List<KeyValuePair<string, Vector3>> list = new List<KeyValuePair<string, Vector3>>();
		GameObject source = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(prefab) : null);
		if (Object.op_Implicit((Object)(object)source) && Box(source.transform, out var min, out var max))
		{
			List<Vector3> source2 = (from val in Own(source.transform)
				select source.transform.InverseTransformPoint(val.position)).ToList();
			float num = (min.x + max.x) / 2f;
			float num2 = (min.z + max.z) / 2f;
			float[] array = new float[2] { min.y, max.y };
			foreach (float num4 in array)
			{
				string text = ((num4 == min.y) ? "Bottom" : "Top");
				float[] array2 = new float[2] { min.z, max.z };
				foreach (float num6 in array2)
				{
					float[] array3 = new float[2] { min.x, max.x };
					foreach (float num8 in array3)
					{
						list.Add(new KeyValuePair<string, Vector3>(text + " " + ((num6 == max.z) ? "front" : "back") + " " + ((num8 == max.x) ? "right" : "left") + " corner", new Vector3(num8, num4, num6)));
					}
				}
				list.Add(new KeyValuePair<string, Vector3>(text + " front edge", new Vector3(num, num4, max.z)));
				list.Add(new KeyValuePair<string, Vector3>(text + " back edge", new Vector3(num, num4, min.z)));
				list.Add(new KeyValuePair<string, Vector3>(text + " left edge", new Vector3(min.x, num4, num2)));
				list.Add(new KeyValuePair<string, Vector3>(text + " right edge", new Vector3(max.x, num4, num2)));
				list.Add(new KeyValuePair<string, Vector3>(text + " centre", new Vector3(num, num4, num2)));
			}
			List<KeyValuePair<string, Vector3>> list2 = new List<KeyValuePair<string, Vector3>>();
			foreach (KeyValuePair<string, Vector3> point in list)
			{
				if (!source2.Any(delegate(Vector3 p)
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val = p - point.Value;
					return ((Vector3)(ref val)).sqrMagnitude < 0.0025f;
				}) && !list2.Any(delegate(KeyValuePair<string, Vector3> p)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_000d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val = p.Value - point.Value;
					return ((Vector3)(ref val)).sqrMagnitude < 0.0025f;
				}))
				{
					list2.Add(point);
				}
			}
			list = list2;
		}
		Points[prefab] = list;
		return list;
	}

	internal static string Describe(string prefab, Vector3 local)
	{
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: 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_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: 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_0056: 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_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		if (!Boxes.TryGetValue(prefab, out var value))
		{
			GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(prefab) : null);
			value = ((Object.op_Implicit((Object)(object)val) && Box(val.transform, out var min, out var max)) ? new Bounds?(new Bounds((min + max) / 2f, max - min)) : ((Bounds?)null));
			Boxes[prefab] = value;
		}
		if (!value.HasValue)
		{
			return null;
		}
		Bounds value2 = value.Value;
		string text = Side(local.y, ((Bounds)(ref value2)).min.y, ((Bounds)(ref value2)).max.y, "Bottom", "Top");
		string text2 = Side(local.z, ((Bounds)(ref value2)).min.z, ((Bounds)(ref value2)).max.z, "back", "front");
		string text3 = Side(local.x, ((Bounds)(ref value2)).min.x, ((Bounds)(ref value2)).max.x, "left", "right");
		List<string> list = new string[3] { text, text2, text3 }.Where((string word) => word != null).ToList();
		if (list.Count == 0)
		{
			return "Centre";
		}
		string text4 = string.Join(" ", list);
		text4 = char.ToUpper(text4[0]) + text4.Substring(1);
		if (list.Count != 3)
		{
			if (list.Count != 2)
			{
				return text4 + " centre";
			}
			return text4 + " edge";
		}
		return text4 + " corner";
		static string Side(float num2, float low, float high, string lowWord, string highWord)
		{
			float num = high - low;
			if (num < 0.05f)
			{
				return null;
			}
			if (num2 <= low + num * 0.2f)
			{
				return lowWord;
			}
			if (num2 >= high - num * 0.2f)
			{
				return highWord;
			}
			return null;
		}
	}

	private static bool Box(Transform root, out Vector3 min, out Vector3 max)
	{
		//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_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: 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_01d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: 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_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0132: 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_013b: 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)
		min = Vector3.positiveInfinity;
		max = Vector3.negativeInfinity;
		bool flag = false;
		Collider[] componentsInChildren = ((Component)root).GetComponentsInChildren<Collider>(true);
		Bounds bounds;
		foreach (Collider val in componentsInChildren)
		{
			if (val.isTrigger)
			{
				continue;
			}
			Collider val2 = val;
			BoxCollider val3 = (BoxCollider)(object)((val2 is BoxCollider) ? val2 : null);
			Vector3 center;
			Vector3 size;
			if (val3 == null)
			{
				SphereCollider val4 = (SphereCollider)(object)((val2 is SphereCollider) ? val2 : null);
				if (val4 == null)
				{
					CapsuleCollider val5 = (CapsuleCollider)(object)((val2 is CapsuleCollider) ? val2 : null);
					if (val5 == null)
					{
						MeshCollider val6 = (MeshCollider)(object)((val2 is MeshCollider) ? val2 : null);
						if (val6 == null || !Object.op_Implicit((Object)(object)val6.sharedMesh))
						{
							continue;
						}
						bounds = val6.sharedMesh.bounds;
						center = ((Bounds)(ref bounds)).center;
						bounds = val6.sharedMesh.bounds;
						size = ((Bounds)(ref bounds)).size;
					}
					else
					{
						center = val5.center;
						size = Vector3.one * val5.radius * 2f;
						((Vector3)(ref size))[val5.direction] = Mathf.Max(val5.height, val5.radius * 2f);
					}
				}
				else
				{
					center = val4.center;
					size = Vector3.one * val4.radius * 2f;
				}
			}
			else
			{
				center = val3.center;
				size = val3.size;
			}
			Grow(root, ((Component)val).transform, center, size, ref min, ref max);
			flag = true;
		}
		if (!flag)
		{
			MeshFilter[] componentsInChildren2 = ((Component)root).GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val7 in componentsInChildren2)
			{
				if (Object.op_Implicit((Object)(object)val7.sharedMesh))
				{
					Transform transform = ((Component)val7).transform;
					bounds = val7.sharedMesh.bounds;
					Vector3 center2 = ((Bounds)(ref bounds)).center;
					bounds = val7.sharedMesh.bounds;
					Grow(root, transform, center2, ((Bounds)(ref bounds)).size, ref min, ref max);
					flag = true;
				}
			}
		}
		if (flag)
		{
			Vector3 val8 = max - min;
			return ((Vector3)(ref val8)).sqrMagnitude > 0.0001f;
		}
		return false;
	}

	private static void Grow(Transform root, Transform part, Vector3 center, Vector3 size, ref Vector3 min, ref Vector3 max)
	{
		//IL_0004: 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_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: 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_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		for (int i = 0; i < 8; i++)
		{
			Vector3 val = center + Vector3.Scale(size * 0.5f, new Vector3((float)(((i & 1) != 0) ? 1 : (-1)), (float)(((i & 2) != 0) ? 1 : (-1)), (float)(((i & 4) != 0) ? 1 : (-1))));
			Vector3 val2 = root.InverseTransformPoint(part.TransformPoint(val));
			min = Vector3.Min(min, val2);
			max = Vector3.Max(max, val2);
		}
	}

	private static void Refresh(Piece piece)
	{
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: 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)
		//IL_00da: 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)
		if (!Object.op_Implicit((Object)(object)piece))
		{
			return;
		}
		Transform transform = ((Component)piece).transform;
		List<GameObject> list = new List<GameObject>();
		for (int i = 0; i < transform.childCount; i++)
		{
			if (Object.op_Implicit((Object)(object)((Component)transform.GetChild(i)).GetComponent<Marker>()))
			{
				list.Add(((Component)transform.GetChild(i)).gameObject);
			}
		}
		string prefabName = Utils.GetPrefabName(((Component)piece).gameObject);
		bool flag = Wants(prefabName);
		if (!flag || list.Count > 0)
		{
			if (flag)
			{
				return;
			}
			{
				foreach (GameObject item in list)
				{
					Object.Destroy((Object)(object)item);
				}
				return;
			}
		}
		foreach (KeyValuePair<string, Vector3> item2 in PointsFor(prefabName))
		{
			GameObject val = new GameObject(item2.Key)
			{
				tag = "snappoint"
			};
			val.AddComponent<Marker>();
			val.transform.SetParent(transform, false);
			val.transform.localPosition = item2.Value;
		}
	}

	private static void RefreshAll()
	{
		try
		{
			foreach (Piece item in AllPieces.Invoke().ToList())
			{
				Refresh(item);
			}
			GameObject val = (Object.op_Implicit((Object)(object)Player.m_localPlayer) ? Traverse.Create((object)Player.m_localPlayer).Field("m_placementGhost").GetValue<GameObject>() : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				Refresh(val.GetComponent<Piece>());
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Couldn't update snap points: " + ex.Message));
		}
	}

	internal static void Pick(Terminal context)
	{
		Player localPlayer = Player.m_localPlayer;
		Piece val = (Object.op_Implicit((Object)(object)localPlayer) ? localPlayer.GetHoveringPiece() : null);
		if (!Object.op_Implicit((Object)(object)val))
		{
			Say(context, "Take out the hammer and look at a built piece first.");
			return;
		}
		string prefabName = Utils.GetPrefabName(((Component)val).gameObject);
		string text = Localization.instance.Localize(val.m_name);
		HashSet<string> hashSet = List(chosen);
		HashSet<string> hashSet2 = List(refused);
		bool flag = Wants(prefabName);
		hashSet.Remove(prefabName);
		hashSet2.Remove(prefabName);
		if (flag)
		{
			hashSet2.Add(prefabName);
		}
		else
		{
			hashSet.Add(prefabName);
		}
		Save(chosen, hashSet);
		Save(refused, hashSet2);
		RefreshAll();
		if (!on.Value)
		{
			Say(context, text + ": saved, but \"Add snap points\" is off in the settings.");
			return;
		}
		if (flag)
		{
			Say(context, text + ": back to its own snap points.");
			return;
		}
		int count = PointsFor(prefabName).Count;
		Say(context, (count > 0) ? $"{text}: {count} snap points added (corners, edges and centres)." : (text + ": couldn't work out its shape, so no points were added."));
	}

	private static void Say(Terminal context, string text)
	{
		if (Object.op_Implicit((Object)(object)context))
		{
			context.AddString(text);
		}
		Player localPlayer = Player.m_localPlayer;
		if (localPlayer != null)
		{
			((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
		}
		Plugin.Log.LogInfo((object)("Snap points: " + text));
	}

	internal static void Update()
	{
		//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)
		if (on != null && key != null && on.Value && Object.op_Implicit((Object)(object)Player.m_localPlayer))
		{
			KeyboardShortcut value = key.Value;
			if (((KeyboardShortcut)(ref value)).IsDown() && !Console.IsVisible() && (!Object.op_Implicit((Object)(object)Chat.instance) || !Chat.instance.HasFocus()) && !TextInput.IsVisible() && !Menu.IsVisible() && !InventoryGui.IsVisible() && ((Character)Player.m_localPlayer).InPlaceMode())
			{
				Pick(null);
			}
		}
	}
}