Decompiled source of BurgerHouse v0.1.0

BurgerHouse.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BurgerHouse")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BurgerHouse")]
[assembly: AssemblyTitle("BurgerHouse")]
[assembly: AssemblyVersion("1.0.0.0")]
[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 BurgerHouse
{
	[BepInPlugin("com.mackenzie.burgerhouse", "BurgerHouse", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class BurgerHousePlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.mackenzie.burgerhouse";

		public const string PluginName = "BurgerHouse";

		public const string PluginVersion = "0.1.0";

		public static ManualLogSource Log;

		public static BurgerHousePlugin Instance;

		private void Awake()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Hello, Valheim! BurgerHouse is loading.");
			PrefabManager.OnVanillaPrefabsAvailable += AddFoods;
			HarbourDecor.Init(((BaseUnityPlugin)this).Config);
			new Harmony("com.mackenzie.burgerhouse").PatchAll();
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ListLocationsCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new TpHarbourCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new PlaceVendorCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new CaptureHarbourCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ScalePieceCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ReloadFoodsCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ListItemsCommand());
			try
			{
				HarbourLayout.Load();
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Couldn't load the harbour layout: {arg}");
			}
		}

		private void AddFoods()
		{
			try
			{
				Foods.RegisterAll();
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Couldn't load foods: {arg}");
			}
			PrefabManager.OnVanillaPrefabsAvailable -= AddFoods;
		}
	}
	public class ListLocationsCommand : ConsoleCommand
	{
		public override string Name => "listlocations";

		public override string Help => "[filter] List location names (e.g. `listlocations mistlands`)";

		public override void Run(string[] args)
		{
			if (!Object.op_Implicit((Object)(object)ZoneSystem.instance))
			{
				Print("Load a world first.");
				return;
			}
			string filter = ((args.Length != 0) ? string.Join(" ", args) : "");
			List<string> list = (from n in (from l in ZoneSystem.instance.m_locations
					where l?.m_enable ?? false
					select l.m_prefabName into n
					where n.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0
					select n).Distinct()
				orderby n
				select n).ToList();
			foreach (string item in list)
			{
				Print("  " + item);
			}
			Print(string.Format("{0} location(s){1}.", list.Count, (filter != "") ? (" matching '" + filter + "'") : ""));
		}

		internal static void Print(string s)
		{
			Console.instance.Print(s);
		}
	}
	public class TpHarbourCommand : ConsoleCommand
	{
		public override string Name => "tpharbour";

		public override string Help => "[locationName] Teleport to the nearest Mistlands_Harbour1 (or other location)";

		public override bool IsCheat => true;

		public override void Run(string[] args)
		{
			//IL_0040: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer) || !Object.op_Implicit((Object)(object)ZoneSystem.instance))
			{
				ListLocationsCommand.Print("Load a world first.");
				return;
			}
			string text = ((args.Length != 0) ? args[0] : "Mistlands_Harbour1");
			LocationInstance val = default(LocationInstance);
			if (!ZoneSystem.instance.FindClosestLocation(text, ((Component)localPlayer).transform.position, ref val))
			{
				ListLocationsCommand.Print("No '" + text + "' found in this world. (Check the name with `listlocations`.)");
				return;
			}
			Vector3 val2 = val.m_position + Vector3.up * 2f;
			((Character)localPlayer).TeleportTo(val2, ((Component)localPlayer).transform.rotation, true);
			ListLocationsCommand.Print($"Teleporting to {text} at {val2:F0} ({Vector3.Distance(((Component)localPlayer).transform.position, val2):F0}m away).");
		}
	}
	public class PlaceVendorCommand : ConsoleCommand
	{
		public override string Name => "placevendor";

		public override string Help => "Move the harbour vendor to where you're standing (saved to config)";

		public override bool IsCheat => true;

		public override void Run(string[] args)
		{
			ListLocationsCommand.Print(HarbourDecor.PlaceVendorAtPlayer());
		}
	}
	public class CaptureHarbourCommand : ConsoleCommand
	{
		public override string Name => "captureharbour";

		public override string Help => "[clear] Save your built pieces in this harbour as the layout for every harbour. `clear` also removes your originals.";

		public override bool IsCheat => true;

		public override void Run(string[] args)
		{
			ListLocationsCommand.Print(HarbourLayout.Capture(args.Any((string a) => a.Equals("clear", StringComparison.OrdinalIgnoreCase))));
		}
	}
	public class ReloadFoodsCommand : ConsoleCommand
	{
		public override string Name => "reloadfoods";

		public override string Help => "[foodId] Re-read the food files (config/BurgerHouse/foods) and harbour vendor settings, update everything live, and drop fresh copies in front of you";

		public override bool IsCheat => true;

		public override void Run(string[] args)
		{
			string[] array = Foods.Reload(args.FirstOrDefault()).Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				ListLocationsCommand.Print(array[i]);
			}
		}
	}
	public class ListItemsCommand : ConsoleCommand
	{
		public override string Name => "listitems";

		public override string Help => "[filter] List item prefab names (e.g. `listitems honey`), for use as a food's base or [model] parts";

		public override void Run(string[] args)
		{
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance))
			{
				ListLocationsCommand.Print("Load a world first.");
				return;
			}
			string filter = ((args.Length != 0) ? string.Join(" ", args) : "");
			List<string> list = (from n in (from i in ObjectDB.instance.m_items
					where Object.op_Implicit((Object)(object)i)
					select ((Object)i).name into n
					where n.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0
					select n).Distinct()
				orderby n
				select n).ToList();
			foreach (string item in list.Take(200))
			{
				ListLocationsCommand.Print("  " + item);
			}
			ListLocationsCommand.Print(string.Format("{0} item(s){1}{2}.", list.Count, (filter != "") ? (" matching '" + filter + "'") : "", (list.Count > 200) ? " (showing first 200; add a filter)" : ""));
		}
	}
	public class ScalePieceCommand : ConsoleCommand
	{
		public override string Name => "scalepiece";

		public override string Help => "[size] Resize the harbour layout piece you're looking at in every harbour, e.g. `scalepiece 2` (1 = normal)";

		public override bool IsCheat => true;

		public override void Run(string[] args)
		{
			ListLocationsCommand.Print(HarbourLayout.ScaleLookedAt(args.FirstOrDefault()));
		}
	}
	public class FoodDef
	{
		public string Id;

		public string Name;

		public string Description = "";

		public string Base = "CookedMeat";

		public bool Sell = true;

		public int Price = 25;

		public int BuyStack = 1;

		public float Health = 30f;

		public float Stamina = 10f;

		public float Eitr;

		public float Regen = 2f;

		public float Duration = 1200f;

		public float? Weight;

		public int? MaxStack;

		public Quaternion? IconRotation;

		public List<FoodModel.Part> Parts = new List<FoodModel.Part>();

		private const string ResourcePrefix = "BurgerHouse.foods.";

		private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

		public static string Folder => Path.Combine(Paths.ConfigPath, "BurgerHouse", "foods");

		public static List<FoodDef> LoadAll(List<string> warnings)
		{
			WriteDefaultsIfMissing();
			List<FoodDef> list = new List<FoodDef>();
			foreach (string item in Directory.GetFiles(Folder, "*.txt").OrderBy<string, string>((string p) => p, StringComparer.OrdinalIgnoreCase))
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(item);
				if (!Regex.IsMatch(fileNameWithoutExtension, "^[A-Za-z][A-Za-z0-9_]*$"))
				{
					warnings.Add(fileNameWithoutExtension + ".txt: file name must be letters/digits/underscores (it becomes the item ID), skipped");
					continue;
				}
				try
				{
					list.Add(Parse(fileNameWithoutExtension, File.ReadAllLines(item), warnings));
				}
				catch (Exception ex)
				{
					warnings.Add(fileNameWithoutExtension + ".txt: " + ex.Message);
				}
			}
			return list;
		}

		private static void WriteDefaultsIfMissing()
		{
			if (Directory.Exists(Folder) && Directory.GetFiles(Folder, "*.txt").Length != 0)
			{
				return;
			}
			Directory.CreateDirectory(Folder);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			foreach (string item in from r in executingAssembly.GetManifestResourceNames()
				where r.StartsWith("BurgerHouse.foods.")
				select r)
			{
				using Stream stream = executingAssembly.GetManifestResourceStream(item);
				File.WriteAllText(Path.Combine(Folder, item.Substring("BurgerHouse.foods.".Length)), new StreamReader(stream).ReadToEnd());
			}
		}

		private static FoodDef Parse(string id, string[] lines, List<string> warnings)
		{
			//IL_0456: Unknown result type (might be due to invalid IL or missing references)
			FoodDef foodDef = new FoodDef
			{
				Id = id,
				Name = id
			};
			bool flag = false;
			for (int i = 0; i < lines.Length; i++)
			{
				string text = StripComment(lines[i]).Trim();
				if (text == "")
				{
					continue;
				}
				string text2 = $"{id}.txt line {i + 1}";
				if (text.Equals("[model]", StringComparison.OrdinalIgnoreCase))
				{
					flag = true;
					continue;
				}
				if (flag)
				{
					string error;
					FoodModel.Part part = FoodModel.ParsePart(text, out error);
					if (part != null)
					{
						foodDef.Parts.Add(part);
					}
					else
					{
						warnings.Add(text2 + ": " + error);
					}
					continue;
				}
				int num = text.IndexOf('=');
				if (num < 0)
				{
					warnings.Add(text2 + ": expected 'key = value'");
					continue;
				}
				string text3 = text.Substring(0, num).Trim().ToLowerInvariant();
				string text4 = text.Substring(num + 1).Trim();
				try
				{
					switch (text3)
					{
					case "name":
						foodDef.Name = text4;
						break;
					case "description":
						foodDef.Description = text4.Replace("\\n", "\n");
						break;
					case "base":
						foodDef.Base = text4;
						break;
					case "sell":
						foodDef.Sell = !Regex.IsMatch(text4, "^(no|false|0)$", RegexOptions.IgnoreCase);
						break;
					case "price":
						foodDef.Price = Positive(text4);
						break;
					case "buy_stack":
						foodDef.BuyStack = Positive(text4);
						break;
					case "health":
						foodDef.Health = F(text4);
						break;
					case "stamina":
						foodDef.Stamina = F(text4);
						break;
					case "eitr":
						foodDef.Eitr = F(text4);
						break;
					case "regen":
						foodDef.Regen = F(text4);
						break;
					case "duration":
						foodDef.Duration = F(text4);
						break;
					case "weight":
						foodDef.Weight = F(text4);
						break;
					case "max_stack":
						foodDef.MaxStack = Positive(text4);
						break;
					case "icon":
					{
						float[] array = text4.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).Select(F).ToArray();
						if (array.Length == 3)
						{
							foodDef.IconRotation = Quaternion.Euler(array[0], array[1], array[2]);
						}
						else
						{
							warnings.Add(text2 + ": icon needs 3 numbers (rotX rotY rotZ)");
						}
						break;
					}
					default:
						warnings.Add(text2 + ": unknown setting '" + text3 + "'");
						break;
					}
				}
				catch (FormatException ex)
				{
					warnings.Add(text2 + ": '" + text4 + "' isn't valid for " + text3 + (ex.Message.StartsWith("must") ? (" (" + ex.Message + ")") : "") + ", using the default");
				}
				catch (OverflowException)
				{
					warnings.Add(text2 + ": '" + text4 + "' is too big for " + text3 + ", using the default");
				}
			}
			return foodDef;
		}

		private static string StripComment(string line)
		{
			string text = line.TrimStart();
			if (text.StartsWith("#"))
			{
				return "";
			}
			string text2 = text.ToLowerInvariant();
			if (text2.StartsWith("name") || text2.StartsWith("description"))
			{
				return line;
			}
			int num = line.IndexOf('#');
			if (num < 0)
			{
				return line;
			}
			return line.Substring(0, num);
		}

		private static float F(string s)
		{
			return float.Parse(s, NumberStyles.Float, Inv);
		}

		private static int Positive(string s)
		{
			int num = int.Parse(s, NumberStyles.Integer, Inv);
			if (num < 1)
			{
				throw new FormatException("must be 1 or more");
			}
			return num;
		}

		public void ApplyStats(SharedData shared)
		{
			shared.m_name = Name;
			shared.m_description = Description;
			shared.m_food = Health;
			shared.m_foodStamina = Stamina;
			shared.m_foodEitr = Eitr;
			shared.m_foodRegen = Regen;
			shared.m_foodBurnTime = Duration;
			if (Weight.HasValue)
			{
				shared.m_weight = Weight.Value;
			}
			if (MaxStack.HasValue)
			{
				shared.m_maxStackSize = MaxStack.Value;
			}
		}
	}
	public static class FoodModel
	{
		public class Part
		{
			public string donor;

			public Vector3 pos;

			public Vector3 rot;

			public Vector3 scale;
		}

		private const string ModelChildName = "BurgerHouse_Model";

		private static readonly Dictionary<GameObject, Sprite[]> OriginalIcons = new Dictionary<GameObject, Sprite[]>();

		public static Part ParsePart(string line, out string error)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			error = null;
			string[] array = line.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
			float[] array2 = new float[array.Length - 1];
			for (int i = 1; i < array.Length; i++)
			{
				if (!float.TryParse(array[i], NumberStyles.Float, CultureInfo.InvariantCulture, out array2[i - 1]))
				{
					error = "'" + array[i] + "' isn't a number";
					return null;
				}
			}
			if (array2.Length != 7 && array2.Length != 9)
			{
				error = $"expected: donorPrefab x y z rotX rotY rotZ scale (or sx sy sz), got {array2.Length} numbers";
				return null;
			}
			return new Part
			{
				donor = array[0],
				pos = new Vector3(array2[0], array2[1], array2[2]),
				rot = new Vector3(array2[3], array2[4], array2[5]),
				scale = (Vector3)((array2.Length == 7) ? (Vector3.one * array2[6]) : new Vector3(array2[6], array2[7], array2[8]))
			};
		}

		public static string Build(GameObject itemPrefab, FoodDef def)
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: 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_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			SharedData shared = itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared;
			if (!OriginalIcons.ContainsKey(itemPrefab))
			{
				OriginalIcons[itemPrefab] = shared.m_icons;
			}
			Transform val = itemPrefab.transform.Find("BurgerHouse_Model");
			if (Object.op_Implicit((Object)(object)val))
			{
				Object.DestroyImmediate((Object)(object)((Component)val).gameObject);
			}
			bool flag = def.Parts.Count > 0;
			Renderer[] componentsInChildren = itemPrefab.GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].enabled = !flag;
			}
			if (!flag)
			{
				shared.m_icons = OriginalIcons[itemPrefab];
				return def.Id + ": no [model] parts, using the look of '" + def.Base + "'.";
			}
			Transform transform = new GameObject("BurgerHouse_Model").transform;
			transform.SetParent(itemPrefab.transform, false);
			int num = 0;
			foreach (Part part in def.Parts)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab(part.donor);
				if (!Object.op_Implicit((Object)(object)prefab))
				{
					list.Add("unknown prefab '" + part.donor + "'");
					continue;
				}
				Transform transform2 = new GameObject(part.donor).transform;
				transform2.SetParent(transform, false);
				transform2.localPosition = part.pos;
				transform2.localRotation = Quaternion.Euler(part.rot);
				transform2.localScale = part.scale;
				int num2 = CopyVisuals(prefab.transform, transform2);
				if (num2 == 0)
				{
					list.Add("'" + part.donor + "' has no visible meshes");
				}
				num += num2;
			}
			RenderIcon(shared, transform, def.IconRotation, list);
			string text = $"{def.Id}: {def.Parts.Count} part(s), {num} mesh(es).";
			if (list.Count > 0)
			{
				text = text + " Warnings: " + string.Join("; ", list);
			}
			return text;
		}

		private static int CopyVisuals(Transform donorRoot, Transform target)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			MeshRenderer[] componentsInChildren = ((Component)donorRoot).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (IsVisibleInPrefab(((Component)val).transform, donorRoot) && ((Renderer)val).enabled && !Regex.IsMatch(((Object)val).name, "_?LOD[1-9]"))
				{
					MeshFilter component = ((Component)val).GetComponent<MeshFilter>();
					if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.sharedMesh))
					{
						GameObject val2 = new GameObject(((Object)val).name);
						val2.transform.SetParent(target, false);
						val2.transform.localPosition = donorRoot.InverseTransformPoint(((Component)val).transform.position);
						val2.transform.localRotation = Quaternion.Inverse(donorRoot.rotation) * ((Component)val).transform.rotation;
						val2.transform.localScale = Divide(((Component)val).transform.lossyScale, donorRoot.lossyScale);
						val2.layer = ((Component)val).gameObject.layer;
						val2.AddComponent<MeshFilter>().sharedMesh = component.sharedMesh;
						((Renderer)val2.AddComponent<MeshRenderer>()).sharedMaterials = ((Renderer)val).sharedMaterials;
						num++;
					}
				}
			}
			return num;
		}

		private static bool IsVisibleInPrefab(Transform t, Transform root)
		{
			while (Object.op_Implicit((Object)(object)t) && (Object)(object)t != (Object)(object)root)
			{
				if (!((Component)t).gameObject.activeSelf)
				{
					return false;
				}
				t = t.parent;
			}
			return true;
		}

		private static Vector3 Divide(Vector3 a, Vector3 b)
		{
			//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_001b: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_0044: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3((b.x != 0f) ? (a.x / b.x) : a.x, (b.y != 0f) ? (a.y / b.y) : a.y, (b.z != 0f) ? (a.z / b.z) : a.z);
		}

		private static void RenderIcon(SharedData shared, Transform model, Quaternion? rotation, List<string> warnings)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: 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_0050: 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_0067: Expected O, but got Unknown
			GameObject val = new GameObject("BurgerHouse_IconRender");
			try
			{
				Object.Instantiate<GameObject>(((Component)model).gameObject, val.transform).transform.localPosition = Vector3.zero;
				RenderRequest val2 = new RenderRequest(val)
				{
					Rotation = (Quaternion)(((??)rotation) ?? RenderManager.IsometricRotation),
					Width = 128,
					Height = 128
				};
				Sprite val3 = RenderManager.Instance.Render(val2);
				if (Object.op_Implicit((Object)(object)val3))
				{
					shared.m_icons = (Sprite[])(object)new Sprite[1] { val3 };
				}
				else
				{
					warnings.Add("icon render returned nothing");
				}
			}
			finally
			{
				Object.DestroyImmediate((Object)(object)val);
			}
		}
	}
	public static class Foods
	{
		public static readonly Dictionary<string, CustomItem> Items = new Dictionary<string, CustomItem>();

		public static List<FoodDef> Defs = new List<FoodDef>();

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

		public static IEnumerable<(FoodDef def, CustomItem item)> ForSale => from d in Defs
			where d.Sell && Items.ContainsKey(d.Id)
			select (d: d, Items[d.Id]);

		public static void RegisterAll()
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			List<string> list = new List<string>();
			Defs = FoodDef.LoadAll(list);
			foreach (FoodDef def in Defs)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab(def.Base);
				if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)prefab.GetComponent<ItemDrop>()))
				{
					list.Add(def.Id + ": base '" + def.Base + "' isn't an item (find names with `listitems`), skipped");
					continue;
				}
				if (Object.op_Implicit((Object)(object)PrefabManager.Instance.GetPrefab(def.Id)))
				{
					list.Add(def.Id + ": an item/prefab with that name already exists in the game; rename the file (e.g. BH_" + def.Id + ".txt), skipped");
					continue;
				}
				CustomItem val = new CustomItem(def.Id, def.Base, new ItemConfig
				{
					Name = def.Name,
					Description = def.Description
				});
				def.ApplyStats(val.ItemDrop.m_itemData.m_shared);
				if (!ItemManager.Instance.AddItem(val))
				{
					list.Add(def.Id + ": Jotunn refused to add the item (see the log above), skipped");
					continue;
				}
				Items[def.Id] = val;
				RegisteredBase[def.Id] = def.Base;
				try
				{
					BurgerHousePlugin.Log.LogInfo((object)FoodModel.Build(val.ItemPrefab, def));
				}
				catch (Exception ex)
				{
					list.Add(def.Id + ": model failed: " + ex.Message);
				}
				BurgerHousePlugin.Log.LogInfo((object)("Added food '" + def.Id + "' (" + def.Name + "). Try: spawn " + def.Id));
			}
			foreach (string item in list)
			{
				BurgerHousePlugin.Log.LogWarning((object)("Foods: " + item));
			}
		}

		public static string Reload(string onlyId)
		{
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			((BaseUnityPlugin)BurgerHousePlugin.Instance).Config.Reload();
			Defs = FoodDef.LoadAll(list2);
			foreach (FoodDef def in Defs)
			{
				if (!Items.TryGetValue(def.Id, out var value))
				{
					list.Add(def.Id + ": new food, restart the game to add it.");
					continue;
				}
				if (RegisteredBase[def.Id] != def.Base)
				{
					list.Add(def.Id + ": base changed to '" + def.Base + "', takes effect after a restart.");
				}
				def.ApplyStats(value.ItemDrop.m_itemData.m_shared);
				try
				{
					list.Add(FoodModel.Build(value.ItemPrefab, def));
				}
				catch (Exception ex)
				{
					list2.Add(def.Id + ": model failed: " + ex.Message);
				}
			}
			foreach (string item in Items.Keys.Where((string id) => Defs.All((FoodDef d) => d.Id != id)))
			{
				list.Add(item + ": file removed; it stays in the game until you restart.");
			}
			HarbourDecor.RefreshTraders();
			list.Add($"Harbour vendor updated ({ForSale.Count()} food(s) for sale).");
			DropPreviews(onlyId, list);
			foreach (string item2 in list2)
			{
				list.Add("Warning: " + item2);
			}
			return string.Join("\n", list);
		}

		private static void DropPreviews(string onlyId, List<string> lines)
		{
			//IL_00cf: 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_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: 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_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)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: 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)
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return;
			}
			List<KeyValuePair<string, CustomItem>> list = Items.Where((KeyValuePair<string, CustomItem> kv) => string.IsNullOrEmpty(onlyId) || kv.Key.Equals(onlyId, StringComparison.OrdinalIgnoreCase)).ToList();
			if (list.Count == 0)
			{
				lines.Add("No food with ID '" + onlyId + "'.");
				return;
			}
			HashSet<string> hashSet = new HashSet<string>(list.Select((KeyValuePair<string, CustomItem> kv) => kv.Key));
			int num = 0;
			ItemDrop[] array = Object.FindObjectsByType<ItemDrop>((FindObjectsSortMode)0);
			foreach (ItemDrop val in array)
			{
				string item = ((Object)val).name.Replace("(Clone)", "").Trim();
				if (hashSet.Contains(item) && !(Vector3.Distance(((Component)val).transform.position, ((Component)localPlayer).transform.position) > 15f))
				{
					ZNetView component = ((Component)val).GetComponent<ZNetView>();
					if (Object.op_Implicit((Object)(object)component) && component.IsValid())
					{
						component.ClaimOwnership();
						ZNetScene.instance.Destroy(((Component)val).gameObject);
						num++;
					}
				}
			}
			Transform transform = ((Component)localPlayer).transform;
			for (int num3 = 0; num3 < list.Count; num3++)
			{
				float num4 = ((float)num3 - (float)(list.Count - 1) / 2f) * 0.7f;
				Object.Instantiate<GameObject>(list[num3].Value.ItemPrefab, transform.position + transform.forward * 1.5f + transform.right * num4 + Vector3.up, Quaternion.identity);
			}
			lines.Add(string.Format("Dropped {0} fresh one(s) in front of you{1}.", list.Count, (num > 0) ? $" (removed {num} old nearby)" : ""));
		}
	}
	public static class HarbourDecor
	{
		[HarmonyPatch(typeof(Location), "Awake")]
		private static class LocationAwakePatch
		{
			private static void Postfix(Location __instance)
			{
				if (!((Object)__instance).name.StartsWith("Mistlands_Harbour1"))
				{
					return;
				}
				try
				{
					SpawnVendorIn(((Component)__instance).transform);
				}
				catch (Exception arg)
				{
					BurgerHousePlugin.Log.LogError((object)$"Failed to add harbour vendor: {arg}");
				}
				try
				{
					HarbourLayout.SpawnIn(((Component)__instance).transform);
				}
				catch (Exception arg2)
				{
					BurgerHousePlugin.Log.LogError((object)$"Failed to add harbour layout: {arg2}");
				}
			}
		}

		public const string HarbourLocation = "Mistlands_Harbour1";

		public const string VendorObjectName = "BurgerHouse_HarbourVendor";

		private static ConfigEntry<float> _x;

		private static ConfigEntry<float> _y;

		private static ConfigEntry<float> _z;

		private static ConfigEntry<float> _rotY;

		private static ConfigEntry<string> _name;

		private static ConfigEntry<string> _greets;

		private static ConfigEntry<string> _goodbyes;

		private static ConfigEntry<string> _startTrade;

		private static ConfigEntry<string> _buy;

		private static ConfigEntry<string> _talk;

		private static GameObject _vendorBlueprint;

		private static GameObject _blueprintContainer;

		public static void Init(ConfigFile config)
		{
			_name = config.Bind<string>("HarbourVendor", "Name", "Burger Master", "The shopkeeper's name");
			_greets = config.Bind<string>("HarbourVendor", "Greetings", "Ah, a surface-dweller! Hungry?|Welcome to the grill, friend. Mind the mist.|You look like a Seeker chased you here. Have a burger!|Smell that? That's this morning's catch.", "Said when you walk up. Separate multiple lines with |  (one is picked at random). `reloadfoods` applies changes live.");
			_goodbyes = config.Bind<string>("HarbourVendor", "Goodbyes", "Come back if the mist doesn't eat you first!|Watch the skies. Gjall don't share.|Tell the Seekers I said hello. I cooked their cousins.", "Said when you walk away. Separate multiple lines with |  (one is picked at random). `reloadfoods` applies changes live.");
			_startTrade = config.Bind<string>("HarbourVendor", "OpenShop", "Fresh off the grill! Mostly dead.|Everything on this menu tried to kill me once.|Seeker patties, hand-caught! Mind the pincers.", "Said when you open the shop. Separate multiple lines with |  (one is picked at random). `reloadfoods` applies changes live.");
			_buy = config.Bind<string>("HarbourVendor", "Bought", "A fine choice! Chew fast, it may still twitch.|Good! Now you eat like a Dvergr.|The crunchy bits are legs. Very nutritious.", "Said when you buy something. Separate multiple lines with |  (one is picked at random). `reloadfoods` applies changes live.");
			_talk = config.Bind<string>("HarbourVendor", "Idle", "Burgers! Fresh Seeker burgers!|Lost two fingers catching today's special. Worth it.|The mist hides many things. Most taste good on a bun.|Ticks make a lovely sauce, once you pry them off.|A Gjall burger? Ha! One day...", "Said now and then while you're nearby. Separate multiple lines with |  (one is picked at random). `reloadfoods` applies changes live.");
			_x = config.Bind<float>("HarbourVendor", "OffsetX", 2.05f, "Position relative to the harbour's center (set in game with `placevendor`)");
			_y = config.Bind<float>("HarbourVendor", "OffsetY", 1.98f, "Height relative to the harbour's center");
			_z = config.Bind<float>("HarbourVendor", "OffsetZ", -16.78f, "Position relative to the harbour's center");
			_rotY = config.Bind<float>("HarbourVendor", "RotationY", 177.46f, "Facing direction (degrees) relative to the harbour");
		}

		private static Transform SpawnVendorIn(Transform harbour)
		{
			//IL_0074: 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)
			Transform val = harbour.Find("BurgerHouse_HarbourVendor");
			if (Object.op_Implicit((Object)(object)val))
			{
				return val;
			}
			if (!Object.op_Implicit((Object)(object)_vendorBlueprint))
			{
				_vendorBlueprint = BuildVendor();
			}
			if (!Object.op_Implicit((Object)(object)_vendorBlueprint))
			{
				return null;
			}
			GameObject obj = Object.Instantiate<GameObject>(_vendorBlueprint, harbour);
			((Object)obj).name = "BurgerHouse_HarbourVendor";
			obj.transform.localPosition = new Vector3(_x.Value, _y.Value, _z.Value);
			obj.transform.localRotation = Quaternion.Euler(0f, _rotY.Value, 0f);
			return obj.transform;
		}

		private static GameObject BuildVendor()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			GameObject val = FindHaldor();
			if (!Object.op_Implicit((Object)(object)val))
			{
				BurgerHousePlugin.Log.LogError((object)"Couldn't find a vanilla trader (Haldor) to copy.");
				return null;
			}
			if (!Object.op_Implicit((Object)(object)_blueprintContainer))
			{
				_blueprintContainer = new GameObject("BurgerHouse_Blueprints");
				_blueprintContainer.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)_blueprintContainer);
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, _blueprintContainer.transform);
			((Object)val2).name = "BurgerHouse_HarbourVendor";
			foreach (Component item in from c in val2.GetComponentsInChildren<Component>(true)
				where Object.op_Implicit((Object)(object)c) && ((object)c).GetType().Name.StartsWith("ZSync")
				select c)
			{
				Object.DestroyImmediate((Object)(object)item);
			}
			ZNetView[] componentsInChildren = val2.GetComponentsInChildren<ZNetView>(true);
			for (int num = 0; num < componentsInChildren.Length; num++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[num]);
			}
			Trader componentInChildren = val2.GetComponentInChildren<Trader>(true);
			componentInChildren.m_useItems = new List<TraderUseItem>();
			componentInChildren.m_randomTalkConditionals = new List<ConditionalDialog>();
			ApplyTraderSettings(componentInChildren);
			return val2;
		}

		private static void ApplyTraderSettings(Trader trader)
		{
			trader.m_name = _name.Value;
			trader.m_items = Foods.ForSale.Select<(FoodDef, CustomItem), TradeItem>((Func<(FoodDef, CustomItem), TradeItem>)(((FoodDef def, CustomItem item) f) => new TradeItem
			{
				m_prefab = f.item.ItemDrop,
				m_stack = f.def.BuyStack,
				m_price = f.def.Price,
				m_requiredGlobalKey = ""
			})).ToList();
			trader.m_randomGreets = Lines(_greets);
			trader.m_randomGoodbye = Lines(_goodbyes);
			trader.m_randomStartTrade = Lines(_startTrade);
			trader.m_randomBuy = Lines(_buy);
			trader.m_randomTalk = Lines(_talk);
		}

		private static List<string> Lines(ConfigEntry<string> e)
		{
			return (from s in e.Value.Split('|')
				select s.Trim() into s
				where s != ""
				select s).ToList();
		}

		public static void RefreshTraders()
		{
			if (Object.op_Implicit((Object)(object)_vendorBlueprint))
			{
				ApplyTraderSettings(_vendorBlueprint.GetComponentInChildren<Trader>(true));
			}
			Location[] array = Object.FindObjectsByType<Location>((FindObjectsSortMode)0);
			foreach (Location val in array)
			{
				if (((Object)val).name.StartsWith("Mistlands_Harbour1"))
				{
					Transform val2 = ((Component)val).transform.Find("BurgerHouse_HarbourVendor");
					Trader val3 = (Object.op_Implicit((Object)(object)val2) ? ((Component)val2).GetComponentInChildren<Trader>(true) : null);
					if (Object.op_Implicit((Object)(object)val3))
					{
						ApplyTraderSettings(val3);
					}
				}
			}
		}

		private static GameObject FindHaldor()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = PrefabManager.Instance.GetPrefab("Haldor");
			Trader val = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponentInChildren<Trader>(true) : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				return ((Component)val).gameObject;
			}
			ZoneLocation zoneLocation = ZoneManager.Instance.GetZoneLocation("Vendor_BlackForest");
			if (zoneLocation == null)
			{
				return null;
			}
			zoneLocation.m_prefab.Load();
			val = zoneLocation.m_prefab.Asset.GetComponentInChildren<Trader>(true);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return ((Component)val).gameObject;
		}

		public static Location CurrentHarbour(out string error)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			error = null;
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				error = "No local player.";
				return null;
			}
			Location location = Location.GetLocation(((Component)localPlayer).transform.position, false);
			if (!Object.op_Implicit((Object)(object)location) || !((Object)location).name.StartsWith("Mistlands_Harbour1"))
			{
				error = "You're not inside a Mistlands_Harbour1 (found: " + (Object.op_Implicit((Object)(object)location) ? ((Object)location).name : "nothing") + ").";
				return null;
			}
			return location;
		}

		public static string PlaceVendorAtPlayer()
		{
			//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_0030: 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_0044: 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_0076: 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_00df: 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)
			string error;
			Location val = CurrentHarbour(out error);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return error;
			}
			Transform transform = ((Component)val).transform;
			Transform transform2 = ((Component)Player.m_localPlayer).transform;
			Vector3 val2 = transform.InverseTransformPoint(transform2.position);
			float v = Mathf.Repeat(transform2.eulerAngles.y + 180f - transform.eulerAngles.y, 360f);
			_x.Value = Round(val2.x);
			_y.Value = Round(val2.y);
			_z.Value = Round(val2.z);
			_rotY.Value = Round(v);
			Transform val3 = SpawnVendorIn(transform);
			if (Object.op_Implicit((Object)(object)val3))
			{
				val3.localPosition = new Vector3(_x.Value, _y.Value, _z.Value);
				val3.localRotation = Quaternion.Euler(0f, _rotY.Value, 0f);
			}
			return $"Vendor placed. Saved OffsetX={_x.Value} OffsetY={_y.Value} OffsetZ={_z.Value} RotationY={_rotY.Value}";
		}

		private static float Round(float v)
		{
			return Mathf.Round(v * 100f) / 100f;
		}
	}
	public static class HarbourLayout
	{
		public class Entry
		{
			public string prefab;

			public Vector3 pos;

			public Vector3 rot;

			public float scale = 1f;

			public string text;
		}

		public class Layout
		{
			public List<Entry> pieces = new List<Entry>();
		}

		public const string ContainerName = "BurgerHouse_Layout";

		public const string FileName = "BurgerHouse.harbour_layout.txt";

		private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

		private static Layout _layout = new Layout();

		private static readonly Dictionary<string, GameObject> Blueprints = new Dictionary<string, GameObject>();

		private static GameObject _blueprintContainer;

		private static string FilePath => Path.Combine(Paths.ConfigPath, "BurgerHouse.harbour_layout.txt");

		private static string Escape(string s)
		{
			return s.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\n", "\\n")
				.Replace("\r", "");
		}

		private static string Unescape(string s)
		{
			StringBuilder stringBuilder = new StringBuilder(s.Length);
			for (int i = 0; i < s.Length; i++)
			{
				if (s[i] != '\\' || i + 1 >= s.Length)
				{
					stringBuilder.Append(s[i]);
					continue;
				}
				char c = s[++i];
				stringBuilder.Append(c switch
				{
					't' => '\t', 
					'n' => '\n', 
					_ => c, 
				});
			}
			return stringBuilder.ToString();
		}

		private static string Serialize(Layout layout)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("# BurgerHouse harbour layout. One piece per line, tab-separated:");
			stringBuilder.AppendLine("# prefab, position (x y z) and rotation (x y z) relative to the harbour, then optional scale=N and text=...");
			foreach (Entry piece in layout.pieces)
			{
				stringBuilder.Append(piece.prefab);
				float[] array = new float[6]
				{
					piece.pos.x,
					piece.pos.y,
					piece.pos.z,
					piece.rot.x,
					piece.rot.y,
					piece.rot.z
				};
				foreach (float num in array)
				{
					stringBuilder.Append('\t').Append(num.ToString("0.###", Inv));
				}
				if (!Mathf.Approximately(piece.scale, 1f))
				{
					stringBuilder.Append("\tscale=").Append(piece.scale.ToString("0.###", Inv));
				}
				if (!string.IsNullOrEmpty(piece.text))
				{
					stringBuilder.Append("\ttext=").Append(Escape(piece.text));
				}
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}

		private static Layout Deserialize(string text)
		{
			//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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			Layout layout = new Layout();
			int num = 0;
			string[] array = text.Split('\n');
			foreach (string obj in array)
			{
				num++;
				string text2 = obj.TrimEnd('\r');
				if (text2.Trim() == "" || text2.TrimStart().StartsWith("#"))
				{
					continue;
				}
				try
				{
					Match m = Regex.Match(text2, string.Concat("^\\s*(\\S+)", string.Concat(Enumerable.Repeat("\\s+(\\S+)", 6)), "\\s*(.*)$"));
					if (!m.Success)
					{
						throw new FormatException("expected: prefab x y z rotX rotY rotZ");
					}
					Entry entry = new Entry
					{
						prefab = m.Groups[1].Value,
						pos = new Vector3(F(1), F(2), F(3)),
						rot = new Vector3(F(4), F(5), F(6))
					};
					string value = m.Groups[8].Value;
					int num2 = value.IndexOf("text=", StringComparison.Ordinal);
					Match match = Regex.Match((num2 >= 0) ? value.Substring(0, num2) : value, "scale=([-+0-9.eE]+)");
					if (match.Success)
					{
						entry.scale = float.Parse(match.Groups[1].Value, Inv);
						if (entry.scale <= 0f)
						{
							throw new FormatException("scale must be above 0");
						}
					}
					if (num2 >= 0)
					{
						entry.text = Unescape(value.Substring(num2 + "text=".Length));
					}
					else if (!match.Success && value.Trim() != "")
					{
						entry.text = Unescape(value.Trim());
					}
					layout.pieces.Add(entry);
					float F(int num3)
					{
						return float.Parse(m.Groups[num3 + 1].Value, Inv);
					}
				}
				catch (Exception ex)
				{
					BurgerHousePlugin.Log.LogWarning((object)$"Harbour layout line {num} skipped ({ex.Message}): {text2}");
				}
			}
			return layout;
		}

		public static void Load()
		{
			string text = null;
			string text2 = null;
			if (File.Exists(FilePath))
			{
				text = File.ReadAllText(FilePath);
				text2 = FilePath;
			}
			else
			{
				using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BurgerHouse.BurgerHouse.harbour_layout.txt");
				if (stream != null)
				{
					text = new StreamReader(stream).ReadToEnd();
					text2 = "built-in default";
				}
			}
			_layout = ((text != null) ? Deserialize(text) : new Layout());
			BurgerHousePlugin.Log.LogInfo((object)string.Format("Harbour layout: {0} piece(s){1}.", _layout.pieces.Count, (text2 != null) ? (" from " + text2) : ""));
		}

		public static void SpawnIn(Transform harbour)
		{
			//IL_0029: 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_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_00f2: 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)
			if (_layout.pieces.Count == 0 || Object.op_Implicit((Object)(object)harbour.Find("BurgerHouse_Layout")))
			{
				return;
			}
			Transform transform = new GameObject("BurgerHouse_Layout").transform;
			transform.SetParent(harbour, false);
			for (int i = 0; i < _layout.pieces.Count; i++)
			{
				Entry entry = _layout.pieces[i];
				GameObject blueprint = GetBlueprint(entry.prefab);
				if (!Object.op_Implicit((Object)(object)blueprint))
				{
					continue;
				}
				bool forceDisableInit = ZNetView.m_forceDisableInit;
				bool forceDisableTerrainOps = TerrainOp.m_forceDisableTerrainOps;
				ZNetView.m_forceDisableInit = true;
				TerrainOp.m_forceDisableTerrainOps = true;
				GameObject val;
				try
				{
					val = Object.Instantiate<GameObject>(blueprint, transform);
				}
				finally
				{
					ZNetView.m_forceDisableInit = forceDisableInit;
					TerrainOp.m_forceDisableTerrainOps = forceDisableTerrainOps;
				}
				((Object)val).name = $"{entry.prefab}#{i}";
				val.transform.localPosition = entry.pos;
				val.transform.localRotation = Quaternion.Euler(entry.rot);
				val.transform.localScale = blueprint.transform.localScale * entry.scale;
				Sign componentInChildren = val.GetComponentInChildren<Sign>(true);
				if (Object.op_Implicit((Object)(object)componentInChildren))
				{
					if (Object.op_Implicit((Object)(object)componentInChildren.m_textWidget) && !string.IsNullOrEmpty(entry.text))
					{
						((TMP_Text)componentInChildren.m_textWidget).text = entry.text;
					}
					Object.Destroy((Object)(object)componentInChildren);
				}
			}
		}

		private static GameObject GetBlueprint(string prefabName)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			if (Blueprints.TryGetValue(prefabName, out var value))
			{
				return value;
			}
			if (!Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return null;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
			if (!Object.op_Implicit((Object)(object)prefab))
			{
				BurgerHousePlugin.Log.LogWarning((object)("Harbour layout: unknown prefab '" + prefabName + "', skipping."));
				Blueprints[prefabName] = null;
				return null;
			}
			if (!Object.op_Implicit((Object)(object)_blueprintContainer))
			{
				_blueprintContainer = new GameObject("BurgerHouse_LayoutBlueprints");
				_blueprintContainer.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)_blueprintContainer);
			}
			value = Object.Instantiate<GameObject>(prefab, _blueprintContainer.transform);
			((Object)value).name = prefabName;
			WearNTear[] componentsInChildren = value.GetComponentsInChildren<WearNTear>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			Piece[] componentsInChildren2 = value.GetComponentsInChildren<Piece>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			ItemDrop[] componentsInChildren3 = value.GetComponentsInChildren<ItemDrop>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				MakeStaticPiece(componentsInChildren3[i]);
			}
			Fireplace[] componentsInChildren4 = value.GetComponentsInChildren<Fireplace>(true);
			for (int i = 0; i < componentsInChildren4.Length; i++)
			{
				LightForever(componentsInChildren4[i]);
			}
			MonoBehaviour[] componentsInChildren5 = value.GetComponentsInChildren<MonoBehaviour>(true);
			foreach (MonoBehaviour val in componentsInChildren5)
			{
				if (Object.op_Implicit((Object)(object)val) && (val is Interactable || val is Hoverable) && !(val is Sign))
				{
					Object.DestroyImmediate((Object)(object)val);
				}
			}
			Blueprints[prefabName] = value;
			return value;
		}

		private static void MakeStaticPiece(ItemDrop drop)
		{
			GameObject gameObject = ((Component)drop).gameObject;
			if (Object.op_Implicit((Object)(object)drop.m_pieceEnableObj))
			{
				drop.m_pieceEnableObj.SetActive(true);
			}
			if (Object.op_Implicit((Object)(object)drop.m_pieceDisabledObj))
			{
				drop.m_pieceDisabledObj.SetActive(false);
			}
			Collider componentInChildren = gameObject.GetComponentInChildren<Collider>(true);
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				((Component)componentInChildren).gameObject.layer = LayerMask.NameToLayer("piece");
			}
			Object.DestroyImmediate((Object)(object)drop);
			Floating[] components = gameObject.GetComponents<Floating>();
			for (int i = 0; i < components.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components[i]);
			}
			foreach (Component item in from c in gameObject.GetComponents<Component>()
				where Object.op_Implicit((Object)(object)c) && ((object)c).GetType().Name.StartsWith("ZSync")
				select c)
			{
				Object.DestroyImmediate((Object)(object)item);
			}
			Rigidbody[] components2 = gameObject.GetComponents<Rigidbody>();
			for (int i = 0; i < components2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components2[i]);
			}
		}

		private static void LightForever(Fireplace fire)
		{
			Set(fire.m_enabledObject, on: true);
			Set(fire.m_enabledObjectHigh, on: true);
			Set(fire.m_enabledObjectLow, on: false);
			Set(fire.m_fullObject, on: true);
			Set(fire.m_halfObject, on: false);
			Set(fire.m_emptyObject, on: false);
			static void Set(GameObject go, bool on)
			{
				if (Object.op_Implicit((Object)(object)go))
				{
					go.SetActive(on);
				}
			}
		}

		private static void RefreshLoadedHarbours()
		{
			Location[] array = Object.FindObjectsByType<Location>((FindObjectsSortMode)0);
			foreach (Location val in array)
			{
				if (((Object)val).name.StartsWith("Mistlands_Harbour1"))
				{
					Transform val2 = ((Component)val).transform.Find("BurgerHouse_Layout");
					if (Object.op_Implicit((Object)(object)val2))
					{
						((Object)val2).name = "BurgerHouse_Layout_old";
						Object.Destroy((Object)(object)((Component)val2).gameObject);
					}
					SpawnIn(((Component)val).transform);
				}
			}
		}

		public static string Capture(bool clearOriginals)
		{
			//IL_001a: 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_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)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: 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_017a: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return "No local player.";
			}
			Location location = Location.GetLocation(((Component)localPlayer).transform.position, false);
			if (!Object.op_Implicit((Object)(object)location) || !((Object)location).name.StartsWith("Mistlands_Harbour1"))
			{
				return "Stand inside a Mistlands_Harbour1 first (found: " + (Object.op_Implicit((Object)(object)location) ? ((Object)location).name : "nothing") + ").";
			}
			Transform transform = ((Component)location).transform;
			List<Piece> list = new List<Piece>();
			Piece.GetAllPiecesInRadius(transform.position, location.GetMaxRadius(), list);
			Layout layout = new Layout();
			List<GameObject> list2 = new List<GameObject>();
			foreach (Piece item in list.Where((Piece p) => Object.op_Implicit((Object)(object)p) && p.IsPlacedByPlayer()))
			{
				ZNetView component = ((Component)item).GetComponent<ZNetView>();
				ZDO val = (Object.op_Implicit((Object)(object)component) ? component.GetZDO() : null);
				GameObject val2 = ((val != null) ? ZNetScene.instance.GetPrefab(val.GetPrefab()) : null);
				if (Object.op_Implicit((Object)(object)val2))
				{
					Sign component2 = ((Component)item).GetComponent<Sign>();
					List<Entry> pieces = layout.pieces;
					Entry obj = new Entry
					{
						prefab = ((Object)val2).name,
						pos = Round(transform.InverseTransformPoint(((Component)item).transform.position))
					};
					Quaternion val3 = Quaternion.Inverse(transform.rotation) * ((Component)item).transform.rotation;
					obj.rot = Round(((Quaternion)(ref val3)).eulerAngles);
					obj.text = (Object.op_Implicit((Object)(object)component2) ? component2.GetText() : null);
					pieces.Add(obj);
					list2.Add(((Component)item).gameObject);
				}
			}
			if (layout.pieces.Count == 0)
			{
				return "No player-built pieces found in this harbour. (Layout file left unchanged.)";
			}
			foreach (Entry e in layout.pieces)
			{
				Entry entry = _layout.pieces.FirstOrDefault((Entry o) => o.prefab == e.prefab && Vector3.Distance(o.pos, e.pos) < 0.05f);
				if (entry != null)
				{
					e.scale = entry.scale;
				}
			}
			File.WriteAllText(FilePath, Serialize(layout));
			_layout = layout;
			if (clearOriginals)
			{
				foreach (GameObject item2 in list2)
				{
					ZNetView component3 = item2.GetComponent<ZNetView>();
					if (Object.op_Implicit((Object)(object)component3) && component3.IsValid())
					{
						component3.ClaimOwnership();
					}
					ZNetScene.instance.Destroy(item2);
				}
			}
			RefreshLoadedHarbours();
			string arg = string.Join(", ", from p in layout.pieces
				group p by p.prefab into g
				select $"{g.Count()}x {g.Key}");
			return $"Captured {layout.pieces.Count} piece(s) to {FilePath}: {arg}" + (clearOriginals ? ". Removed your originals; what you see now is the mod's copy." : "");
		}

		public static string ScaleLookedAt(string arg)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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)
			if (!float.TryParse(arg ?? "", NumberStyles.Float, Inv, out var result) || result <= 0f)
			{
				return "Usage: look at a piece from the harbour layout, then e.g. `scalepiece 2` (1 = normal size).";
			}
			Transform val = (Object.op_Implicit((Object)(object)GameCamera.instance) ? ((Component)GameCamera.instance).transform : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return "No camera.";
			}
			foreach (RaycastHit item in from h in Physics.RaycastAll(val.position, val.forward, 50f, -1, (QueryTriggerInteraction)1)
				orderby ((RaycastHit)(ref h)).distance
				select h)
			{
				RaycastHit current = item;
				Transform val2 = ((RaycastHit)(ref current)).transform;
				while (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.parent))
				{
					if (!(((Object)val2.parent).name != "BurgerHouse_Layout"))
					{
						int num = ((Object)val2).name.LastIndexOf('#');
						if (num < 0 || !int.TryParse(((Object)val2).name.Substring(num + 1), out var result2) || result2 >= _layout.pieces.Count)
						{
							break;
						}
						Entry entry = _layout.pieces[result2];
						entry.scale = Mathf.Round(result * 1000f) / 1000f;
						File.WriteAllText(FilePath, Serialize(_layout));
						RefreshLoadedHarbours();
						return string.Format("{0} scaled to {1} in all harbours (saved to {2}).", entry.prefab, entry.scale, "BurgerHouse.harbour_layout.txt");
					}
					val2 = val2.parent;
				}
			}
			return "Not looking at a piece from the harbour layout (within 50m).";
		}

		private static Vector3 Round(Vector3 v)
		{
			//IL_0000: 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_002e: 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)
			return new Vector3(Mathf.Round(v.x * 1000f) / 1000f, Mathf.Round(v.y * 1000f) / 1000f, Mathf.Round(v.z * 1000f) / 1000f);
		}
	}
}