Decompiled source of Building Tweaks v1.0.36

DigiBuilding.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BeamFit;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BuildCamera;
using BuildMaterials;
using BuildMenuMemory;
using BuildRestrictions;
using ChestSnapping;
using ComfortRange;
using DigiCore;
using DigiShared;
using DismantleVehicles;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using LevelStrength;
using Microsoft.CodeAnalysis;
using NoWeatherDamage;
using QuickRotate;
using RepairNearby;
using RugLift;
using SafePortals;
using Schematics;
using SnowToggle;
using SnowUnderRoofs;
using SpawnFreeRange;
using StabilityMeter;
using StationExtensionRange;
using StationRange;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using WoodSwap;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class SettingOrder
{
	internal sealed class ConfigurationManagerAttributes
	{
		public int? Order;
	}

	internal static void Apply(ConfigFile config)
	{
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Expected O, but got Unknown
		FieldInfo fieldInfo = AccessTools.Field(typeof(ConfigEntryBase), "<Description>k__BackingField");
		if (fieldInfo == null)
		{
			return;
		}
		int num = 1000;
		foreach (ConfigDefinition item in config.Keys.ToList())
		{
			ConfigEntryBase val = config[item];
			ConfigDescription description = val.Description;
			object[] array = ((description != null) ? description.Tags : null) ?? new object[0];
			object obj = array.FirstOrDefault((object t) => t != null && t.GetType().Name == "ConfigurationManagerAttributes");
			if (obj != null)
			{
				FieldInfo fieldInfo2 = AccessTools.Field(obj.GetType(), "Order");
				if (fieldInfo2 != null && fieldInfo2.GetValue(obj) == null)
				{
					fieldInfo2.SetValue(obj, num);
				}
			}
			else
			{
				fieldInfo.SetValue(val, (object?)new ConfigDescription(((description != null) ? description.Description : null) ?? "", (description != null) ? description.AcceptableValues : null, array.Concat(new object[1]
				{
					new ConfigurationManagerAttributes
					{
						Order = num
					}
				}).ToArray()));
			}
			num--;
		}
	}
}
internal static class StoreRules
{
	private sealed class Box
	{
		public Vector3 At;

		public Bounds Bounds;
	}

	private sealed class InputSet
	{
		public int Count;

		public HashSet<string> Names;
	}

	private static ConfigEntry<bool> _leaveOne;

	private static ConfigEntry<bool> _onlyMatching;

	private static int _holdSaves;

	private static readonly HashSet<Container> HeldSaves = new HashSet<Container>();

	private static MethodInfo _save;

	private static bool _savePatched;

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

	private static readonly Dictionary<Container, bool> Mobile = new Dictionary<Container, bool>();

	private static int _mobilePruneAt = 512;

	private static readonly Dictionary<Component, Box> Boxes = new Dictionary<Component, Box>();

	private static int _boxPruneAt = 512;

	private static readonly Dictionary<IList, InputSet> InputSets = new Dictionary<IList, InputSet>();

	internal static bool LeaveOne
	{
		get
		{
			if (_leaveOne != null)
			{
				return _leaveOne.Value;
			}
			return false;
		}
	}

	internal static bool OnlyMatching
	{
		get
		{
			if (_onlyMatching != null)
			{
				return _onlyMatching.Value;
			}
			return false;
		}
	}

	internal static bool CanDeposit(Inventory inv)
	{
		return true;
	}

	internal static bool CanWithdraw(Inventory inv)
	{
		return true;
	}

	internal static bool CanWithdraw(Container chest)
	{
		return !ChestFlags.TakeBlocked(chest);
	}

	internal static bool IsProtected(Inventory inv, ItemData item)
	{
		return false;
	}

	internal static bool IsProtectedSlot(Inventory inv, int x, int y)
	{
		return false;
	}

	internal static Func<int, int, bool> ProtectedSlots(Inventory inv)
	{
		return null;
	}

	internal static void BindRules(ModuleConfig config)
	{
		ConfigFile file = config.File;
		string text = (config.Standalone ? "Chest rules" : "Craft From Chests - Chest rules");
		_leaveOne = file.Bind<bool>(text, "Leave 1 in each chest", false, "Crafting, building, filling by hand and the automated stations never take the last one of an item from a chest: a chest kept for one item (wood, iron, a mead) keeps one, so it stays that item's chest. Off: all of it can be used.");
		_onlyMatching = file.Bind<bool>(text, "Only store into chests that already have it", false, "The automated stations put what they make only into a chest that already holds that item. Off: when no chest has it, it goes into the nearest chest with room. With no chest for it, fermenters, ovens, cooking stations, beehives and sap extractors keep it (food only drops just before it burns); smelters, kilns and the like drop it as in the game.");
	}

	internal static bool KeepsLast(Inventory inv, ItemData item)
	{
		if (LeaveOne && item?.m_shared != null)
		{
			return inv.CountItems(item.m_shared.m_name, -1, false) <= 1;
		}
		return false;
	}

	internal static Container PickOutputChest(List<Container> nearestFirst, GameObject prefab, int amount)
	{
		string shared = prefab.GetComponent<ItemDrop>()?.m_itemData.m_shared.m_name;
		List<Container> source = nearestFirst.Where((Container c) => c.GetInventory().CanAddItem(prefab, amount)).ToList();
		object obj = ((IEnumerable<Container>)source).FirstOrDefault((Func<Container, bool>)((Container c) => c.GetInventory().GetAllItems().Any((ItemData i) => i?.m_shared != null && i.m_shared.m_name == shared)));
		if (obj == null)
		{
			if (!OnlyMatching)
			{
				return source.FirstOrDefault();
			}
			obj = null;
		}
		return (Container)obj;
	}

	internal static void HoldSaves()
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Expected O, but got Unknown
		if (!_savePatched)
		{
			_savePatched = true;
			_save = AccessTools.Method(typeof(Container), "Save", (Type[])null, (Type[])null);
			if (_save != null)
			{
				new Harmony("digi.storerules.saves." + typeof(StoreRules).Assembly.GetName().Name).Patch((MethodBase)_save, new HarmonyMethod(typeof(StoreRules), "SaveLater", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
		_holdSaves++;
	}

	internal static void SaveHeld()
	{
		if (--_holdSaves > 0)
		{
			return;
		}
		_holdSaves = 0;
		if (HeldSaves.Count == 0)
		{
			return;
		}
		List<Container> list = HeldSaves.ToList();
		HeldSaves.Clear();
		foreach (Container item in list)
		{
			if (!((Object)(object)item == (Object)null) && !(_save == null))
			{
				try
				{
					_save.Invoke(item, null);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)("[Digi] chest save failed: " + (ex.InnerException ?? ex).Message));
				}
			}
		}
	}

	private static bool SaveLater(Container __instance)
	{
		if (_holdSaves <= 0 || (Object)(object)__instance == (Object)null)
		{
			return true;
		}
		HeldSaves.Add(__instance);
		return false;
	}

	internal static string NameOf(GameObject prefab)
	{
		if ((Object)(object)prefab == (Object)null)
		{
			return null;
		}
		if (!Names.TryGetValue(prefab, out var value))
		{
			if (Names.Count > 20000)
			{
				Names.Clear();
			}
			value = (Names[prefab] = ((Object)prefab).name);
		}
		return value;
	}

	internal static string NameOf(Component prefab)
	{
		if (!((Object)(object)prefab == (Object)null))
		{
			return NameOf(prefab.gameObject);
		}
		return null;
	}

	internal static bool CartShipOrGrave(Container chest)
	{
		if (Mobile.TryGetValue(chest, out var value))
		{
			return value;
		}
		if (Mobile.Count >= _mobilePruneAt)
		{
			foreach (Container item in Mobile.Keys.Where((Container c) => (Object)(object)c == (Object)null).ToList())
			{
				Mobile.Remove(item);
			}
			_mobilePruneAt = Math.Max(512, Mobile.Count * 2);
		}
		value = (Object)(object)chest.m_wagon != (Object)null || (Object)(object)((Component)chest).GetComponentInParent<Ship>() != (Object)null || (Object)(object)((Component)chest).GetComponent<TombStone>() != (Object)null;
		Mobile[chest] = value;
		return value;
	}

	internal static Bounds SolidBounds(Component owner, Func<Component, Bounds> measure)
	{
		//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_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = owner.transform.position;
		if (Boxes.TryGetValue(owner, out var value) && value.At == position)
		{
			return value.Bounds;
		}
		if (value == null && Boxes.Count >= _boxPruneAt)
		{
			foreach (Component item in Boxes.Keys.Where((Component c) => (Object)(object)c == (Object)null).ToList())
			{
				Boxes.Remove(item);
			}
			_boxPruneAt = Math.Max(512, Boxes.Count * 2);
		}
		Bounds val = measure(owner);
		Boxes[owner] = new Box
		{
			At = position,
			Bounds = val
		};
		return val;
	}

	internal static HashSet<string> InputNames<T>(List<T> conversions, Func<T, Component> from)
	{
		if (conversions == null)
		{
			return new HashSet<string>();
		}
		if (!InputSets.TryGetValue(conversions, out var value) || value.Count != conversions.Count)
		{
			if (InputSets.Count > 2000)
			{
				InputSets.Clear();
			}
			HashSet<string> hashSet = new HashSet<string>();
			foreach (T conversion in conversions)
			{
				Component val = ((conversion != null) ? from(conversion) : null);
				if ((Object)(object)val != (Object)null)
				{
					hashSet.Add(NameOf(val));
				}
			}
			value = (InputSets[conversions] = new InputSet
			{
				Count = conversions.Count,
				Names = hashSet
			});
		}
		return value.Names;
	}

	internal static bool TakeOne(List<Container> nearestFirst, Func<ItemData, bool> match, out ItemData taken)
	{
		foreach (Container item in nearestFirst)
		{
			if (CanWithdraw(item))
			{
				Inventory inv = item.GetInventory();
				ItemData val = ((IEnumerable<ItemData>)inv.GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData i) => match(i) && !KeepsLast(inv, i)));
				if (val != null)
				{
					taken = val.Clone();
					inv.RemoveOneItem(val);
					return true;
				}
			}
		}
		taken = null;
		return false;
	}
}
namespace DigiShared
{
	internal static class Buildings
	{
		internal static Bounds BoundsOf(Piece piece)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			Bounds result = default(Bounds);
			((Bounds)(ref result))..ctor(((Component)piece).transform.position, Vector3.zero);
			Collider[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Collider>();
			foreach (Collider val in componentsInChildren)
			{
				if (val.enabled && !val.isTrigger)
				{
					((Bounds)(ref result)).Encapsulate(val.bounds);
				}
			}
			return result;
		}

		internal static IEnumerable<Piece> Connected(Piece start, List<Piece> found, int max = 20000)
		{
			HashSet<Piece> seen = new HashSet<Piece> { start };
			found.Add(start);
			Collider[] hits = (Collider[])(object)new Collider[128];
			int mask = LayerMask.GetMask(new string[2] { "piece", "piece_nonsolid" });
			for (int i = 0; i < found.Count; i++)
			{
				if (found.Count >= max)
				{
					break;
				}
				Piece val = found[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Bounds val2 = BoundsOf(val);
				int num = Physics.OverlapBoxNonAlloc(((Bounds)(ref val2)).center, ((Bounds)(ref val2)).extents + Vector3.one * 0.1f, hits, Quaternion.identity, mask);
				for (int j = 0; j < num; j++)
				{
					Piece val3 = (((Object)(object)hits[j] != (Object)null) ? ((Component)hits[j]).GetComponentInParent<Piece>() : null);
					if ((Object)(object)val3 != (Object)null && val3.IsPlacedByPlayer() && seen.Add(val3))
					{
						found.Add(val3);
					}
				}
				yield return val;
			}
		}
	}
	internal sealed class IconSheet
	{
		private const int Cell = 128;

		private const int Columns = 4;

		private readonly Assembly _assembly;

		private readonly string _resource;

		private readonly Action<string> _warn;

		private Texture2D _sheet;

		private readonly Dictionary<string, int[]> _cells = new Dictionary<string, int[]>();

		private bool _loaded;

		private static readonly MethodInfo LoadImage = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[2]
		{
			typeof(Texture2D),
			typeof(byte[])
		});

		private static readonly MethodInfo EncodeToPng = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("EncodeToPNG", new Type[1] { typeof(Texture2D) });

		internal static bool LoadPng(Texture2D texture, byte[] png)
		{
			bool flag = default(bool);
			int num;
			if (LoadImage != null)
			{
				object obj = LoadImage.Invoke(null, new object[2] { texture, png });
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}

		internal static byte[] EncodePng(Texture2D texture)
		{
			return EncodeToPng?.Invoke(null, new object[1] { texture }) as byte[];
		}

		internal IconSheet(Assembly assembly, string resource, Action<string> warn)
		{
			_assembly = assembly;
			_resource = resource;
			_warn = warn;
		}

		private void Init()
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			if (_loaded)
			{
				return;
			}
			_loaded = true;
			try
			{
				byte[] png;
				using (Stream stream = _assembly.GetManifestResourceStream(_resource + ".png"))
				{
					using MemoryStream memoryStream = new MemoryStream();
					if (stream == null)
					{
						return;
					}
					stream.CopyTo(memoryStream);
					png = memoryStream.ToArray();
				}
				string text;
				using (Stream stream2 = _assembly.GetManifestResourceStream(_resource + ".txt"))
				{
					if (stream2 == null)
					{
						return;
					}
					using StreamReader streamReader = new StreamReader(stream2);
					text = streamReader.ReadToEnd();
				}
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!LoadPng(val, png))
				{
					return;
				}
				_sheet = val;
				int num = 0;
				string[] array = text.Split(new char[1] { '\n' });
				for (int i = 0; i < array.Length; i++)
				{
					string[] array2 = array[i].Trim().Split(new char[1] { ' ' });
					if (array2.Length >= 4)
					{
						_cells[array2[0]] = new int[4]
						{
							num++,
							int.Parse(array2[1]),
							int.Parse(array2[2]),
							int.Parse(array2[3])
						};
					}
				}
			}
			catch (Exception ex)
			{
				_warn?.Invoke("Tool icons not loaded: " + ex.Message);
			}
		}

		internal Sprite For(string id, Sprite under)
		{
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: 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_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			Init();
			if ((Object)(object)_sheet == (Object)null || !_cells.TryGetValue(id, out var value))
			{
				return null;
			}
			try
			{
				int num = value[0] % 4;
				int num2 = value[0] / 4;
				Color[] pixels = _sheet.GetPixels(num * 128, ((Texture)_sheet).height - (num2 + 1) * 128, 128, 128);
				int num3 = value[3];
				Texture2D val = ((num3 > 0 && (Object)(object)under != (Object)null) ? Readable(under) : null);
				if ((Object)(object)val != (Object)null)
				{
					for (int i = 0; i < num3; i++)
					{
						for (int j = 0; j < num3; j++)
						{
							int num4 = value[1] + j;
							int num5 = value[2] + i;
							if (num4 >= 0 && num4 < 128 && num5 >= 0 && num5 < 128)
							{
								Color pixelBilinear = val.GetPixelBilinear(((float)j + 0.5f) / (float)num3, 1f - ((float)i + 0.5f) / (float)num3);
								int num6 = (127 - num5) * 128 + num4;
								pixels[num6] = Over(pixels[num6], pixelBilinear);
							}
						}
					}
					Object.Destroy((Object)(object)val);
				}
				Texture2D val2 = new Texture2D(128, 128, (TextureFormat)4, false)
				{
					name = "Digi icon " + id,
					wrapMode = (TextureWrapMode)1
				};
				val2.SetPixels(pixels);
				val2.Apply(false, true);
				return Sprite.Create(val2, new Rect(0f, 0f, 128f, 128f), new Vector2(0.5f, 0.5f), 100f);
			}
			catch (Exception ex)
			{
				_warn?.Invoke("Icon " + id + ": " + ex.Message);
				return null;
			}
		}

		private static Color Over(Color top, Color bottom)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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_003e: 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_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: 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)
			float num = top.a + bottom.a * (1f - top.a);
			if (num <= 0f)
			{
				return new Color(0f, 0f, 0f, 0f);
			}
			Color result = (top * top.a + bottom * bottom.a * (1f - top.a)) / num;
			result.a = num;
			return result;
		}

		private static Texture2D Readable(Sprite sprite)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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_00d9: Expected O, but got Unknown
			Texture2D texture = sprite.texture;
			if ((Object)(object)texture == (Object)null)
			{
				return null;
			}
			Rect textureRect = sprite.textureRect;
			int num = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref textureRect)).width));
			int num2 = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref textureRect)).height));
			RenderTexture temporary = RenderTexture.GetTemporary(num, num2, 0, (RenderTextureFormat)0);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit((Texture)(object)texture, temporary, new Vector2(((Rect)(ref textureRect)).width / (float)((Texture)texture).width, ((Rect)(ref textureRect)).height / (float)((Texture)texture).height), new Vector2(((Rect)(ref textureRect)).x / (float)((Texture)texture).width, ((Rect)(ref textureRect)).y / (float)((Texture)texture).height));
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(num, num2, (TextureFormat)4, false)
				{
					wrapMode = (TextureWrapMode)1
				};
				val.ReadPixels(new Rect(0f, 0f, (float)num, (float)num2), 0, 0);
				val.Apply();
				return val;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
	internal static class MaterialsList
	{
		private enum Column
		{
			Name,
			Total,
			Have,
			Missing
		}

		private sealed class Line
		{
			public string Name;

			public Sprite Icon;

			public int Amount;

			public int Have;

			public int Missing => Mathf.Max(0, Amount - Have);
		}

		internal static float ChestRange = 50f;

		private const float Width = 880f;

		private const float Height = 820f;

		private const float RowHeight = 40f;

		private const float ColumnWidth = 110f;

		private const float HeaderY = 146f;

		private const float ListTop = 184f;

		private static readonly Color Green = new Color(0.5f, 0.88f, 0.42f);

		private static readonly Color Red = new Color(1f, 0.45f, 0.38f);

		private static readonly string[] Titles = new string[4] { "Material", "Total", "Have", "Missing" };

		private static readonly MethodInfo CheckAccess = AccessTools.Method(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null);

		private static Column _sort = Column.Total;

		private static bool _descending = true;

		private static List<Line> _materials = new List<Line>();

		private static List<Line> _pieces = new List<Line>();

		private static Windows.Window _window;

		private static string _query = "";

		private static readonly TextMeshProUGUI[] Headers = (TextMeshProUGUI[])(object)new TextMeshProUGUI[4];

		internal static string Number(int n)
		{
			return n.ToString("N0", CultureInfo.InvariantCulture);
		}

		internal static void Show(string subtitle, List<string> prefabs, Action back = null)
		{
			//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Expected O, but got Unknown
			//IL_04db: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, Line> dictionary = new Dictionary<string, Line>();
			Dictionary<string, Line> dictionary2 = new Dictionary<string, Line>();
			SortedSet<string> sortedSet = new SortedSet<string>();
			float num = 0f;
			foreach (string prefab in prefabs)
			{
				GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(prefab) : null);
				Piece val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Piece>() : null);
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				Add(dictionary2, prefab, Localization.instance.Localize(val2.m_name), val2.m_icon, 1);
				if ((Object)(object)val2.m_craftingStation != (Object)null)
				{
					sortedSet.Add(Localization.instance.Localize(val2.m_craftingStation.m_name));
				}
				if (val2.m_resources == null)
				{
					continue;
				}
				Requirement[] resources = val2.m_resources;
				foreach (Requirement val3 in resources)
				{
					if (!((Object)(object)val3?.m_resItem == (Object)null) && val3.m_amount > 0)
					{
						ItemData itemData = val3.m_resItem.m_itemData;
						Add(dictionary, itemData.m_shared.m_name, Localization.instance.Localize(itemData.m_shared.m_name), itemData.GetIcon(), val3.m_amount);
						num += itemData.m_shared.m_weight * (float)val3.m_amount;
					}
				}
			}
			Player localPlayer = Player.m_localPlayer;
			List<Inventory> source = Stores(localPlayer);
			foreach (KeyValuePair<string, Line> pair in dictionary)
			{
				pair.Value.Have = (((Object)(object)localPlayer != (Object)null) ? ((Humanoid)localPlayer).GetInventory().CountItems(pair.Key, -1, true) : 0) + source.Sum((Inventory inv) => inv.CountItems(pair.Key, -1, true));
			}
			_materials = dictionary.Values.ToList();
			_pieces = dictionary2.Values.ToList();
			string footer = "Total weight " + Number(Mathf.RoundToInt(num)) + ((sortedSet.Count > 0) ? ("   ·   Needs " + string.Join(", ", sortedSet)) : "") + $"   ·   Have: inventory + chests within {ChestRange:0} m";
			_window = Windows.Open("Build Materials", subtitle, 880f, 820f, footer, 80f, back, 184f);
			if (_window == null)
			{
				return;
			}
			_query = "";
			TMP_InputField val4 = Windows.SearchBox(_window.Panel, 24f, 100f, 340f, 38f, "Search material or piece...");
			((UnityEvent<string>)(object)val4.onValueChanged).AddListener((UnityAction<string>)delegate(string text)
			{
				_query = (text ?? "").Trim();
				Fill();
			});
			_window.Search = val4;
			int num2 = _materials.Count((Line l) => l.Missing > 0);
			Windows.Place(((TMP_Text)Windows.Text((Transform)(object)_window.Panel, (_materials.Count == 0) ? "" : ((num2 == 0) ? "You have everything" : $"Short of {num2} of {_materials.Count} materials"), 20f, (num2 == 0) ? Green : Red, (TextAlignmentOptions)516)).rectTransform, 384f, 104f, 472f, 30f);
			RectTransform val5 = Windows.Rect("Header", (Transform)(object)_window.Panel);
			Windows.Place(val5, 24f, 146f, _window.RowWidth, 32f);
			for (int num3 = 0; num3 < Titles.Length; num3++)
			{
				Column column = (Column)num3;
				RectTransform val6 = Windows.Rect("Column " + Titles[num3], (Transform)(object)val5);
				if (num3 == 0)
				{
					Windows.Place(val6, 12f, 0f, NameWidth(), 32f);
				}
				else
				{
					Windows.Place(val6, ColumnX(num3), 0f, 110f, 32f);
				}
				((Graphic)((Component)val6).gameObject.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
				((UnityEvent)((Component)val6).gameObject.AddComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					SortBy(column);
				});
				TextMeshProUGUI val7 = Windows.Text((Transform)(object)val6, Titles[num3], 19f, Windows.Gold, (TextAlignmentOptions)((num3 == 0) ? 513 : 516));
				Windows.Stretch(((TMP_Text)val7).rectTransform);
				Headers[num3] = val7;
			}
			Fill();
		}

		private static float NameWidth()
		{
			return _window.RowWidth - 52f - 330f - 16f;
		}

		private static float ColumnX(int i)
		{
			return _window.RowWidth - (float)(4 - i) * 110f - 12f;
		}

		private static void SortBy(Column column)
		{
			if (_sort == column)
			{
				_descending = !_descending;
			}
			else
			{
				_sort = column;
				_descending = column != Column.Name;
			}
			Fill();
		}

		private static void Add(Dictionary<string, Line> lines, string key, string name, Sprite icon, int amount)
		{
			if (!lines.TryGetValue(key, out var value))
			{
				Line obj = new Line
				{
					Name = name,
					Icon = icon
				};
				value = obj;
				lines[key] = obj;
			}
			value.Amount += amount;
		}

		internal static List<Container> Chests(Player player)
		{
			//IL_002a: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			if ((Object)(object)player == (Object)null || ChestRange <= 0f)
			{
				return list;
			}
			Vector3 origin = ((Component)player).transform.position;
			float num = ChestRange * ChestRange;
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			foreach (Container val in array)
			{
				if ((Object)(object)val == (Object)null || val.GetInventory() == null)
				{
					continue;
				}
				Vector3 val2 = ((Component)val).transform.position - origin;
				if (!(((Vector3)(ref val2)).sqrMagnitude > num))
				{
					Piece componentInParent = ((Component)val).GetComponentInParent<Piece>();
					if (!((Object)(object)componentInParent == (Object)null) && componentInParent.IsPlacedByPlayer() && (!(CheckAccess != null) || (bool)CheckAccess.Invoke(val, new object[1] { player.GetPlayerID() })))
					{
						list.Add(val);
					}
				}
			}
			return list.OrderBy(delegate(Container c)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val3 = ((Component)c).transform.position - origin;
				return ((Vector3)(ref val3)).sqrMagnitude;
			}).ToList();
		}

		private static List<Inventory> Stores(Player player)
		{
			return (from c in Chests(player)
				select c.GetInventory()).ToList();
		}

		private static IEnumerable<Line> Sorted(IEnumerable<Line> lines, bool material)
		{
			Func<Line, int> keySelector = _sort switch
			{
				Column.Have => (Line l) => (!material) ? l.Amount : l.Have, 
				Column.Missing => (Line l) => (!material) ? l.Amount : l.Missing, 
				_ => (Line l) => l.Amount, 
			};
			if (_sort == Column.Name)
			{
				if (!_descending)
				{
					return lines.OrderBy<Line, string>((Line l) => l.Name, StringComparer.OrdinalIgnoreCase);
				}
				return lines.OrderByDescending<Line, string>((Line l) => l.Name, StringComparer.OrdinalIgnoreCase);
			}
			if (!_descending)
			{
				return lines.OrderBy(keySelector).ThenBy((Line l) => l.Name);
			}
			return lines.OrderByDescending(keySelector).ThenBy((Line l) => l.Name);
		}

		private static void Fill()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			if (_window == null || (Object)(object)_window.Content == (Object)null)
			{
				return;
			}
			for (int i = 0; i < Headers.Length; i++)
			{
				if (!((Object)(object)Headers[i] == (Object)null))
				{
					bool flag = _sort == (Column)i;
					((TMP_Text)Headers[i]).text = Titles[i] + ((!flag) ? "" : (_descending ? " <size=70%>v</size>" : " <size=70%>^</size>"));
					((Graphic)Headers[i]).color = (flag ? Color.white : Windows.Gold);
				}
			}
			for (int num = ((Transform)_window.Content).childCount - 1; num >= 0; num--)
			{
				Object.Destroy((Object)(object)((Component)((Transform)_window.Content).GetChild(num)).gameObject);
			}
			float num2 = Section(0f, "Materials", material: true, Sorted(_materials.Where(Matches), material: true).ToList());
			num2 = Section(num2 + 12f, "Pieces", material: false, Sorted(_pieces.Where(Matches), material: false).ToList());
			Windows.Done(_window, num2);
			static bool Matches(Line l)
			{
				if (_query.Length != 0)
				{
					return l.Name.IndexOf(_query, StringComparison.OrdinalIgnoreCase) >= 0;
				}
				return true;
			}
		}

		private static float Section(float y, string title, bool material, List<Line> lines)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: 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_0155: 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_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			float rowWidth = _window.RowWidth;
			RectTransform val = Windows.Rect("Heading", (Transform)(object)_window.Content);
			Windows.Place(val, 0f, y, rowWidth, 34f);
			Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val, title, 22f, Windows.Gold, (TextAlignmentOptions)513)).rectTransform, 12f, 2f, NameWidth(), 30f);
			if (!material)
			{
				Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val, "Count", 19f, Windows.Gold, (TextAlignmentOptions)516)).rectTransform, ColumnX(1), 4f, 110f, 28f);
			}
			RectTransform obj = Windows.Rect("Line", (Transform)(object)val);
			Windows.Place(obj, 8f, 33f, rowWidth - 16f, 1f);
			((Graphic)((Component)obj).gameObject.AddComponent<Image>()).color = new Color(Windows.Gold.r, Windows.Gold.g, Windows.Gold.b, 0.4f);
			y += 36f;
			if (lines.Count == 0)
			{
				RectTransform obj2 = Windows.Rect("None", (Transform)(object)_window.Content);
				Windows.Place(obj2, 0f, y, rowWidth, 40f);
				Windows.Place(((TMP_Text)Windows.Text((Transform)(object)obj2, (_query.Length > 0) ? "nothing matches" : "nothing", 19f, Windows.Dim, (TextAlignmentOptions)513)).rectTransform, 52f, 6f, rowWidth - 60f, 28f);
				return y + 40f;
			}
			for (int i = 0; i < lines.Count; i++)
			{
				Line line = lines[i];
				RectTransform val2 = Windows.Rect("Row", (Transform)(object)_window.Content);
				Windows.Place(val2, 0f, y, rowWidth, 40f);
				((Graphic)((Component)val2).gameObject.AddComponent<Image>()).color = ((i % 2 == 0) ? Windows.RowEven : Windows.RowOdd);
				if ((Object)(object)line.Icon != (Object)null)
				{
					Windows.Picture(val2, line.Icon, 10f, 4f, 32f, 32f);
				}
				Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val2, line.Name, 20f, Windows.Body, (TextAlignmentOptions)513)).rectTransform, 52f, 6f, NameWidth(), 28f);
				Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val2, Number(line.Amount), 20f, Windows.Body, (TextAlignmentOptions)516)).rectTransform, ColumnX(1), 6f, 110f, 28f);
				if (material)
				{
					bool flag = line.Missing == 0;
					Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val2, Number(line.Have), 20f, flag ? Green : Red, (TextAlignmentOptions)516)).rectTransform, ColumnX(2), 6f, 110f, 28f);
					Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val2, flag ? "-" : Number(line.Missing), 20f, flag ? Windows.Dim : Red, (TextAlignmentOptions)516)).rectTransform, ColumnX(3), 6f, 110f, 28f);
				}
				y += 40f;
			}
			return y;
		}
	}
	internal static class SchematicLibrary
	{
		internal sealed class Entry
		{
			public string Prefab;

			public Vector3 Pos;

			public Quaternion Rot;
		}

		internal sealed class Schematic
		{
			public string Name;

			public string File;

			public string Saved = "";

			public int Count;

			public Vector3 Size;

			public float Ground;

			public readonly List<Entry> Pieces = new List<Entry>();
		}

		internal const float RowHeight = 116f;

		private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

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

		internal static ManualLogSource Log;

		internal static string Folder => Path.Combine(Paths.ConfigPath, "DigiCreative", "Schematics");

		internal static Schematic Load(string file, bool pieces)
		{
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: 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)
			Schematic schematic = new Schematic
			{
				File = file,
				Name = Path.GetFileNameWithoutExtension(file)
			};
			Quaternion val = default(Quaternion);
			foreach (string item in File.ReadLines(file))
			{
				string text = item.Trim();
				if (text.Length == 0 || text[0] == '#')
				{
					continue;
				}
				if (text.IndexOf(';') < 0)
				{
					int num = text.IndexOf('=');
					if (num <= 0)
					{
						continue;
					}
					string text2 = text.Substring(0, num).Trim();
					string text3 = text.Substring(num + 1).Trim();
					if (text2 == "name" && text3.Length > 0)
					{
						schematic.Name = text3;
						continue;
					}
					switch (text2)
					{
					case "saved":
						schematic.Saved = text3;
						break;
					case "pieces":
						int.TryParse(text3, NumberStyles.Integer, Inv, out schematic.Count);
						break;
					case "ground":
						schematic.Ground = P(text3);
						break;
					case "size":
					{
						string[] array = text3.Split(new char[1] { ' ' });
						if (array.Length == 3)
						{
							schematic.Size = new Vector3(P(array[0]), P(array[1]), P(array[2]));
						}
						break;
					}
					}
				}
				else
				{
					if (!pieces)
					{
						break;
					}
					string[] array2 = text.Split(new char[1] { ';' });
					if (array2.Length >= 8 && array2[0].Length != 0)
					{
						((Quaternion)(ref val))..ctor(P(array2[4]), P(array2[5]), P(array2[6]), P(array2[7]));
						schematic.Pieces.Add(new Entry
						{
							Prefab = array2[0],
							Pos = new Vector3(P(array2[1]), P(array2[2]), P(array2[3])),
							Rot = ((val.x == 0f && val.y == 0f && val.z == 0f && val.w == 0f) ? Quaternion.identity : ((Quaternion)(ref val)).normalized)
						});
					}
				}
			}
			if (pieces)
			{
				schematic.Count = schematic.Pieces.Count;
			}
			return schematic;
		}

		private static float P(string s)
		{
			if (!float.TryParse(s, NumberStyles.Float, Inv, out var result))
			{
				return 0f;
			}
			return result;
		}

		internal static List<Schematic> All()
		{
			List<Schematic> list = new List<Schematic>();
			if (!Directory.Exists(Folder))
			{
				return list;
			}
			string[] files = Directory.GetFiles(Folder, "*.schematic");
			foreach (string text in files)
			{
				try
				{
					list.Add(Load(text, pieces: false));
				}
				catch (Exception ex)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogWarning((object)("Could not read " + text + ": " + ex.Message));
					}
				}
			}
			return list.OrderBy<Schematic, string>((Schematic s) => s.Name, StringComparer.OrdinalIgnoreCase).ToList();
		}

		internal static Schematic Full(Schematic s)
		{
			try
			{
				return Load(s.File, pieces: true);
			}
			catch (Exception arg)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogError((object)$"Could not read {s.File}: {arg}");
				}
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Could not read that schematic (see the log)", 0, (Sprite)null, false);
				}
				return null;
			}
		}

		internal static Sprite PictureOf(string file)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.ChangeExtension(file, ".png");
			if (!File.Exists(text))
			{
				return null;
			}
			string key = text + "|" + File.GetLastWriteTimeUtc(text).Ticks;
			if (Pictures.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			Texture2D val = new Texture2D(2, 2);
			if (!IconSheet.LoadPng(val, File.ReadAllBytes(text)))
			{
				Object.Destroy((Object)(object)val);
				return null;
			}
			value = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			Pictures[key] = value;
			return value;
		}

		internal static void ShowMaterials(Schematic s, Action back)
		{
			Schematic schematic = Full(s);
			if (schematic != null)
			{
				MaterialsList.Show("Schematic " + schematic.Name + ": " + MaterialsList.Number(schematic.Pieces.Count) + " pieces", schematic.Pieces.Select((Entry e) => e.Prefab).ToList(), back);
			}
		}

		internal static void Open(string footer, Func<Windows.Window, float, float> top, Action<RectTransform, Schematic, float> buttons)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			List<Schematic> list = All();
			Windows.Window window = Windows.Open("Schematics", (list.Count == 0) ? "None saved yet" : ((list.Count == 1) ? "1 saved" : $"{list.Count} saved"), 900f, 820f, footer, 116f);
			if (window != null)
			{
				float rowWidth = window.RowWidth;
				float num = top?.Invoke(window, rowWidth) ?? 0f;
				if (list.Count == 0)
				{
					RectTransform obj = Windows.Rect("None", (Transform)(object)window.Content);
					Windows.Place(obj, 0f, num, rowWidth, 80f);
					Windows.Place(((TMP_Text)Windows.Text((Transform)(object)obj, "No schematics yet: save a building with Ultimate Builder's Save Schematic tool (in its creative world).", 19f, Windows.Dim, (TextAlignmentOptions)513)).rectTransform, 16f, 24f, rowWidth - 32f, 30f);
					num += 80f;
				}
				for (int i = 0; i < list.Count; i++)
				{
					Schematic schematic = list[i];
					RectTransform val = Windows.Rect("Row", (Transform)(object)window.Content);
					Windows.Place(val, 0f, num, rowWidth, 116f);
					((Graphic)((Component)val).gameObject.AddComponent<Image>()).color = ((i % 2 == 0) ? Windows.RowEven : Windows.RowOdd);
					Windows.Picture(val, PictureOf(schematic.File), 8f, 8f, 100f, 100f);
					Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val, schematic.Name, 24f, Windows.Gold, (TextAlignmentOptions)513)).rectTransform, 124f, 8f, rowWidth - 140f, 32f);
					string text = $"{MaterialsList.Number(schematic.Count)} pieces   ·   {schematic.Size.x:0} x {schematic.Size.z:0} m, {schematic.Size.y:0} m high" + ((schematic.Saved.Length > 0) ? ("   ·   saved " + schematic.Saved) : "");
					Windows.Place(((TMP_Text)Windows.Text((Transform)(object)val, text, 18f, Windows.Dim, (TextAlignmentOptions)513)).rectTransform, 124f, 40f, rowWidth - 140f, 26f);
					buttons?.Invoke(val, schematic, rowWidth);
					num += 116f;
				}
				Windows.Done(window, num);
			}
		}
	}
	internal static class SchematicPlacer
	{
		internal sealed class Host
		{
			public MonoBehaviour Runner;

			public Func<Player, bool> Allowed;

			public Func<KeyboardShortcut> FreeKey;

			public Func<float> HeightStep;

			public Func<int> GhostPieces;

			public float Reach = 150f;

			public Func<Player, Plan, bool> Check;

			public Action<bool> Placing;

			public Action<Player, Plan, List<Piece>> Done;
		}

		internal sealed class Item
		{
			public Piece Piece;

			public string Prefab;

			public Vector3 Pos;

			public Quaternion Rot;
		}

		internal sealed class Plan
		{
			public string Name;

			public readonly List<Item> Items = new List<Item>();

			public int AlreadyThere;

			public readonly SortedDictionary<string, int> Missing = new SortedDictionary<string, int>();
		}

		private const int PastePerFrame = 150;

		private const float MaxShift = 2f;

		private const float Same = 0.1f;

		private static readonly Color GhostTint = new Color(0.12f, 0.3f, 0.4f);

		private static readonly EffectList NoEffects = new EffectList
		{
			m_effectPrefabs = (EffectData[])(object)new EffectData[0]
		};

		private static Host _host;

		private static string _name;

		private static string _file;

		private static List<SchematicLibrary.Entry> _entries;

		private static List<Vector3> _snaps;

		private static Vector3 _size;

		private static float _ground;

		private static GameObject _ghost;

		private static int _generation;

		private static bool _building;

		private static bool _pasting;

		private static bool _aimValid;

		private static bool _turnKnown;

		private static Vector3 _pos;

		private static Vector3 _lastBase = new Vector3(float.NaN, 0f, 0f);

		private static Vector3 _lastShift;

		private static Quaternion _rot;

		private static Quaternion _lastRot;

		private static bool _lastOnPiece;

		private static float _wheel;

		private static float _height;

		private static int _lastTurn;

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

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

		private static readonly List<Transform> SnapScratch = new List<Transform>();

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

		internal static readonly FieldRef<Player, int> PlaceRotation = AccessTools.FieldRefAccess<Player, int>("m_placeRotation");

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

		internal static readonly FieldRef<Player, int> PlaceRayMask = AccessTools.FieldRefAccess<Player, int>("m_placeRayMask");

		internal static readonly FieldRef<Player, PieceTable> BuildPieces = AccessTools.FieldRefAccess<Player, PieceTable>("m_buildPieces");

		internal static readonly FieldRef<Player, bool> NoPlacementCost = AccessTools.FieldRefAccess<Player, bool>("m_noPlacementCost");

		private static readonly FieldRef<Piece, ZNetView> PieceView = AccessTools.FieldRefAccess<Piece, ZNetView>("m_nview");

		private static List<Piece> _allPieces;

		internal static readonly List<Piece> LastPaste = new List<Piece>();

		internal static string LastPasteName = "";

		private static List<Piece> AllPieces => _allPieces ?? (_allPieces = AccessTools.Field(typeof(Piece), "s_allPieces")?.GetValue(null) as List<Piece>);

		internal static bool Chosen => _entries != null;

		internal static string ChosenFile => _file;

		internal static bool Pasting => _pasting;

		internal static bool CanPaste
		{
			get
			{
				if (_entries != null && _aimValid && (Object)(object)_ghost != (Object)null && !_building)
				{
					return !_pasting;
				}
				return false;
			}
		}

		private static bool Real(Piece piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			ZNetView val = PieceView.Invoke(piece);
			if ((Object)(object)val != (Object)null)
			{
				return val.IsValid();
			}
			return false;
		}

		internal static Piece Selected(Player player)
		{
			PieceTable val = (((Object)(object)player != (Object)null) ? BuildPieces.Invoke(player) : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.GetSelectedPiece();
		}

		internal static void Choose(Host host, string name, string file, List<SchematicLibrary.Entry> entries, Vector3 size, float ground)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			Drop();
			if (!((Object)(object)host?.Runner == (Object)null) && entries != null && entries.Count != 0)
			{
				_host = host;
				_name = name;
				_file = file;
				_entries = entries;
				_size = size;
				_ground = ground;
				_snaps = SnapsOf(entries);
				_height = 0f;
				_lastBase = new Vector3(float.NaN, 0f, 0f);
				host.Runner.StartCoroutine(BuildGhost(entries, size));
			}
		}

		internal static void Drop()
		{
			_generation++;
			if ((Object)(object)_ghost != (Object)null)
			{
				Object.Destroy((Object)(object)_ghost);
			}
			_ghost = null;
			_entries = null;
			_name = (_file = null);
			_building = false;
			_aimValid = false;
		}

		private static Piece PieceOf(string name)
		{
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(name) : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.GetComponent<Piece>();
		}

		private static List<Vector3> PrefabSnapsOf(string prefab)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (PrefabSnaps.TryGetValue(prefab, out var value))
			{
				return value;
			}
			value = new List<Vector3>();
			Piece val = PieceOf(prefab);
			if ((Object)(object)val != (Object)null)
			{
				SnapScratch.Clear();
				val.GetSnapPoints(SnapScratch);
				foreach (Transform item in SnapScratch)
				{
					value.Add(((Component)val).transform.InverseTransformPoint(item.position));
				}
			}
			PrefabSnaps[prefab] = value;
			return value;
		}

		private static List<Vector3> SnapsOf(List<SchematicLibrary.Entry> entries)
		{
			//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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			foreach (SchematicLibrary.Entry entry in entries)
			{
				foreach (Vector3 item in PrefabSnapsOf(entry.Prefab))
				{
					list.Add(entry.Pos + entry.Rot * item);
				}
			}
			return list;
		}

		private static bool Square(string prefab)
		{
			if (PrefabSquare.TryGetValue(prefab, out var value))
			{
				return value;
			}
			List<Vector3> list = PrefabSnapsOf(prefab);
			if (list.Count >= 2)
			{
				float num = list.Min((Vector3 p) => p.x);
				float num2 = list.Max((Vector3 p) => p.x);
				float num3 = list.Min((Vector3 p) => p.z);
				float num4 = list.Max((Vector3 p) => p.z);
				value = num2 - num > 0.1f && Mathf.Abs(num2 - num - (num4 - num3)) < 0.05f;
			}
			PrefabSquare[prefab] = value;
			return value;
		}

		private static IEnumerator BuildGhost(List<SchematicLibrary.Entry> entries, Vector3 size)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			int generation = ++_generation;
			_building = true;
			GameObject root = new GameObject("Digi_SchematicGhost");
			root.SetActive(false);
			_ghost = root;
			int num = ((_host.GhostPieces != null) ? Mathf.Max(50, _host.GhostPieces()) : 1500);
			float step = ((entries.Count > num) ? ((float)entries.Count / (float)num) : 1f);
			int made = 0;
			for (float f = 0f; f < (float)entries.Count; f += step)
			{
				if (generation != _generation || (Object)(object)root == (Object)null)
				{
					yield break;
				}
				SchematicLibrary.Entry entry = entries[(int)f];
				GameObject val = GhostCopy(entry.Prefab);
				if ((Object)(object)val != (Object)null)
				{
					val.transform.SetParent(root.transform, false);
					val.transform.localPosition = entry.Pos;
					val.transform.localRotation = entry.Rot;
				}
				int num2 = made + 1;
				made = num2;
				if (num2 % 40 == 0)
				{
					yield return null;
				}
			}
			if (step > 1f)
			{
				Box(root, size);
			}
			if (generation == _generation)
			{
				_building = false;
			}
		}

		private static GameObject GhostCopy(string name)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(name) : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			TerrainModifier componentInChildren = val.GetComponentInChildren<TerrainModifier>();
			bool enabled = (Object)(object)componentInChildren != (Object)null && ((Behaviour)componentInChildren).enabled;
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = false;
			}
			ZNetView.m_forceDisableInit = true;
			TerrainOp.m_forceDisableTerrainOps = true;
			GameObject val2;
			try
			{
				val2 = Object.Instantiate<GameObject>(val, new Vector3(0f, -5000f, 0f), Quaternion.identity);
			}
			finally
			{
				ZNetView.m_forceDisableInit = false;
				TerrainOp.m_forceDisableTerrainOps = false;
				if ((Object)(object)componentInChildren != (Object)null)
				{
					((Behaviour)componentInChildren).enabled = enabled;
				}
			}
			((Object)val2).name = name + " (ghost)";
			MonoBehaviour[] componentsInChildren = val2.GetComponentsInChildren<MonoBehaviour>(true);
			for (int num = componentsInChildren.Length - 1; num >= 0; num--)
			{
				if ((Object)(object)componentsInChildren[num] != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren[num]);
				}
			}
			Joint[] componentsInChildren2 = val2.GetComponentsInChildren<Joint>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			Rigidbody[] componentsInChildren3 = val2.GetComponentsInChildren<Rigidbody>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
			}
			Collider[] componentsInChildren4 = val2.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren4.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren4[i]);
			}
			Light[] componentsInChildren5 = val2.GetComponentsInChildren<Light>(true);
			for (int i = 0; i < componentsInChildren5.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren5[i]);
			}
			Component[] componentsInChildren6 = val2.GetComponentsInChildren<Component>(true);
			foreach (Component val3 in componentsInChildren6)
			{
				if (!((Object)(object)val3 == (Object)null))
				{
					string name2 = ((object)val3).GetType().Name;
					if (name2 == "AudioSource")
					{
						Object.DestroyImmediate((Object)(object)val3);
					}
					else if (name2 == "ParticleSystem")
					{
						val3.gameObject.SetActive(false);
					}
				}
			}
			int layer = LayerMask.NameToLayer("ghost");
			Transform[] componentsInChildren7 = val2.GetComponentsInChildren<Transform>(true);
			for (int i = 0; i < componentsInChildren7.Length; i++)
			{
				((Component)componentsInChildren7[i]).gameObject.layer = layer;
			}
			if ((Object)(object)MaterialMan.instance != (Object)null)
			{
				MaterialMan.instance.SetValue<Color>(val2, ShaderProps._EmissionColor, GhostTint, false);
			}
			return val2;
		}

		private static void Box(GameObject root, Vector3 size)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: 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_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: 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_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: 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_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: 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)
			Shader val = Shader.Find("Sprites/Default") ?? Shader.Find("Unlit/Color");
			if (!((Object)(object)val == (Object)null))
			{
				GameObject val2 = new GameObject("Box");
				val2.transform.SetParent(root.transform, false);
				LineRenderer val3 = val2.AddComponent<LineRenderer>();
				((Renderer)val3).material = new Material(val);
				Color val4 = default(Color);
				((Color)(ref val4))..ctor(0.2f, 0.9f, 1f, 0.85f);
				val3.endColor = val4;
				val3.startColor = val4;
				float startWidth = (val3.endWidth = 0.08f);
				val3.startWidth = startWidth;
				val3.useWorldSpace = false;
				((Renderer)val3).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)val3).receiveShadows = false;
				float num2 = size.x * 0.5f;
				float num3 = size.z * 0.5f;
				float y = size.y;
				Vector3 val5 = default(Vector3);
				((Vector3)(ref val5))..ctor(0f - num2, 0f, 0f - num3);
				Vector3 val6 = default(Vector3);
				((Vector3)(ref val6))..ctor(num2, 0f, 0f - num3);
				Vector3 val7 = default(Vector3);
				((Vector3)(ref val7))..ctor(num2, 0f, num3);
				Vector3 val8 = default(Vector3);
				((Vector3)(ref val8))..ctor(0f - num2, 0f, num3);
				Vector3 val9 = val5 + Vector3.up * y;
				Vector3 val10 = val6 + Vector3.up * y;
				Vector3 val11 = val7 + Vector3.up * y;
				Vector3 val12 = val8 + Vector3.up * y;
				Vector3[] array = (Vector3[])(object)new Vector3[16]
				{
					val5, val6, val7, val8, val5, val9, val10, val6, val10, val11,
					val7, val11, val12, val8, val12, val9
				};
				val3.positionCount = array.Length;
				val3.SetPositions(array);
			}
		}

		internal static void Tick()
		{
			//IL_00da: 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_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: 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_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			if (_entries == null || _host == null)
			{
				return;
			}
			if ((Object)(object)_ghost == (Object)null && !_building)
			{
				Drop();
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			bool num = (Object)(object)localPlayer != (Object)null && ((Character)localPlayer).InPlaceMode() && (_host.Allowed == null || _host.Allowed(localPlayer)) && !_building && !_pasting && !Windows.IsOpen && !TextInput.IsVisible() && !Menu.IsVisible();
			_aimValid = false;
			if (!num || !Aim(localPlayer, out var point, out var onPiece))
			{
				if ((Object)(object)_ghost != (Object)null && _ghost.activeSelf)
				{
					_ghost.SetActive(false);
				}
				_turnKnown = false;
				return;
			}
			int num2;
			if (_host.FreeKey != null)
			{
				KeyboardShortcut val = _host.FreeKey();
				num2 = (((KeyboardShortcut)(ref val)).IsPressed() ? 1 : 0);
			}
			else
			{
				num2 = 0;
			}
			bool flag = (byte)num2 != 0;
			GameObject val2 = PlacementGhost.Invoke(localPlayer);
			bool flag2 = (Object)(object)val2 != (Object)null && val2.activeInHierarchy;
			int num3 = 0;
			if (flag2)
			{
				num3 = (_turnKnown ? (PlaceRotation.Invoke(localPlayer) - _lastTurn) : 0);
			}
			else
			{
				_wheel += ZInput.GetMouseScrollWheel();
				if (_wheel > localPlayer.m_scrollAmountThreshold)
				{
					num3 = 1;
				}
				else if (_wheel < 0f - localPlayer.m_scrollAmountThreshold)
				{
					num3 = -1;
				}
				if (num3 != 0)
				{
					_wheel = 0f;
				}
			}
			if (num3 != 0 && flag)
			{
				if (flag2)
				{
					PlaceRotation.Invoke(localPlayer) -= num3;
				}
				_height += (float)num3 * ((_host.HeightStep != null) ? _host.HeightStep() : 0.25f);
				((Character)localPlayer).Message((MessageType)2, string.Format("Height {0}{1:0.00} m", (_height >= 0f) ? "+" : "", _height), 0, (Sprite)null, false);
			}
			else if (num3 != 0 && !flag2)
			{
				PlaceRotation.Invoke(localPlayer) += num3;
			}
			_lastTurn = PlaceRotation.Invoke(localPlayer);
			_turnKnown = true;
			Quaternion val3 = Quaternion.Euler(0f, 22.5f * (float)PlaceRotation.Invoke(localPlayer), 0f);
			Vector3 val4 = (onPiece ? point : (point + Vector3.up * (_height - _ground)));
			if (onPiece)
			{
				val4 += Vector3.up * _height;
			}
			Vector3 val5 = (flag ? val4 : (val4 + Shift(val4, val3, onPiece)));
			_ghost.transform.SetPositionAndRotation(val5, val3);
			if (!_ghost.activeSelf)
			{
				_ghost.SetActive(true);
			}
			_pos = val5;
			_rot = val3;
			_aimValid = true;
		}

		private static bool Aim(Player player, out Vector3 point, out bool onPiece)
		{
			//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_0025: 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_005a: 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)
			point = Vector3.zero;
			onPiece = false;
			GameCamera instance = GameCamera.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(((Component)instance).transform.position, ((Component)instance).transform.forward, ref val, _host.Reach, PlaceRayMask.Invoke(player), (QueryTriggerInteraction)1))
			{
				return false;
			}
			point = ((RaycastHit)(ref val)).point;
			onPiece = (Object)(object)((RaycastHit)(ref val)).collider != (Object)null && (Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Piece>() != (Object)null;
			return true;
		}

		private static Vector3 Shift(Vector3 basePos, Quaternion rot, bool onPiece)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_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_005a: 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)
			Vector3 val = basePos - _lastBase;
			if (((Vector3)(ref val)).sqrMagnitude < 0.0001f && rot == _lastRot && onPiece == _lastOnPiece)
			{
				return _lastShift;
			}
			_lastBase = basePos;
			_lastRot = rot;
			_lastOnPiece = onPiece;
			_lastShift = BestShift(basePos, rot, onPiece ? 1 : 2);
			return _lastShift;
		}

		private static Vector3 BestShift(Vector3 basePos, Quaternion rot, int need)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: 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_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: 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_0182: 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_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: 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_01af: 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_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0420: Unknown result type (might be due to invalid IL or missing references)
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			if (_snaps == null || _snaps.Count == 0)
			{
				return Vector3.zero;
			}
			float num = ((Vector3)(ref _size)).magnitude * 0.5f + 2f + 1f;
			Vector3 val = basePos + Vector3.up * (_size.y * 0.5f);
			Around.Clear();
			Piece.GetAllPiecesInRadius(val, num + 4f, Around);
			Dictionary<Vector3Int, List<Vector3>> dictionary = new Dictionary<Vector3Int, List<Vector3>>();
			bool flag = false;
			Vector3 val2 = Vector3.positiveInfinity;
			Vector3 val3 = Vector3.negativeInfinity;
			foreach (Piece item in Around)
			{
				if (!Real(item))
				{
					continue;
				}
				SnapScratch.Clear();
				item.GetSnapPoints(SnapScratch);
				foreach (Transform item2 in SnapScratch)
				{
					Vector3 position = item2.position;
					Vector3Int key = Cell(position);
					if (!dictionary.TryGetValue(key, out var value))
					{
						value = (dictionary[key] = new List<Vector3>());
					}
					value.Add(position);
					val2 = Vector3.Min(val2, position);
					val3 = Vector3.Max(val3, position);
					flag = true;
				}
			}
			if (!flag)
			{
				return Vector3.zero;
			}
			val2 -= Vector3.one * 2f;
			val3 += Vector3.one * 2f;
			Dictionary<Vector3Int, int> dictionary2 = new Dictionary<Vector3Int, int>();
			Dictionary<Vector3Int, Vector3> dictionary3 = new Dictionary<Vector3Int, Vector3>();
			Vector3Int key2 = default(Vector3Int);
			foreach (Vector3 snap in _snaps)
			{
				Vector3 val4 = basePos + rot * snap;
				if (val4.x < val2.x || val4.y < val2.y || val4.z < val2.z || val4.x > val3.x || val4.y > val3.y || val4.z > val3.z)
				{
					continue;
				}
				Vector3Int val5 = Cell(val4);
				for (int i = -1; i <= 1; i++)
				{
					for (int j = -1; j <= 1; j++)
					{
						for (int k = -1; k <= 1; k++)
						{
							if (!dictionary.TryGetValue(new Vector3Int(((Vector3Int)(ref val5)).x + i, ((Vector3Int)(ref val5)).y + j, ((Vector3Int)(ref val5)).z + k), out var value2))
							{
								continue;
							}
							foreach (Vector3 item3 in value2)
							{
								Vector3 val6 = item3 - val4;
								if (!(((Vector3)(ref val6)).sqrMagnitude > 4f))
								{
									((Vector3Int)(ref key2))..ctor(Mathf.RoundToInt(val6.x * 20f), Mathf.RoundToInt(val6.y * 20f), Mathf.RoundToInt(val6.z * 20f));
									dictionary2.TryGetValue(key2, out var value3);
									dictionary2[key2] = value3 + 1;
									if (value3 == 0)
									{
										dictionary3[key2] = val6;
									}
								}
							}
						}
					}
				}
			}
			Vector3 result = Vector3.zero;
			int num2 = need - 1;
			float num3 = float.MaxValue;
			foreach (KeyValuePair<Vector3Int, int> item4 in dictionary2)
			{
				Vector3 val7 = dictionary3[item4.Key];
				float sqrMagnitude = ((Vector3)(ref val7)).sqrMagnitude;
				if (item4.Value > num2 || (item4.Value == num2 && item4.Value >= need && sqrMagnitude < num3))
				{
					result = dictionary3[item4.Key];
					num2 = item4.Value;
					num3 = sqrMagnitude;
				}
			}
			if (num2 < need)
			{
				return Vector3.zero;
			}
			return result;
		}

		private static Vector3Int Cell(Vector3 p)
		{
			//IL_0000: 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_0022: 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)
			return new Vector3Int(Mathf.FloorToInt(p.x / 2f), Mathf.FloorToInt(p.y / 2f), Mathf.FloorToInt(p.z / 2f));
		}

		internal static void Paste(Player player)
		{
			//IL_002a: 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)
			if (CanPaste && !((Object)(object)player == (Object)null) && !((Object)(object)_host?.Runner == (Object)null))
			{
				Plan plan = MakePlan(_pos, _rot);
				if (_host.Check == null || _host.Check(player, plan))
				{
					_host.Runner.StartCoroutine(PasteRun(player, plan));
				}
			}
		}

		internal static Plan MakePlan(Vector3 pos, Quaternion rot)
		{
			//IL_0032: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: 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_01aa: Unknown result type (might be due to invalid IL or missing references)
			Plan plan = new Plan
			{
				Name = _name
			};
			float num = ((Vector3)(ref _size)).magnitude * 0.5f + 2f;
			Around.Clear();
			Piece.GetAllPiecesInRadius(pos + Vector3.up * (_size.y * 0.5f), num + 4f, Around);
			Dictionary<Vector3Int, List<Piece>> dictionary = new Dictionary<Vector3Int, List<Piece>>();
			foreach (Piece item in Around)
			{
				if (Real(item))
				{
					Vector3Int key = Vector3Int.FloorToInt(((Component)item).transform.position);
					if (!dictionary.TryGetValue(key, out var value))
					{
						value = (dictionary[key] = new List<Piece>());
					}
					value.Add(item);
				}
			}
			foreach (SchematicLibrary.Entry entry in _entries)
			{
				Piece val = PieceOf(entry.Prefab);
				if ((Object)(object)val == (Object)null)
				{
					plan.Missing.TryGetValue(entry.Prefab, out var value2);
					plan.Missing[entry.Prefab] = value2 + 1;
					continue;
				}
				Vector3 val2 = pos + rot * entry.Pos;
				Quaternion val3 = rot * entry.Rot;
				if (AlreadyThere(dictionary, entry.Prefab, val2, val3))
				{
					plan.AlreadyThere++;
					continue;
				}
				plan.Items.Add(new Item
				{
					Piece = val,
					Prefab = entry.Prefab,
					Pos = val2,
					Rot = val3
				});
			}
			return plan;
		}

		private static bool AlreadyThere(Dictionary<Vector3Int, List<Piece>> standing, string prefab, Vector3 p, Quaternion r)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//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_0013: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: 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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			Vector3Int val = Vector3Int.FloorToInt(p);
			Vector3 val2 = r * Vector3.up;
			Vector3 val3 = r * Vector3.forward;
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					for (int k = -1; k <= 1; k++)
					{
						if (!standing.TryGetValue(new Vector3Int(((Vector3Int)(ref val)).x + i, ((Vector3Int)(ref val)).y + j, ((Vector3Int)(ref val)).z + k), out var value))
						{
							continue;
						}
						foreach (Piece item in value)
						{
							if ((Object)(object)item == (Object)null)
							{
								continue;
							}
							Vector3 val4 = ((Component)item).transform.position - p;
							if (!(((Vector3)(ref val4)).sqrMagnitude > 0.010000001f) && !(Utils.GetPrefabName(((Component)item).gameObject) != prefab) && !(Vector3.Dot(((Component)item).transform.up, val2) < 0.98f))
							{
								float num = Mathf.Abs(Vector3.Dot(((Component)item).transform.forward, val3));
								if (num > 0.98f || (num < 0.17f && Square(prefab)))
								{
									return true;
								}
							}
						}
					}
				}
			}
			return false;
		}

		private static IEnumerator PasteRun(Player player, Plan plan)
		{
			_pasting = true;
			int turn = PlaceRotation.Invoke(player);
			int placed = 0;
			List<Piece> made = new List<Piece>();
			LastPaste.Clear();
			LastPasteName = plan.Name;
			try
			{
				foreach (Item item in plan.Items.OrderBy((Item x) => x.Pos.y))
				{
					if ((Object)(object)player == (Object)null)
					{
						yield break;
					}
					Piece piece = item.Piece;
					EffectList placeEffect = piece.m_placeEffect;
					if (placed > 0)
					{
						piece.m_placeEffect = NoEffects;
					}
					_host?.Placing?.Invoke(obj: true);
					try
					{
						player.PlacePiece(piece, item.Pos, item.Rot, false, false);
						List<Piece> allPieces = AllPieces;
						Piece val = ((allPieces != null && allPieces.Count > 0) ? allPieces[allPieces.Count - 1] : null);
						if ((Object)(object)val != (Object)null && Utils.GetPrefabName(((Component)val).gameObject) == item.Prefab)
						{
							made.Add(val);
						}
					}
					finally
					{
						_host?.Placing?.Invoke(obj: false);
						piece.m_placeEffect = placeEffect;
					}
					int num = placed + 1;
					placed = num;
					if (num % 150 == 0)
					{
						yield return null;
					}
				}
			}
			finally
			{
				_pasting = false;
				if ((Object)(object)player != (Object)null)
				{
					PlaceRotation.Invoke(player) = turn;
				}
				LastPaste.AddRange(made);
			}
			_lastBase = new Vector3(float.NaN, 0f, 0f);
			_host?.Done?.Invoke(player, plan, made);
		}

		internal static string MissingText(Plan plan)
		{
			if (plan.Missing.Count == 0)
			{
				return "";
			}
			return string.Format("{0} left out, from mods not installed: {1}", plan.Missing.Values.Sum(), string.Join(", ", plan.Missing.Keys.Take(4))) + ((plan.Missing.Count > 4) ? ", ..." : "");
		}
	}
	internal class StabilityMeter : MonoBehaviour
	{
		private struct Link
		{
			public int To;

			public float Factor;
		}

		private struct Rest
		{
			public int To;

			public float Factor;
		}

		private struct Memory
		{
			public int To;

			public float Value;

			public float Fixed;
		}

		private sealed class Node
		{
			public WearNTear Piece;

			public float Max;

			public float Min;

			public float Horizontal;

			public float Vertical;

			public bool Grounded;

			public bool Static;

			public bool Outside;

			public bool Read;

			public bool Alive = true;

			public bool CanBreak;

			public bool CanBreakKnown;

			public bool Tell;

			public bool Skip;

			public int Order;

			public float Value;

			public readonly List<Link> Links = new List<Link>();

			public readonly List<Rest> Rests = new List<Rest>();

			public List<int> Pairs = new List<int>();

			public List<WearNTear> Touching = new List<WearNTear>();

			public readonly List<Memory> Memory = new List<Memory>();
		}

		private struct Shown
		{
			public float Value;

			public float Max;

			public float Min;

			public bool Breaks;
		}

		private sealed class Geometry
		{
			public bool Grounded;

			public float At;

			public readonly List<WearNTear> Touching = new List<WearNTear>();

			public readonly List<WearNTear> LinkPieces = new List<WearNTear>();

			public readonly List<float> LinkFactors = new List<float>();

			public readonly List<WearNTear> RestPieces = new List<WearNTear>();

			public readonly List<float> RestFactors = new List<float>();

			public readonly List<int> Pairs = new List<int>();
		}

		internal static Func<bool> Wanted = () => true;

		internal static Func<bool> ShowValue = () => false;

		private const int MaxPieces = 5000;

		private const int MaxRounds = 3000;

		private const int MaxSteps = 3000000;

		private const float UrgentBudget = 0.01f;

		private const float BackgroundBudget = 0.0015f;

		private const float CellSize = 8f;

		private const float CacheAge = 60f;

		private const float Refresh = 3f;

		private static readonly MethodInfo MaterialProperties = AccessTools.Method(typeof(WearNTear), "GetMaterialProperties", (Type[])null, (Type[])null);

		private static readonly Func<WearNTear, float> SupportNow = AccessTools.MethodDelegate<Func<WearNTear, float>>(AccessTools.Method(typeof(WearNTear), "GetSupport", (Type[])null, (Type[])null), (object)null, true);

		private static readonly FieldRef<WearNTear, List<WearNTear>> RememberedPieces = AccessTools.FieldRefAccess<WearNTear, List<WearNTear>>("m_supportWearNTear");

		private static readonly FieldRef<WearNTear, List<float>> RememberedValues = AccessTools.FieldRefAccess<WearNTear, List<float>>("m_supportValue");

		private static readonly FieldRef<WearNTear, List<Collider>> RememberedColliders = AccessTools.FieldRefAccess<WearNTear, List<Collider>>("m_supportColliders");

		private static readonly FieldRef<WearNTear, bool> TellNeighbours = AccessTools.FieldRefAccess<WearNTear, bool>("m_clearCachedSupport");

		private static readonly FieldRef<WearNTear, int> ListIndex = AccessTools.FieldRefAccess<WearNTear, int>("m_myIndex");

		private static readonly List<Node> Nodes = new List<Node>();

		private static readonly Dictionary<WearNTear, int> Index = new Dictionary<WearNTear, int>();

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

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

		private static int _read;

		private static int _roundPos;

		private static int _rounds;

		private static int _steps;

		private static int _listCount;

		private static bool _solving;

		private static bool _changed;

		private static bool _reorder;

		private static bool _dirty;

		private static bool _noFall;

		private static float _solvedAt;

		private static float _nextWarmUp;

		private static int _prepared;

		private static readonly Dictionary<MaterialType, float[]> Materials = new Dictionary<MaterialType, float[]>();

		private static readonly Collider[] Hits = (Collider[])(object)new Collider[128];

		private static readonly List<Collider> HitColliders = new List<Collider>();

		private static readonly List<WearNTear> HitPieces = new List<WearNTear>();

		private static readonly List<Collider> Own = new List<Collider>();

		private static int _mask;

		private static int _pieceMask;

		private static int _terrain = -1;

		private static readonly Dictionary<WearNTear, Shown> Result = new Dictionary<WearNTear, Shown>();

		private static readonly Dictionary<WearNTear, Geometry> Cache = new Dictionary<WearNTear, Geometry>();

		private static readonly Dictionary<long, List<WearNTear>> Cells = new Dictionary<long, List<WearNTear>>();

		private static ZNetScene _scene;

		private GameObject _root;

		private RectTransform _fill;

		private Image _fillImage;

		private TextMeshProUGUI _text;

		internal static void Patch(Harmony harmony)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "OnPlaced", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(StabilityMeter), "Changed", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(StabilityMeter), "Appeared", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "OnDestroy", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(StabilityMeter), "Gone", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void Changed()
		{
			_dirty = true;
		}

		private static void Appeared(WearNTear __instance)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (Cache.Count != 0)
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.GetZDO() != null)
				{
					Forget(((Component)__instance).transform.position);
				}
			}
		}

		private static void Gone(WearNTear __instance)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (Index.ContainsKey(__instance) || Result.Remove(__instance))
			{
				_dirty = true;
			}
			if (Cache.Count > 0)
			{
				Forget(((Component)__instance).transform.position);
			}
		}

		private static long CellOf(Vector3 p, int dx, int dy, int dz)
		{
			//IL_0000: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			long num = Mathf.FloorToInt(p.x / 8f) + dx;
			long num2 = Mathf.FloorToInt(p.y / 8f) + dy;
			long num3 = Mathf.FloorToInt(p.z / 8f) + dz;
			return ((num & 0x1FFFFF) << 42) | ((num2 & 0x1FFFFF) << 21) | (num3 & 0x1FFFFF);
		}

		private static void Forget(Vector3 p)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					for (int k = -1; k <= 1; k++)
					{
						long key = CellOf(p, i, j, k);
						if (!Cells.TryGetValue(key, out var value))
						{
							continue;
						}
						foreach (WearNTear item in value)
						{
							Cache.Remove(item);
						}
						Cells.Remove(key);
					}
				}
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)_root);
			}
			Clear();
			Result.Clear();
			Cache.Clear();
			Cells.Clear();
		}

		private void Update()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)Hud.instance == (Object)null || !Wanted() || !((Character)localPlayer).InPlaceMode())
			{
				Show(on: false);
				return;
			}
			Piece val = (Hud.IsPieceSelectionVisible() ? null : localPlayer.GetHoveringPiece());
			WearNTear val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<WearNTear>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				Show(on: false);
				WarmUp();
				return;
			}
			Shown value;
			bool flag = Result.TryGetValue(val2, out value);
			if (!_solving)
			{
				if (!flag || _dirty || Time.time - _solvedAt > 3f)
				{
					Begin(val2);
				}
			}
			else if (!flag && !Index.ContainsKey(val2))
			{
				Begin(val2);
			}
			if (_solving)
			{
				Advance(flag ? 0.0015f