NSI.dll

Decompiled 6 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using NiflCore;
using Niflheim.Cores;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NiflCore
{
	internal static class Words
	{
		private static readonly Dictionary<string, string> English = new Dictionary<string, string>();

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

		private static ManualLogSource _log;

		private static bool _loaded;

		public static Func<bool> PadWording;

		public static Func<string, string> PadNames;

		public static void Load(ManualLogSource log)
		{
			if (_loaded)
			{
				return;
			}
			_loaded = true;
			_log = log;
			try
			{
				string text;
				using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("en.json"))
				{
					if (stream == null)
					{
						log.LogError((object)"lang/en.json is not in the dll; every line will show as its key");
						return;
					}
					using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
					text = streamReader.ReadToEnd();
				}
				Parse(text, English, log);
				LocalizationManager.Instance.GetLocalization().AddJsonFile("English", text);
				log.LogInfo((object)("words: " + English.Count + " lines of English loaded"));
			}
			catch (Exception ex)
			{
				log.LogError((object)("words: could not read lang/en.json, " + ex.Message));
			}
		}

		public static string T(string key)
		{
			if (PadWording != null && English.ContainsKey(key + "_pad") && PadWording())
			{
				if (PadNames == null)
				{
					return Read(key + "_pad");
				}
				return PadNames(Read(key + "_pad"));
			}
			return Read(key);
		}

		private static string Read(string key)
		{
			if (Localization.instance != null)
			{
				string text = Localization.instance.Localize("$" + key);
				if (!string.IsNullOrEmpty(text) && text != "[" + key + "]" && text != "$" + key)
				{
					return text;
				}
			}
			if (English.TryGetValue(key, out var value))
			{
				return value;
			}
			if (Missing.Add(key) && _log != null)
			{
				_log.LogWarning((object)("words: nothing under \"" + key + "\" in lang/en.json; the key is shown instead"));
			}
			return key;
		}

		public static string T(string key, params object[] fill)
		{
			try
			{
				return string.Format(T(key), fill);
			}
			catch (FormatException)
			{
				return T(key);
			}
		}

		private static void Parse(string json, Dictionary<string, string> into, ManualLogSource log)
		{
			int i = 0;
			string text = null;
			while (i < json.Length)
			{
				char c = json[i];
				if (c == '"')
				{
					string text2 = ReadString(json, ref i);
					if (text == null)
					{
						text = text2;
						continue;
					}
					into[text] = text2;
					text = null;
				}
				else if (text != null && c != ':' && !char.IsWhiteSpace(c))
				{
					log.LogWarning((object)("words: \"" + text + "\" in lang/en.json is not a string; skipped"));
					text = null;
					int num = 0;
					for (; i < json.Length; i++)
					{
						c = json[i];
						if (num == 0 && (c == ',' || c == '}'))
						{
							break;
						}
						switch (c)
						{
						case '[':
						case '{':
							num++;
							break;
						case ']':
						case '}':
							num--;
							break;
						}
					}
				}
				else
				{
					i++;
				}
			}
		}

		private static string ReadString(string json, ref int i)
		{
			StringBuilder stringBuilder = new StringBuilder();
			i++;
			while (i < json.Length && json[i] != '"')
			{
				char c = json[i];
				if (c == '\\' && i + 1 < json.Length)
				{
					c = json[++i];
					switch (c)
					{
					case 'n':
						c = '\n';
						break;
					case 't':
						c = '\t';
						break;
					case 'r':
						c = '\r';
						break;
					case 'b':
						c = '\b';
						break;
					case 'f':
						c = '\f';
						break;
					case 'u':
						if (i + 4 < json.Length)
						{
							c = (char)Convert.ToInt32(json.Substring(i + 1, 4), 16);
							i += 4;
						}
						break;
					}
				}
				stringBuilder.Append(c);
				i++;
			}
			i++;
			return stringBuilder.ToString();
		}
	}
	public class Pad : MonoBehaviour
	{
		public Func<Transform> Layer;

		public Func<Transform, GameObject> Default;

		public Action Back;

		public Action Close;

		public Func<GameObject, int, bool> Page;

		public Func<string> Hints;

		public Func<GameObject, Vector2, bool> AtEnd;

		public Func<Vector2, bool> Steer;

		public RectTransform HintArea;

		public static bool Pretend;

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

		public static string PretendHeld = "";

		public static Vector2 PretendRightStick;

		private GameObject _focus;

		private Transform _layer;

		private readonly Dictionary<Transform, GameObject> _lastIn = new Dictionary<Transform, GameObject>();

		private RectTransform _frame;

		private TMP_Text _hint;

		private UITooltip _tip;

		private GameObject _tipHadObject;

		private static readonly Color FrameColour = new Color(1f, 0.69f, 0.2f, 0.95f);

		private const float FrameWidth = 3f;

		private static InputField _typingInto;

		private static bool _steamKeyboard;

		private static Callback<GamepadTextInputDismissed_t> _dismissed;

		private static readonly Vector3[] Corners = (Vector3[])(object)new Vector3[4];

		private string _hintSaid;

		private static readonly string[][] Buttons = new string[9][]
		{
			new string[2] { "{A}", "JoyButtonA" },
			new string[2] { "{B}", "JoyButtonB" },
			new string[2] { "{X}", "JoyButtonX" },
			new string[2] { "{Y}", "JoyButtonY" },
			new string[2] { "{LB}", "JoyLBumper" },
			new string[2] { "{RB}", "JoyRBumper" },
			new string[2] { "{LT}", "JoyLTrigger" },
			new string[2] { "{RT}", "JoyRTrigger" },
			new string[2] { "{RS}", "JoyRStick" }
		};

		public static Pad Current { get; private set; }

		public static bool Split { get; private set; }

		public static bool Move { get; private set; }

		public static bool Active
		{
			get
			{
				if (!Pretend)
				{
					return ZInput.IsExclusiveGamepadActive();
				}
				return true;
			}
		}

		public static bool AltHeld
		{
			get
			{
				if (Active)
				{
					return Held("JoyLTrigger");
				}
				return false;
			}
		}

		public static Vector3 Pointer
		{
			get
			{
				//IL_0048: 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_003a: 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_0042: Unknown result type (might be due to invalid IL or missing references)
				if (Active && (Object)(object)Current != (Object)null && (Object)(object)Current._focus != (Object)null)
				{
					Rect val = Current.ScreenRect(Current._focus);
					return Vector2.op_Implicit(((Rect)(ref val)).center);
				}
				return Input.mousePosition;
			}
		}

		public static Vector2 RightStick
		{
			get
			{
				//IL_000d: 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)
				if (!Pretend)
				{
					return ZInput.GetJoyRightStick();
				}
				return PretendRightStick;
			}
		}

		public GameObject Focus => _focus;

		public static void Press(string button)
		{
			Queued.Add(button);
		}

		public static bool IsHeld(string button)
		{
			return Held(button);
		}

		private void Update()
		{
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: 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_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Layer != null) ? Layer() : null);
			if ((Object)(object)val != (Object)null && Active && Typing())
			{
				if (!_steamKeyboard && Down("JoyButtonB"))
				{
					StopTyping();
				}
				Queued.Clear();
				return;
			}
			if ((Object)(object)val == (Object)null || !Active)
			{
				SetFocus(null);
				ShowFrame(on: false);
				ShowHints(on: false);
				if ((Object)(object)Current == (Object)(object)this)
				{
					Current = null;
				}
				return;
			}
			Current = this;
			if ((Object)(object)EventSystem.current != (Object)null && (Object)(object)EventSystem.current.currentSelectedGameObject != (Object)null && (Object)(object)EventSystem.current.currentSelectedGameObject.GetComponent<InputField>() == (Object)null)
			{
				EventSystem.current.SetSelectedGameObject((GameObject)null);
			}
			if ((Object)(object)val != (Object)(object)_layer)
			{
				if ((Object)(object)_layer != (Object)null && (Object)(object)_focus != (Object)null)
				{
					_lastIn[_layer] = _focus;
				}
				_layer = val;
				SetFocus((_lastIn.TryGetValue(val, out var value) && Usable(value, val)) ? value : null);
			}
			if (!Usable(_focus, val))
			{
				SetFocus(Start(val));
			}
			Vector2 val2 = Direction();
			if (val2 != Vector2.zero && (Steer == null || !Steer(val2)) && !Adjust(val2))
			{
				Step(val, val2);
			}
			bool flag = Held("JoyLTrigger");
			if (Down("JoyButtonA"))
			{
				Activate(flag);
			}
			else if (Down("JoyButtonX"))
			{
				Click((InputButton)(!flag), split: false, flag);
			}
			else if (Down("JoyLBumper"))
			{
				PageBy(-1);
			}
			else if (Down("JoyRBumper"))
			{
				PageBy(1);
			}
			else if (Down("JoyButtonB"))
			{
				if (Back != null)
				{
					Back();
				}
			}
			else if (Down("JoyButtonY") && Close != null)
			{
				Close();
			}
			ShowFrame((Object)(object)_focus != (Object)null);
			ShowHints(on: true);
			Queued.Clear();
		}

		private void OnDisable()
		{
			SetFocus(null);
			ShowFrame(on: false);
			if ((Object)(object)Current == (Object)(object)this)
			{
				Current = null;
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)_frame != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_frame).gameObject);
			}
		}

		private static bool Down(string button)
		{
			foreach (string item in Queued)
			{
				if (item == button || item.EndsWith("+" + button))
				{
					return true;
				}
			}
			if (!Pretend)
			{
				return ZInput.GetButtonDown(button);
			}
			return false;
		}

		private static bool Held(string button)
		{
			foreach (string item in Queued)
			{
				if (item.StartsWith(button + "+"))
				{
					return true;
				}
			}
			if (Pretend)
			{
				return ("," + PretendHeld + ",").Contains("," + button + ",");
			}
			return ZInput.GetButton(button);
		}

		private static Vector2 Direction()
		{
			//IL_0018: 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_0054: 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)
			if (Down("JoyDPadUp") || Down("JoyLStickUp"))
			{
				return Vector2.up;
			}
			if (Down("JoyDPadDown") || Down("JoyLStickDown"))
			{
				return Vector2.down;
			}
			if (Down("JoyDPadLeft") || Down("JoyLStickLeft"))
			{
				return Vector2.left;
			}
			if (Down("JoyDPadRight") || Down("JoyLStickRight"))
			{
				return Vector2.right;
			}
			return Vector2.zero;
		}

		private List<GameObject> Targets(Transform layer)
		{
			List<GameObject> list = new List<GameObject>();
			HashSet<GameObject> hashSet = new HashSet<GameObject>();
			MonoBehaviour[] componentsInChildren = ((Component)layer).GetComponentsInChildren<MonoBehaviour>(false);
			foreach (MonoBehaviour val in componentsInChildren)
			{
				if ((val is Selectable || val is IPointerClickHandler || val is IPointerEnterHandler) && !(val is Scrollbar) && !(val is ScrollRect))
				{
					GameObject gameObject = ((Component)val).gameObject;
					if (hashSet.Add(gameObject) && Usable(gameObject, layer))
					{
						list.Add(gameObject);
					}
				}
			}
			return list;
		}

		private bool Usable(GameObject go, Transform layer)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)go == (Object)null || !go.activeInHierarchy || !go.transform.IsChildOf(layer))
			{
				return false;
			}
			Selectable component = go.GetComponent<Selectable>();
			if ((Object)(object)component != (Object)null)
			{
				if (!component.IsInteractable())
				{
					return false;
				}
			}
			else
			{
				Graphic component2 = go.GetComponent<Graphic>();
				if ((Object)(object)component2 == (Object)null || !component2.raycastTarget || !((Behaviour)component2).enabled)
				{
					return false;
				}
			}
			Transform val = go.transform;
			while ((Object)(object)val != (Object)null)
			{
				CanvasGroup component3 = ((Component)val).GetComponent<CanvasGroup>();
				if ((Object)(object)component3 != (Object)null && (!component3.blocksRaycasts || !component3.interactable))
				{
					return false;
				}
				if ((Object)(object)component3 != (Object)null && component3.ignoreParentGroups)
				{
					break;
				}
				val = val.parent;
			}
			Rect val2 = ScreenRect(go);
			if (((Rect)(ref val2)).width < 4f || ((Rect)(ref val2)).height < 4f)
			{
				return false;
			}
			if (((Rect)(ref val2)).xMax < 0f || ((Rect)(ref val2)).yMax < 0f || ((Rect)(ref val2)).xMin > (float)Screen.width || ((Rect)(ref val2)).yMin > (float)Screen.height)
			{
				return false;
			}
			Rect val3 = ScreenRect(((Component)layer).gameObject);
			if (((Rect)(ref val3)).width > 0f && ((Rect)(ref val2)).width * ((Rect)(ref val2)).height > ((Rect)(ref val3)).width * ((Rect)(ref val3)).height * 0.5f && (Object)(object)go.transform != (Object)(object)layer)
			{
				return false;
			}
			return true;
		}

		private GameObject Start(Transform layer)
		{
			//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)
			if (Default != null)
			{
				GameObject val = Default(layer);
				if (Usable(val, layer))
				{
					return val;
				}
			}
			GameObject result = null;
			float num = float.MaxValue;
			foreach (GameObject item in Targets(layer))
			{
				Rect val2 = ScreenRect(item);
				float num2 = (0f - ((Rect)(ref val2)).yMax) * 4f + ((Rect)(ref val2)).xMin;
				if (num2 < num)
				{
					num = num2;
					result = item;
				}
			}
			return result;
		}

		private void Step(Transform layer, Vector2 dir)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: 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_00a8: 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_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_focus == (Object)null)
			{
				SetFocus(Start(layer));
				return;
			}
			Rect val = ScreenRect(_focus);
			Vector2 center = ((Rect)(ref val)).center;
			bool flag = dir.x != 0f;
			GameObject val2 = null;
			float num = float.MaxValue;
			foreach (GameObject item in Targets(layer))
			{
				if ((Object)(object)item == (Object)(object)_focus)
				{
					continue;
				}
				Rect val3 = ScreenRect(item);
				Vector2 val4 = ((Rect)(ref val3)).center - center;
				float num2 = Vector2.Dot(val4, dir);
				if (num2 < 4f)
				{
					continue;
				}
				Vector2 val5 = val4 - dir * num2;
				float magnitude = ((Vector2)(ref val5)).magnitude;
				if (magnitude > num2 * 2f)
				{
					continue;
				}
				bool num3;
				if (!flag)
				{
					if (((Rect)(ref val3)).xMin < ((Rect)(ref val)).xMax)
					{
						num3 = ((Rect)(ref val3)).xMax > ((Rect)(ref val)).xMin;
						goto IL_0119;
					}
				}
				else if (((Rect)(ref val3)).yMin < ((Rect)(ref val)).yMax)
				{
					num3 = ((Rect)(ref val3)).yMax > ((Rect)(ref val)).yMin;
					goto IL_0119;
				}
				goto IL_011b;
				IL_0119:
				if (!num3)
				{
					goto IL_011b;
				}
				float num4 = 0f;
				goto IL_0127;
				IL_011b:
				num4 = 100000f;
				goto IL_0127;
				IL_0127:
				float num5 = num4 + num2 + magnitude * 3f;
				if (num5 < num)
				{
					num = num5;
					val2 = item;
				}
			}
			if ((Object)(object)val2 != (Object)null)
			{
				SetFocus(val2);
			}
			else if (AtEnd != null)
			{
				AtEnd(_focus, dir);
			}
		}

		public void FocusOn(GameObject go)
		{
			if ((Object)(object)go != (Object)null && (Object)(object)_layer != (Object)null && Usable(go, _layer))
			{
				SetFocus(go);
			}
		}

		private bool Adjust(Vector2 dir)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_focus == (Object)null || dir.x == 0f)
			{
				return false;
			}
			int num = ((dir.x > 0f) ? 1 : (-1));
			Slider component = _focus.GetComponent<Slider>();
			if ((Object)(object)component != (Object)null)
			{
				float num2 = (component.wholeNumbers ? 1f : ((component.maxValue - component.minValue) / 20f));
				component.value = Mathf.Clamp(component.value + (float)num * num2, component.minValue, component.maxValue);
				return true;
			}
			return false;
		}

		private void Activate(bool alt)
		{
			if ((Object)(object)_focus == (Object)null)
			{
				return;
			}
			InputField component = _focus.GetComponent<InputField>();
			if ((Object)(object)component != (Object)null)
			{
				AskForText(component);
				return;
			}
			Dropdown component2 = _focus.GetComponent<Dropdown>();
			if ((Object)(object)component2 != (Object)null && component2.options.Count > 0)
			{
				int count = component2.options.Count;
				component2.value = (component2.value + ((!alt) ? 1 : (count - 1))) % count;
			}
			else
			{
				Click((InputButton)0, alt, move: false);
			}
		}

		private void Click(InputButton button, bool split, bool move)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_focus == (Object)null || (Object)(object)EventSystem.current == (Object)null)
			{
				return;
			}
			GameObject eventHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(_focus);
			if ((Object)(object)eventHandler == (Object)null)
			{
				return;
			}
			PointerEventData val = Data(button);
			val.pointerPress = eventHandler;
			val.rawPointerPress = _focus;
			val.clickCount = 1;
			val.eligibleForClick = true;
			Split = split;
			Move = move;
			try
			{
				ExecuteEvents.Execute<IPointerClickHandler>(eventHandler, (BaseEventData)(object)val, ExecuteEvents.pointerClickHandler);
			}
			finally
			{
				Split = false;
				Move = false;
			}
		}

		private void PageBy(int step)
		{
			if (Page != null && (Object)(object)_focus != (Object)null)
			{
				Page(_focus, step);
			}
		}

		private PointerEventData Data(InputButton button)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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_0012: Expected O, but got Unknown
			//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_0030: Unknown result type (might be due to invalid IL or missing references)
			PointerEventData val = new PointerEventData(EventSystem.current)
			{
				button = button
			};
			if ((Object)(object)_focus != (Object)null)
			{
				Rect val2 = ScreenRect(_focus);
				val.position = ((Rect)(ref val2)).center;
			}
			return val;
		}

		private void SetFocus(GameObject next)
		{
			if ((Object)(object)next == (Object)(object)_focus)
			{
				return;
			}
			GameObject focus = _focus;
			_focus = next;
			LendTip(next);
			if (Pretend)
			{
				Debug.Log((object)("pad: highlight on " + Path(next)));
			}
			if ((Object)(object)EventSystem.current == (Object)null)
			{
				return;
			}
			List<GameObject> list = Chain(focus);
			List<GameObject> list2 = Chain(next);
			PointerEventData val = Data((InputButton)0);
			foreach (GameObject item in list)
			{
				if ((Object)(object)item != (Object)null && !list2.Contains(item))
				{
					ExecuteEvents.Execute<IPointerExitHandler>(item, (BaseEventData)(object)val, ExecuteEvents.pointerExitHandler);
				}
			}
			foreach (GameObject item2 in list2)
			{
				if (!list.Contains(item2))
				{
					ExecuteEvents.Execute<IPointerEnterHandler>(item2, (BaseEventData)(object)val, ExecuteEvents.pointerEnterHandler);
				}
			}
		}

		private static string Path(GameObject go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return "nothing";
			}
			string text = ((Object)go).name;
			Transform parent = go.transform.parent;
			while ((Object)(object)parent != (Object)null && text.Length < 120)
			{
				text = ((Object)parent).name + "/" + text;
				parent = parent.parent;
			}
			return text;
		}

		private List<GameObject> Chain(GameObject go)
		{
			List<GameObject> list = new List<GameObject>();
			Transform val = (((Object)(object)go != (Object)null) ? go.transform : null);
			while ((Object)(object)val != (Object)null)
			{
				list.Add(((Component)val).gameObject);
				if ((Object)(object)val == (Object)(object)((Component)this).transform)
				{
					break;
				}
				val = val.parent;
			}
			return list;
		}

		private void LendTip(GameObject next)
		{
			if ((Object)(object)_tip != (Object)null)
			{
				_tip.m_gamepadFocusObject = _tipHadObject;
			}
			_tip = (((Object)(object)next != (Object)null) ? next.GetComponent<UITooltip>() : null);
			if (!((Object)(object)_tip == (Object)null))
			{
				_tipHadObject = _tip.m_gamepadFocusObject;
				Frame();
				_tip.m_gamepadFocusObject = ((Component)_frame).gameObject;
			}
		}

		private void AskForText(InputField field)
		{
			//IL_0020: 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)
			_typingInto = field;
			string text = ((field.placeholder is Text) ? ((Text)field.placeholder).text : "");
			uint num = ((field.characterLimit > 0) ? ((uint)field.characterLimit) : 64u);
			try
			{
				if (SteamUtils.IsSteamInBigPictureMode())
				{
					if (_dismissed == null)
					{
						_dismissed = Callback<GamepadTextInputDismissed_t>.Create((DispatchDelegate<GamepadTextInputDismissed_t>)OnSteamKeyboardDone);
					}
					if (SteamUtils.ShowGamepadTextInput((EGamepadTextInputMode)0, (EGamepadTextInputLineMode)0, text, num, field.text))
					{
						_steamKeyboard = true;
						return;
					}
				}
			}
			catch (Exception)
			{
			}
			((Selectable)field).Select();
			field.ActivateInputField();
			try
			{
				if (SteamUtils.IsSteamRunningOnSteamDeck())
				{
					Rect val = ScreenRect(((Component)field).gameObject);
					SteamUtils.ShowFloatingGamepadTextInput((EFloatingGamepadTextInputMode)0, (int)((Rect)(ref val)).x, Screen.height - (int)((Rect)(ref val)).yMax, (int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height);
				}
			}
			catch (Exception)
			{
			}
		}

		private static void OnSteamKeyboardDone(GamepadTextInputDismissed_t done)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			_steamKeyboard = false;
			InputField typingInto = _typingInto;
			_typingInto = null;
			if (done.m_bSubmitted && !((Object)(object)typingInto == (Object)null))
			{
				uint enteredGamepadTextLength = SteamUtils.GetEnteredGamepadTextLength();
				string text = default(string);
				if (SteamUtils.GetEnteredGamepadTextInput(ref text, enteredGamepadTextLength + 1))
				{
					typingInto.text = text;
					((UnityEvent<string>)(object)typingInto.onEndEdit).Invoke(text);
				}
			}
		}

		private static bool Typing()
		{
			if (_steamKeyboard)
			{
				return true;
			}
			if ((Object)(object)_typingInto != (Object)null)
			{
				return _typingInto.isFocused;
			}
			return false;
		}

		private static void StopTyping()
		{
			if ((Object)(object)_typingInto != (Object)null)
			{
				_typingInto.DeactivateInputField();
			}
			_typingInto = null;
			if ((Object)(object)EventSystem.current != (Object)null)
			{
				EventSystem.current.SetSelectedGameObject((GameObject)null);
			}
		}

		private Rect ScreenRect(GameObject go)
		{
			//IL_0023: 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)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)(((Object)(object)go != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val == (Object)null)
			{
				return default(Rect);
			}
			Vector3[] corners = Corners;
			val.GetWorldCorners(corners);
			Canvas componentInParent = ((Component)val).GetComponentInParent<Canvas>();
			Camera obj = (((Object)(object)componentInParent != (Object)null && (int)componentInParent.renderMode != 0) ? componentInParent.worldCamera : null);
			Vector2 val2 = RectTransformUtility.WorldToScreenPoint(obj, corners[0]);
			Vector2 val3 = RectTransformUtility.WorldToScreenPoint(obj, corners[2]);
			return Rect.MinMaxRect(Mathf.Min(val2.x, val3.x), Mathf.Min(val2.y, val3.y), Mathf.Max(val2.x, val3.x), Mathf.Max(val2.y, val3.y));
		}

		private void Frame()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0093: 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_009a: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: 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_00d6: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: 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_012d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_frame != (Object)null))
			{
				GameObject val = new GameObject("pad_highlight", new Type[1] { typeof(RectTransform) });
				val.transform.SetParent(((Object)(object)((Component)this).transform.parent != (Object)null) ? ((Component)this).transform.parent : ((Component)this).transform, false);
				_frame = (RectTransform)val.transform;
				RectTransform frame = _frame;
				RectTransform frame2 = _frame;
				RectTransform frame3 = _frame;
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor(0.5f, 0.5f);
				frame3.pivot = val2;
				Vector2 anchorMin = (frame2.anchorMax = val2);
				frame.anchorMin = anchorMin;
				Edge(new Vector2(0f, 1f), new Vector2(1f, 1f));
				Edge(new Vector2(0f, 0f), new Vector2(1f, 0f));
				Edge(new Vector2(0f, 0f), new Vector2(0f, 1f));
				Edge(new Vector2(1f, 0f), new Vector2(1f, 1f));
				val.SetActive(false);
			}
		}

		private void Edge(Vector2 min, Vector2 max)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("edge", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent((Transform)(object)_frame, false);
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = FrameColour;
			((Graphic)component).raycastTarget = false;
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = min;
			val2.anchorMax = max;
			bool flag = min.y == max.y;
			val2.sizeDelta = (flag ? new Vector2(6f, 3f) : new Vector2(3f, 6f));
			val2.anchoredPosition = Vector2.zero;
		}

		private void ShowFrame(bool on)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: 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)
			if (!on)
			{
				if ((Object)(object)_frame != (Object)null)
				{
					((Component)_frame).gameObject.SetActive(false);
				}
				return;
			}
			Frame();
			Transform transform = _focus.transform;
			Transform obj = ((transform is RectTransform) ? transform : null);
			Vector3[] corners = Corners;
			((RectTransform)obj).GetWorldCorners(corners);
			((Component)_frame).gameObject.SetActive(true);
			((Transform)_frame).SetAsLastSibling();
			((Transform)_frame).position = (corners[0] + corners[2]) * 0.5f;
			Vector3 lossyScale = ((Transform)_frame).lossyScale;
			Vector3 val = corners[2] - corners[0];
			_frame.sizeDelta = new Vector2(Mathf.Abs(val.x / lossyScale.x) + 6f, Mathf.Abs(val.y / lossyScale.y) + 6f);
		}

		private void ShowHints(bool on)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)HintArea == (Object)null)
			{
				return;
			}
			if ((Object)(object)_hint == (Object)null)
			{
				if (!on)
				{
					return;
				}
				TMP_Text val = ((Component)this).GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)val == (Object)null || (Object)(object)val.font == (Object)null)
				{
					TMP_Text[] array = Resources.FindObjectsOfTypeAll<TMP_Text>();
					foreach (TMP_Text val2 in array)
					{
						if ((Object)(object)val2.font != (Object)null)
						{
							val = val2;
							break;
						}
					}
				}
				GameObject val3 = new GameObject("pad_hints", new Type[1] { typeof(RectTransform) });
				val3.transform.SetParent((Transform)(object)HintArea, false);
				RectTransform val4 = (RectTransform)val3.transform;
				val4.anchorMin = Vector2.zero;
				val4.anchorMax = Vector2.one;
				Vector2 offsetMin = (val4.offsetMax = Vector2.zero);
				val4.offsetMin = offsetMin;
				_hint = (TMP_Text)(object)val3.AddComponent<TextMeshProUGUI>();
				if ((Object)(object)val != (Object)null && (Object)(object)val.font != (Object)null)
				{
					_hint.font = val.font;
					_hint.fontSharedMaterial = val.fontSharedMaterial;
				}
				if (Pretend)
				{
					Debug.Log((object)("pad: prompts drawn in " + (((Object)(object)_hint.font != (Object)null) ? ((Object)_hint.font).name : "no font")));
				}
				_hint.fontSize = 18f;
				_hint.alignment = (TextAlignmentOptions)514;
				((Graphic)_hint).color = new Color(0.93f, 0.87f, 0.75f);
				((Graphic)_hint).raycastTarget = false;
				_hint.richText = true;
			}
			((Component)_hint).gameObject.SetActive(on);
			string text = ((on && Hints != null) ? Hints() : null);
			if (text != _hintSaid)
			{
				_hintSaid = text;
				if (text != null)
				{
					_hint.text = Glyphs(text);
				}
			}
		}

		public static string Named(string text)
		{
			if (string.IsNullOrEmpty(text) || text.IndexOf('%') < 0)
			{
				return text;
			}
			string[][] buttons = Buttons;
			foreach (string[] array in buttons)
			{
				string text2 = "%" + array[0].Trim('{', '}') + "%";
				if (text.IndexOf(text2, StringComparison.Ordinal) >= 0)
				{
					text = text.Replace(text2, ShortName(array[1], array[0].Trim('{', '}')));
				}
			}
			return text;
		}

		private static string ShortName(string button, string fallback)
		{
			string text = ((ZInput.instance != null) ? ZInput.instance.GetBoundKeyString(button, true) : "");
			int num = text?.IndexOf("name=\"", StringComparison.Ordinal) ?? (-1);
			if (num < 0)
			{
				return fallback;
			}
			int num2 = num + 6;
			int num3 = text.IndexOf('"', num2);
			if (num3 <= num2)
			{
				return fallback;
			}
			string text2 = text.Substring(num2, num3 - num2);
			if (text2.StartsWith("button_"))
			{
				text2 = text2.Substring(7);
			}
			if (text2.Length > 2)
			{
				return char.ToUpperInvariant(text2[0]) + text2.Substring(1);
			}
			return text2.ToUpperInvariant();
		}

		private static string Glyphs(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return "";
			}
			string[][] buttons = Buttons;
			foreach (string[] array in buttons)
			{
				if (text.IndexOf(array[0], StringComparison.Ordinal) >= 0)
				{
					string text2 = ((ZInput.instance != null) ? ZInput.instance.GetBoundKeyString(array[1], true) : "");
					if (string.IsNullOrEmpty(text2))
					{
						text2 = array[0].Trim('{', '}');
					}
					text = text.Replace(array[0], text2);
				}
			}
			return text;
		}
	}
	internal static class Looks
	{
		public static GameObject Part(Transform parent, string name, int layer, Mesh mesh, params Material[] looks)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			GameObject val = new GameObject(name, new Type[2]
			{
				typeof(MeshFilter),
				typeof(MeshRenderer)
			})
			{
				layer = layer
			};
			val.transform.SetParent(parent, false);
			val.GetComponent<MeshFilter>().sharedMesh = mesh;
			((Renderer)val.GetComponent<MeshRenderer>()).sharedMaterials = looks;
			return val;
		}

		public static Texture2D Picture(string name, int width, int height, Color[] pixels, bool mipmaps, TextureWrapMode wrap, FilterMode filter = (FilterMode)1)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_000c: 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)
			Texture2D val = new Texture2D(width, height, (TextureFormat)4, mipmaps);
			((Texture)val).filterMode = filter;
			val.SetPixels(pixels);
			val.Apply(mipmaps);
			if (name != null)
			{
				((Object)val).name = name;
			}
			((Texture)val).wrapMode = wrap;
			return val;
		}

		public static void StripTextures(Material m)
		{
			string[] array = new string[10] { "_MainTex", "_BaseMap", "_EmissionMap", "_EmissiveTex", "_GlowTex", "_BumpMap", "_MetallicGlossMap", "_OcclusionMap", "_DetailAlbedoMap", "_DetailNormalMap" };
			foreach (string text in array)
			{
				if (m.HasProperty(text))
				{
					m.SetTexture(text, (Texture)null);
				}
			}
			m.DisableKeyword("_NORMALMAP");
			m.DisableKeyword("_METALLICGLOSSMAP");
		}

		public static void ClearTextures(Material m, string keep = null)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			Shader shader = m.shader;
			for (int i = 0; i < shader.GetPropertyCount(); i++)
			{
				if ((int)shader.GetPropertyType(i) == 4)
				{
					string propertyName = shader.GetPropertyName(i);
					if (propertyName != keep)
					{
						m.SetTexture(propertyName, (Texture)null);
					}
				}
			}
		}

		public static void Fade(Material m, int queue)
		{
			if (m.HasProperty("_Mode"))
			{
				m.SetFloat("_Mode", 2f);
			}
			m.SetInt("_SrcBlend", 5);
			m.SetInt("_DstBlend", 10);
			m.SetInt("_ZWrite", 0);
			m.DisableKeyword("_ALPHATEST_ON");
			m.EnableKeyword("_ALPHABLEND_ON");
			m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
			m.SetOverrideTag("RenderType", "Transparent");
			m.renderQueue = queue;
		}

		public static Color Full(Color c)
		{
			//IL_0000: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			c *= 1f / Mathf.Max(0.001f, ((Color)(ref c)).maxColorComponent);
			c.a = 1f;
			return c;
		}

		public static Color32[] ReadSmall(Texture picture, int n)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			RenderTexture temporary = RenderTexture.GetTemporary(n, n, 0, (RenderTextureFormat)0);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit(picture, temporary);
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(n, n, (TextureFormat)4, false);
				val.ReadPixels(new Rect(0f, 0f, (float)n, (float)n), 0, 0);
				val.Apply(false);
				Color32[] pixels = val.GetPixels32();
				Object.Destroy((Object)val);
				return pixels;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
}
namespace NSI
{
	internal static class Automation
	{
		private static float _next;

		private static int _cursor;

		internal static bool Busy;

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

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

		private static readonly Dictionary<StorageTerminal, List<Container>> _inputs = new Dictionary<StorageTerminal, List<Container>>();

		private static readonly Dictionary<StorageTerminal, List<Container>> _outputs = new Dictionary<StorageTerminal, List<Container>>();

		internal static int Allowance(StorageTerminal line)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			float num = Tiers.Rate(line.Tier);
			if (num <= 0f)
			{
				return 0;
			}
			string id = line.Id;
			float unscaledTime = Time.unscaledTime;
			if (!_budget.TryGetValue(id, out var value))
			{
				value = 1f;
			}
			if (!_budgetAt.TryGetValue(id, out var value2))
			{
				value2 = unscaledTime;
			}
			value = Mathf.Min(value + (unscaledTime - value2) * num, Mathf.Max(1f, num));
			_budget[id] = value;
			_budgetAt[id] = unscaledTime;
			return Mathf.FloorToInt(value);
		}

		internal static void Spend(StorageTerminal line, int items)
		{
			if (items > 0 && _budget.TryGetValue(line.Id, out var value))
			{
				_budget[line.Id] = Mathf.Max(0f, value - (float)items);
			}
		}

		internal static List<Container> Inputs(StorageTerminal line)
		{
			if (_inputs.TryGetValue(line, out var value))
			{
				return value;
			}
			value = Line.Chests(line, LineMark.Input);
			Func<Container, int> priority = Priority.Remembered();
			value.Sort((Container a, Container b) => priority(a).CompareTo(priority(b)));
			_inputs[line] = value;
			return value;
		}

		internal static List<Container> Outputs(StorageTerminal line)
		{
			if (!_outputs.TryGetValue(line, out var value))
			{
				value = (_outputs[line] = Line.Chests(line, LineMark.Output));
			}
			return value;
		}

		internal static void Tick()
		{
			if (Busy || Time.unscaledTime < _next || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			_next = Time.unscaledTime + 0.5f;
			_inputs.Clear();
			_outputs.Clear();
			Machine.Instances.RemoveAll((Machine m) => (Object)(object)m == (Object)null);
			if (StorageTerminal.All.Count == 0)
			{
				return;
			}
			List<Machine> list = new List<Machine>();
			Dictionary<Machine, string> ids = new Dictionary<Machine, string>();
			foreach (Machine instance in Machine.Instances)
			{
				if (instance.Mine && ((Component)instance).gameObject.activeInHierarchy)
				{
					instance.EnsureId();
					ids[instance] = instance.Id;
					list.Add(instance);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			list.Sort((Machine a, Machine b) => string.CompareOrdinal(ids[a], ids[b]));
			for (int num = 0; num < list.Count; num++)
			{
				int num2 = (_cursor + num) % list.Count;
				if (list[num2].Serve())
				{
					_cursor = (num2 + 1) % list.Count;
					break;
				}
			}
		}
	}
	public class Machine : MonoBehaviour
	{
		private static readonly Action<Smelter, long> SmelterFuel = GameCode.Method<Action<Smelter, long>>(typeof(Smelter), "RPC_AddFuel");

		private static readonly Action<Smelter, long, string, bool> SmelterOre = GameCode.Method<Action<Smelter, long, string, bool>>(typeof(Smelter), "RPC_AddOre");

		private static readonly Action<Fireplace, long> FireFuel = GameCode.Method<Action<Fireplace, long>>(typeof(Fireplace), "RPC_AddFuel");

		private static readonly Action<CookingStation, long> CookingFuel = GameCode.Method<Action<CookingStation, long>>(typeof(CookingStation), "RPC_AddFuel");

		private static readonly Action<ShieldGenerator, long> ShieldFuel = GameCode.Method<Action<ShieldGenerator, long>>(typeof(ShieldGenerator), "RPC_AddFuel");

		private static readonly MethodInfo SetCookingSlot = GameCode.Info(typeof(CookingStation), "SetSlot");

		private bool _collectFirst;

		private bool _inputFirst;

		private bool _cannotEmpty;

		internal static readonly List<Machine> Instances = new List<Machine>();

		private ZNetView _view;

		private Smelter _smelter;

		private Fireplace _fire;

		private CookingStation _cooking;

		private ShieldGenerator _shield;

		private string _lastTrace;

		private float _lastTraceAt;

		internal Sprite MovedIn;

		internal Sprite MovedOut;

		internal float MovedInAt = -1f;

		internal float MovedOutAt = -1f;

		internal bool Valid
		{
			get
			{
				if ((Object)(object)_view != (Object)null)
				{
					return _view.IsValid();
				}
				return false;
			}
		}

		internal bool Mine
		{
			get
			{
				if (Valid)
				{
					return _view.IsOwner();
				}
				return false;
			}
		}

		internal string Id
		{
			get
			{
				if (!Valid)
				{
					return "";
				}
				return _view.GetZDO().GetString("nsi_id", "");
			}
		}

		internal bool CanRefill
		{
			get
			{
				if ((!((Object)(object)_smelter != (Object)null) || ((_smelter.m_maxFuel <= 0 || !((Object)(object)_smelter.m_fuelItem != (Object)null)) && (_smelter.m_maxOre <= 0 || _smelter.m_conversion.Count <= 0))) && (!((Object)(object)_fire != (Object)null) || !_fire.m_canRefill || _fire.m_infiniteFuel || !(_fire.m_maxFuel > 0f) || !((Object)(object)_fire.m_fuelItem != (Object)null)) && (!((Object)(object)_cooking != (Object)null) || !_cooking.m_useFuel || _cooking.m_maxFuel <= 0 || !((Object)(object)_cooking.m_fuelItem != (Object)null)))
				{
					if ((Object)(object)_shield != (Object)null && _shield.m_maxFuel > 0)
					{
						return _shield.m_fuelItems.Count > 0;
					}
					return false;
				}
				return true;
			}
		}

		internal bool CanCollect
		{
			get
			{
				if ((Object)(object)_smelter != (Object)null)
				{
					foreach (ItemConversion item in _smelter.m_conversion)
					{
						if ((Object)(object)item.m_to != (Object)null)
						{
							return true;
						}
					}
					return false;
				}
				if ((Object)(object)_cooking != (Object)null && _cooking.m_slots != null && _cooking.m_slots.Length != 0 && SetCookingSlot != null)
				{
					foreach (ItemConversion item2 in _cooking.m_conversion)
					{
						if ((Object)(object)item2.m_to != (Object)null)
						{
							return true;
						}
					}
				}
				return false;
			}
		}

		private ItemDrop FuelItem
		{
			get
			{
				if (!((Object)(object)_smelter != (Object)null))
				{
					if (!((Object)(object)_fire != (Object)null))
					{
						if (!((Object)(object)_cooking != (Object)null))
						{
							return null;
						}
						return _cooking.m_fuelItem;
					}
					return _fire.m_fuelItem;
				}
				return _smelter.m_fuelItem;
			}
		}

		private ItemDrop FirstFuel
		{
			get
			{
				if ((Object)(object)_smelter != (Object)null || (Object)(object)_fire != (Object)null || (Object)(object)_cooking != (Object)null)
				{
					return FuelItem;
				}
				if (!((Object)(object)_shield != (Object)null) || _shield.m_fuelItems.Count <= 0)
				{
					return null;
				}
				return _shield.m_fuelItems[0];
			}
		}

		internal float FuelMax
		{
			get
			{
				if ((Object)(object)_smelter != (Object)null)
				{
					if (!((Object)(object)_smelter.m_fuelItem != (Object)null))
					{
						return 0f;
					}
					return _smelter.m_maxFuel;
				}
				if ((Object)(object)_fire != (Object)null)
				{
					if (!_fire.m_canRefill || _fire.m_infiniteFuel)
					{
						return 0f;
					}
					return _fire.m_maxFuel;
				}
				if ((Object)(object)_cooking != (Object)null)
				{
					if (!_cooking.m_useFuel)
					{
						return 0f;
					}
					return _cooking.m_maxFuel;
				}
				if (!((Object)(object)_shield != (Object)null))
				{
					return 0f;
				}
				return _shield.m_maxFuel;
			}
		}

		internal bool UsesFuel => FuelMax > 0f;

		internal float FuelNow
		{
			get
			{
				if (!Valid)
				{
					return 0f;
				}
				return _view.GetZDO().GetFloat(ZDOVars.s_fuel, ((Object)(object)_shield != (Object)null) ? ((float)_shield.m_defaultFuel) : 0f);
			}
		}

		internal bool HasQueue
		{
			get
			{
				if ((Object)(object)_smelter != (Object)null)
				{
					return _smelter.m_maxOre > 0;
				}
				return false;
			}
		}

		internal int QueueMax
		{
			get
			{
				if (!((Object)(object)_smelter != (Object)null))
				{
					return 0;
				}
				return _smelter.m_maxOre;
			}
		}

		internal int Queued
		{
			get
			{
				if (!Valid || !((Object)(object)_smelter != (Object)null))
				{
					return 0;
				}
				return _view.GetZDO().GetInt(ZDOVars.s_queued, 0);
			}
		}

		internal string DisplayName
		{
			get
			{
				Piece val = ((Component)this).GetComponent<Piece>() ?? ((Component)this).GetComponentInParent<Piece>();
				string text = (((Object)(object)val != (Object)null) ? val.m_name : (((Object)(object)_smelter != (Object)null) ? _smelter.m_name : ((Object)this).name));
				return Localization.instance.Localize(text);
			}
		}

		internal Sprite Icon
		{
			get
			{
				Piece val = ((Component)this).GetComponent<Piece>() ?? ((Component)this).GetComponentInParent<Piece>();
				if (!((Object)(object)val != (Object)null))
				{
					return null;
				}
				return val.m_icon;
			}
		}

		internal string Status
		{
			get
			{
				if (!Valid)
				{
					return "";
				}
				ZDO zDO = _view.GetZDO();
				List<string> list = new List<string>();
				float num = (((Object)(object)_smelter != (Object)null) ? ((float)_smelter.m_maxFuel) : (((Object)(object)_fire != (Object)null) ? _fire.m_maxFuel : (((Object)(object)_cooking != (Object)null && _cooking.m_useFuel) ? ((float)_cooking.m_maxFuel) : (((Object)(object)_shield != (Object)null) ? ((float)_shield.m_maxFuel) : 0f))));
				if ((((Object)(object)_smelter != (Object)null) ? ((Object)(object)_smelter.m_fuelItem != (Object)null) : (num > 0f)) && num > 0f)
				{
					list.Add(Txt.T("nsi_fuel_amount", Mathf.CeilToInt(zDO.GetFloat(ZDOVars.s_fuel, 0f)), Mathf.RoundToInt(num)));
				}
				if ((Object)(object)_smelter != (Object)null && _smelter.m_maxOre > 0)
				{
					list.Add(Txt.T("nsi_queue_amount", zDO.GetInt(ZDOVars.s_queued, 0), _smelter.m_maxOre));
				}
				return string.Join("   ", list.ToArray());
			}
		}

		private string FuelName
		{
			get
			{
				ItemDrop fuelItem = FuelItem;
				if (!((Object)(object)fuelItem != (Object)null))
				{
					return Txt.T("nsi_fuel_word");
				}
				return Localization.instance.Localize(fuelItem.m_itemData.m_shared.m_name).ToLowerInvariant();
			}
		}

		internal bool Serve()
		{
			_collectFirst = !_collectFirst;
			foreach (StorageTerminal item in StorageTerminal.All)
			{
				if (!OnAwakeLine(item))
				{
					continue;
				}
				bool flag = CanRefill && Flag(Line.FillKey(item));
				bool flag2 = CanCollect && Flag(Line.TakeKey(item));
				if (!flag && !flag2)
				{
					continue;
				}
				bool num;
				if (!_collectFirst)
				{
					if (!flag || !TryRefill(item))
					{
						if (!flag2)
						{
							continue;
						}
						num = TryCollect(item);
						goto IL_00a8;
					}
				}
				else if (!flag2 || !TryCollect(item))
				{
					if (!flag)
					{
						continue;
					}
					num = TryRefill(item);
					goto IL_00a8;
				}
				goto IL_00aa;
				IL_00a8:
				if (!num)
				{
					continue;
				}
				goto IL_00aa;
				IL_00aa:
				return true;
			}
			return false;
		}

		private static int FuelRoom(float fuel, float maximum, bool ceil)
		{
			return Math.Max(0, Mathf.FloorToInt(maximum - (ceil ? Mathf.Ceil(fuel) : fuel)));
		}

		private int Room(Feed kind)
		{
			if (!Valid)
			{
				return 0;
			}
			ZDO zDO = _view.GetZDO();
			if (kind == Feed.Fuel)
			{
				if ((Object)(object)FuelItem == (Object)null && ((Object)(object)_shield == (Object)null || _shield.m_fuelItems.Count == 0))
				{
					return 0;
				}
				return FuelRoom(FuelNow, FuelMax, (Object)(object)_fire != (Object)null);
			}
			if ((Object)(object)_smelter != (Object)null)
			{
				return Math.Max(0, _smelter.m_maxOre - zDO.GetInt(ZDOVars.s_queued, 0));
			}
			return 0;
		}

		private static string Prefab(ItemData item)
		{
			if (item == null || !((Object)(object)item.m_dropPrefab != (Object)null))
			{
				return null;
			}
			return ((Object)item.m_dropPrefab).name;
		}

		private bool Allows(ItemData item, Feed kind)
		{
			if (item == null || item.m_shared == null || item.m_stack <= 0)
			{
				return false;
			}
			if (item.m_worldLevel < Game.m_worldLevel)
			{
				return false;
			}
			if (kind == Feed.Fuel)
			{
				return Burns(item.m_shared.m_name);
			}
			return SmelterRecipe(Prefab(item)) != null;
		}

		private int Measure(Feed kind)
		{
			ZDO zDO = _view.GetZDO();
			if (kind != Feed.Fuel)
			{
				if (!((Object)(object)_smelter != (Object)null))
				{
					return 0;
				}
				return zDO.GetInt(ZDOVars.s_queued, 0);
			}
			return Mathf.RoundToInt(zDO.GetFloat(ZDOVars.s_fuel, 0f) * 10000f);
		}

		private bool AddOne(ItemData item, Feed kind)
		{
			if (!_view.IsOwner() || Room(kind) <= 0)
			{
				return false;
			}
			int num = Measure(kind);
			long owner = _view.GetZDO().GetOwner();
			try
			{
				if (kind == Feed.Input)
				{
					if ((Object)(object)_smelter != (Object)null && SmelterOre != null)
					{
						SmelterOre(_smelter, owner, Prefab(item), item.m_cheated);
					}
				}
				else if ((Object)(object)_smelter != (Object)null)
				{
					if (SmelterFuel != null)
					{
						SmelterFuel(_smelter, owner);
					}
				}
				else if ((Object)(object)_fire != (Object)null)
				{
					if (FireFuel != null)
					{
						FireFuel(_fire, owner);
					}
				}
				else if ((Object)(object)_cooking != (Object)null)
				{
					if (CookingFuel != null)
					{
						CookingFuel(_cooking, owner);
					}
				}
				else if ((Object)(object)_shield != (Object)null && ShieldFuel != null)
				{
					ShieldFuel(_shield, owner);
				}
			}
			catch (Exception ex)
			{
				NSIPlugin.Log.LogError((object)ex);
			}
			return Measure(kind) > num;
		}

		private bool TryRefill(StorageTerminal line)
		{
			if (Automation.Allowance(line) <= 0)
			{
				return false;
			}
			Feed[] obj = ((!_inputFirst) ? new Feed[2]
			{
				Feed.Fuel,
				Feed.Input
			} : new Feed[2]
			{
				Feed.Input,
				Feed.Fuel
			});
			List<Container> list = null;
			Feed[] array = obj;
			for (int i = 0; i < array.Length; i++)
			{
				Feed kind = array[i];
				if (Room(kind) <= 0)
				{
					continue;
				}
				if (list == null)
				{
					list = Automation.Inputs(line);
				}
				Container source = null;
				foreach (Container item in list)
				{
					if ((Object)(object)item == (Object)null || Writeback.InUse(item))
					{
						continue;
					}
					foreach (ItemData allItem in item.GetInventory().GetAllItems())
					{
						if (Allows(allItem, kind))
						{
							source = item;
							break;
						}
					}
					if ((Object)(object)source != (Object)null)
					{
						break;
					}
				}
				if ((Object)(object)source == (Object)null)
				{
					Trace("refill " + kind.ToString() + ": room for " + Room(kind) + ", nothing usable in " + list.Count + " input chest(s)");
					continue;
				}
				_inputFirst = kind == Feed.Fuel;
				Automation.Busy = true;
				Handoff.With(new List<Container> { source }, delegate(List<Container> ours)
				{
					try
					{
						if (ours.Contains(source))
						{
							Supply(source, kind, line);
						}
						else
						{
							Trace("refill " + kind.ToString() + ": the input chest was not handed over");
						}
					}
					finally
					{
						Automation.Busy = false;
					}
				}, forLocalPlayer: false);
				return true;
			}
			return false;
		}

		private void Supply(Container chest, Feed kind, StorageTerminal line)
		{
			if ((Object)(object)this == (Object)null || !Valid || !_view.IsOwner() || (Object)(object)line == (Object)null)
			{
				return;
			}
			int num = Automation.Allowance(line);
			if (num <= 0 || !Writeback.Claim(chest))
			{
				return;
			}
			Inventory inventory = chest.GetInventory();
			int num2 = 0;
			foreach (ItemData item in new List<ItemData>(inventory.GetAllItems()))
			{
				while (num2 < num && Room(kind) > 0 && inventory.ContainsItem(item) && Allows(item, kind) && AddOne(item, kind))
				{
					inventory.RemoveOneItem(item);
					num2++;
					MovedIn = item.GetIcon();
					MovedInAt = Time.unscaledTime;
				}
				if (num2 >= num || Room(kind) <= 0)
				{
					break;
				}
			}
			Automation.Spend(line, num2);
			if (num2 > 0)
			{
				Writeback.Commit(chest);
			}
			Trace("refill " + kind.ToString() + ": added " + num2);
		}

		private ItemData CookedOutput(int slot)
		{
			if (!Valid || (Object)(object)_cooking == (Object)null)
			{
				return null;
			}
			ZDO zDO = _view.GetZDO();
			string text = zDO.GetString("slot" + slot, "");
			int num = zDO.GetInt("slotstatus" + slot, 0);
			if (string.IsNullOrEmpty(text) || num == 0)
			{
				return null;
			}
			ItemDrop val = CookedDrop(text);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			ItemData val2 = val.m_itemData.Clone();
			val2.m_dropPrefab = ((Component)val).gameObject;
			val2.m_stack = 1;
			val2.m_equipped = false;
			val2.m_worldLevel = (byte)Game.m_worldLevel;
			val2.m_cheated = zDO.GetBool(ZDOVars.s_cheatedQueued + slot, false);
			if (_cooking.m_spawnFullDurability)
			{
				val2.m_durability = val2.m_shared.m_maxDurability;
			}
			return val2;
		}

		private void ClearSlot(int slot)
		{
			if (SetCookingSlot == null)
			{
				return;
			}
			try
			{
				ParameterInfo[] parameters = SetCookingSlot.GetParameters();
				object[] array = new object[parameters.Length];
				for (int i = 0; i < parameters.Length; i++)
				{
					Type parameterType = parameters[i].ParameterType;
					array[i] = ((i == 0) ? ((object)slot) : ((parameterType == typeof(string)) ? "" : (parameterType.IsEnum ? Enum.ToObject(parameterType, 0) : (parameterType.IsValueType ? Activator.CreateInstance(parameterType) : null))));
				}
				SetCookingSlot.Invoke(_cooking, array);
				_view.InvokeRPC(ZNetView.Everybody, "RPC_SetSlotVisual", new object[2] { slot, "" });
			}
			catch (Exception ex)
			{
				NSIPlugin.Log.LogError((object)("automation: emptying a cooking slot failed: " + ex));
			}
		}

		internal static int Deliver(ItemData item, int amount, List<Container> ours, Vector3 origin)
		{
			//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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			Inventory val = new Inventory("NSI machine output", (Sprite)null, 1, 1);
			val.GetAllItems().Add(item);
			return Deposit.Push(val, item, amount, ours, origin, Deposit.Band.FreeSlot);
		}

		private bool TryCollect(StorageTerminal line)
		{
			//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_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			Vector3 origin = ((Component)this).transform.position;
			if ((Object)(object)_cooking != (Object)null)
			{
				if (_cannotEmpty)
				{
					return false;
				}
				for (int i = 0; i < _cooking.m_slots.Length; i++)
				{
					ItemData val = CookedOutput(i);
					if (val == null)
					{
						ZDO zDO = _view.GetZDO();
						string text = zDO.GetString("slot" + i, "");
						if (!string.IsNullOrEmpty(text))
						{
							Trace("collect: slot " + i + " holds '" + text + "' status " + zDO.GetInt("slotstatus" + i, 0) + ", not ready");
						}
						continue;
					}
					List<Container> list = Automation.Outputs(line);
					if (list.Count == 0)
					{
						Trace("collect: no output chest on this line");
						return false;
					}
					List<Container> list2 = Deposit.Rank(val, list, origin, Deposit.Band.FreeSlot);
					Trace("collect: slot " + i + " has " + val.m_shared.m_name + " ready, " + list2.Count + " of " + list.Count + " output chest(s) can take it");
					if (list2.Count == 0)
					{
						return false;
					}
					if (list2.Count > 3)
					{
						list2.RemoveRange(3, list2.Count - 3);
					}
					int at = i;
					Automation.Busy = true;
					Handoff.With(list2, delegate(List<Container> ours)
					{
						//IL_0018: Unknown result type (might be due to invalid IL or missing references)
						try
						{
							CollectSlot(at, ours, origin);
						}
						finally
						{
							Automation.Busy = false;
						}
					}, forLocalPlayer: false);
					return true;
				}
				return false;
			}
			List<MachineOutput> list3 = MachineOutput.For(Id);
			if (list3.Count == 0)
			{
				Trace("collect: no marked output on the ground");
				return false;
			}
			List<Container> list4 = null;
			foreach (MachineOutput output in list3)
			{
				if ((Object)(object)output == (Object)null || !output.Eligible(this))
				{
					Trace("collect: a marked drop is not ready or not ours");
					continue;
				}
				if (list4 == null)
				{
					list4 = Automation.Outputs(line);
					if (list4.Count == 0)
					{
						Trace("collect: no output chest on this line");
						return false;
					}
				}
				List<Container> list5 = Deposit.Rank(output.Item.m_itemData, list4, origin, Deposit.Band.FreeSlot);
				Trace("collect: " + output.Item.m_itemData.m_stack + " " + output.Item.m_itemData.m_shared.m_name + " on the ground, " + list5.Count + " of " + list4.Count + " output chest(s) can take it");
				if (list5.Count == 0)
				{
					continue;
				}
				if (list5.Count > 3)
				{
					list5.RemoveRange(3, list5.Count - 3);
				}
				Automation.Busy = true;
				Handoff.With(list5, delegate(List<Container> ours)
				{
					//IL_0080: Unknown result type (might be due to invalid IL or missing references)
					try
					{
						Sprite movedOut = (((Object)(object)output != (Object)null && (Object)(object)output.Item != (Object)null) ? output.Item.m_itemData.GetIcon() : null);
						bool flag = (Object)(object)this != (Object)null && (Object)(object)output != (Object)null && output.Eligible(this) && output.Commit(ours, origin);
						if (flag)
						{
							MovedOut = movedOut;
							MovedOutAt = Time.unscaledTime;
						}
						Trace("collect: " + ours.Count + " chest(s) handed over, " + (flag ? "stored" : "nothing stored"));
					}
					finally
					{
						Automation.Busy = false;
					}
				}, forLocalPlayer: false);
				return true;
			}
			return false;
		}

		private void CollectSlot(int slot, List<Container> ours, Vector3 origin)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)this == (Object)null || !Valid || !_view.IsOwner() || _cannotEmpty)
			{
				return;
			}
			ItemData val = CookedOutput(slot);
			if (val == null)
			{
				Trace("collect: slot " + slot + " changed before the chest arrived");
				return;
			}
			int num = Deliver(val, 1, ours, origin);
			Trace("collect: " + ours.Count + " chest(s) handed over, delivered " + num);
			if (num == 1)
			{
				ClearSlot(slot);
				if (CookedOutput(slot) != null)
				{
					_cannotEmpty = true;
					NSIPlugin.Log.LogError((object)("automation: a cooking slot on " + ((Object)this).name + " would not empty after its food was stored; this station is no longer collected from, so the food is not copied"));
				}
				else
				{
					MovedOut = val.GetIcon();
					MovedOutAt = Time.unscaledTime;
				}
			}
		}

		internal void Trace(string message)
		{
			if (NSIPlugin.DevTools && (!(message == _lastTrace) || !(Time.unscaledTime - _lastTraceAt < 5f)))
			{
				_lastTrace = message;
				_lastTraceAt = Time.unscaledTime;
				NSIPlugin.Log.LogInfo((object)("line: " + ((Object)this).name + " " + message));
			}
		}

		private void Awake()
		{
			_view = ((Component)this).GetComponent<ZNetView>();
			if ((Object)(object)_view == (Object)null || !_view.IsValid())
			{
				((Behaviour)this).enabled = false;
				return;
			}
			_smelter = ((Component)this).GetComponentInChildren<Smelter>(true);
			_fire = ((Component)this).GetComponentInChildren<Fireplace>(true);
			_cooking = ((Component)this).GetComponentInChildren<CookingStation>(true);
			_shield = ((Component)this).GetComponentInChildren<ShieldGenerator>(true);
			_view.Register<string, bool>("NSI_MachineFlag", (Action<long, string, bool>)RPC_Flag);
			Instances.Add(this);
		}

		private void OnDestroy()
		{
			Instances.Remove(this);
		}

		internal static Machine From(Component station)
		{
			if ((Object)(object)station == (Object)null)
			{
				return null;
			}
			ZNetView val = station.GetComponent<ZNetView>() ?? station.GetComponentInParent<ZNetView>();
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return ((Component)val).GetComponent<Machine>();
		}

		internal void EnsureId()
		{
			if (Valid && _view.IsOwner())
			{
				ZDO zDO = _view.GetZDO();
				if (zDO.GetString("nsi_id", "").Length == 0)
				{
					zDO.Set("nsi_id", Guid.NewGuid().ToString("N"));
				}
			}
		}

		private bool Burns(string itemName)
		{
			ItemDrop fuelItem = FuelItem;
			if ((Object)(object)fuelItem != (Object)null)
			{
				return fuelItem.m_itemData.m_shared.m_name == itemName;
			}
			if ((Object)(object)_shield != (Object)null)
			{
				foreach (ItemDrop fuelItem2 in _shield.m_fuelItems)
				{
					if ((Object)(object)fuelItem2 != (Object)null && fuelItem2.m_itemData.m_shared.m_name == itemName)
					{
						return true;
					}
				}
			}
			return false;
		}

		private ItemConversion SmelterRecipe(string input)
		{
			if ((Object)(object)_smelter == (Object)null || string.IsNullOrEmpty(input))
			{
				return null;
			}
			foreach (ItemConversion item in _smelter.m_conversion)
			{
				if ((Object)(object)item.m_from != (Object)null && ((Object)item.m_from).name == input)
				{
					return item;
				}
			}
			return null;
		}

		private ItemConversion CookingRecipe(string held, out bool cooked)
		{
			cooked = false;
			if ((Object)(object)_cooking == (Object)null || string.IsNullOrEmpty(held))
			{
				return null;
			}
			foreach (ItemConversion item in _cooking.m_conversion)
			{
				if ((Object)(object)item.m_from != (Object)null && ((Object)item.m_from).name == held)
				{
					return item;
				}
				if ((Object)(object)item.m_to != (Object)null && ((Object)item.m_to).name == held)
				{
					cooked = true;
					return item;
				}
			}
			return null;
		}

		private ItemDrop CookedDrop(string held)
		{
			if ((Object)(object)_cooking == (Object)null || string.IsNullOrEmpty(held))
			{
				return null;
			}
			if ((Object)(object)_cooking.m_overCookedItem != (Object)null && ((Object)_cooking.m_overCookedItem).name == held)
			{
				return _cooking.m_overCookedItem;
			}
			foreach (ItemConversion item in _cooking.m_conversion)
			{
				if ((Object)(object)item.m_to != (Object)null && ((Object)item.m_to).name == held)
				{
					return item.m_to;
				}
			}
			return null;
		}

		private static Sprite IconOf(ItemDrop drop)
		{
			if (!((Object)(object)drop != (Object)null) || drop.m_itemData == null)
			{
				return null;
			}
			return drop.m_itemData.GetIcon();
		}

		internal bool Flag(string key)
		{
			if (Valid)
			{
				return _view.GetZDO().GetBool(key, false);
			}
			return false;
		}

		internal void SetFlag(string key, bool on)
		{
			if (Valid)
			{
				_view.InvokeRPC("NSI_MachineFlag", new object[2] { key, on });
			}
		}

		private void RPC_Flag(long sender, string key, bool on)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (Valid && _view.IsOwner() && !string.IsNullOrEmpty(key) && key.Length <= 80)
			{
				string text = (key.StartsWith("nsi_fill_") ? "nsi_fill_" : (key.StartsWith("nsi_take_") ? "nsi_take_" : (key.StartsWith("nsi_on_") ? "nsi_on_" : null)));
				if (text != null && key.Length != text.Length)
				{
					_view.GetZDO().Set(key, on);
					ZDOMan.instance.ForceSendZDO(_view.GetZDO().m_uid);
					Trace("switch " + key + " = " + on);
				}
			}
		}

		internal StorageTerminal CollectingLine()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			StorageTerminal result = null;
			float num = float.MaxValue;
			foreach (StorageTerminal item in StorageTerminal.All)
			{
				if (OnAwakeLine(item) && Flag(Line.TakeKey(item)))
				{
					Vector3 val = ((Component)item).transform.position - ((Component)this).transform.position;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (!(sqrMagnitude >= num))
					{
						result = item;
						num = sqrMagnitude;
					}
				}
			}
			return result;
		}

		internal bool OnAwakeLine(StorageTerminal line)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)line == (Object)null || !line.IsAutomation || (int)line.Tier == 0)
			{
				return false;
			}
			float effectiveRadius = line.EffectiveRadius;
			Vector3 val = ((Component)line).transform.position - ((Component)this).transform.position;
			if (((Vector3)(ref val)).sqrMagnitude <= effectiveRadius * effectiveRadius)
			{
				return Flag(Line.OnKey(line));
			}
			return false;
		}

		internal static List<Machine> OnLine(StorageTerminal line)
		{
			List<Machine> list = InRange(line);
			if ((Object)(object)line == (Object)null)
			{
				return list;
			}
			string key = Line.OnKey(line);
			list.RemoveAll((Machine x) => !x.Flag(key));
			return list;
		}

		internal static List<Machine> InRange(StorageTerminal line)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			List<Machine> list = new List<Machine>();
			if ((Object)(object)line == (Object)null || (int)line.Tier == 0)
			{
				return list;
			}
			Vector3 at = ((Component)line).transform.position;
			float effectiveRadius = line.EffectiveRadius;
			foreach (Machine instance in Instances)
			{
				if (!((Object)(object)instance == (Object)null) && instance.Valid && (instance.CanRefill || instance.CanCollect))
				{
					Vector3 val = ((Component)instance).transform.position - at;
					if (((Vector3)(ref val)).sqrMagnitude <= effectiveRadius * effectiveRadius)
					{
						list.Add(instance);
					}
				}
			}
			list.Sort(delegate(Machine a, Machine b)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val2 = ((Component)a).transform.position - at;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				val2 = ((Component)b).transform.position - at;
				return sqrMagnitude.CompareTo(((Vector3)(ref val2)).sqrMagnitude);
			});
			return list;
		}

		internal List<KeyValuePair<Sprite, int>> Contents()
		{
			List<KeyValuePair<Sprite, int>> list = new List<KeyValuePair<Sprite, int>>();
			if (!Valid)
			{
				return list;
			}
			ZDO zDO = _view.GetZDO();
			if (UsesFuel && FuelNow >= 0.01f)
			{
				ItemDrop firstFuel = FirstFuel;
				if ((Object)(object)firstFuel != (Object)null)
				{
					list.Add(new KeyValuePair<Sprite, int>(IconOf(firstFuel), Mathf.CeilToInt(FuelNow)));
				}
			}
			List<string> names = new List<string>();
			List<int> counts = new List<int>();
			Action<string> action = delegate(string held)
			{
				if (!string.IsNullOrEmpty(held))
				{
					int num5 = names.IndexOf(held);
					if (num5 >= 0)
					{
						counts[num5]++;
					}
					else
					{
						names.Add(held);
						counts.Add(1);
					}
				}
			};
			if ((Object)(object)_smelter != (Object)null)
			{
				int num = zDO.GetInt(ZDOVars.s_queued, 0);
				for (int num2 = 0; num2 < num; num2++)
				{
					action(zDO.GetString("item" + num2, ""));
				}
			}
			if ((Object)(object)_cooking != (Object)null && _cooking.m_slots != null)
			{
				for (int num3 = 0; num3 < _cooking.m_slots.Length; num3++)
				{
					action(zDO.GetString("slot" + num3, ""));
				}
			}
			for (int num4 = 0; num4 < names.Count; num4++)
			{
				ItemDrop val = null;
				if ((Object)(object)_smelter != (Object)null)
				{
					ItemConversion val2 = SmelterRecipe(names[num4]);
					if (val2 != null)
					{
						val = val2.m_from;
					}
				}
				else if ((Object)(object)_cooking != (Object)null)
				{
					if ((Object)(object)_cooking.m_overCookedItem != (Object)null && ((Object)_cooking.m_overCookedItem).name == names[num4])
					{
						val = _cooking.m_overCookedItem;
					}
					else
					{
						bool cooked;
						ItemConversion val3 = CookingRecipe(names[num4], out cooked);
						if (val3 != null)
						{
							val = (cooked ? val3.m_to : val3.m_from);
						}
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					list.Add(new KeyValuePair<Sprite, int>(IconOf(val), counts[num4]));
				}
			}
			return list;
		}

		internal bool Making(out Sprite from, out Sprite to, out float progress)
		{
			from = null;
			to = null;
			progress = 0f;
			if (!Valid)
			{
				return false;
			}
			ZDO zDO = _view.GetZDO();
			if ((Object)(object)_smelter != (Object)null)
			{
				if (zDO.GetInt(ZDOVars.s_queued, 0) <= 0)
				{
					return false;
				}
				ItemConversion val = SmelterRecipe(zDO.GetString(ZDOVars.s_item0, ""));
				if (val != null)
				{
					from = IconOf(val.m_from);
					to = IconOf(val.m_to);
				}
				if (_smelter.m_secPerProduct > 0f)
				{
					progress = Mathf.Clamp01(zDO.GetFloat(ZDOVars.s_bakeTimer, 0f) / _smelter.m_secPerProduct);
				}
				if (!((Object)(object)from != (Object)null))
				{
					return (Object)(object)to != (Object)null;
				}
				return true;
			}
			if ((Object)(object)_cooking != (Object)null && _cooking.m_slots != null)
			{
				for (int i = 0; i < _cooking.m_slots.Length; i++)
				{
					bool cooked;
					ItemConversion val2 = CookingRecipe(zDO.GetString("slot" + i, ""), out cooked);
					if (val2 != null)
					{
						if (cooked)
						{
							to = IconOf(val2.m_to);
							progress = 1f;
							return true;
						}
						from = IconOf(val2.m_from);
						to = IconOf(val2.m_to);
						progress = ((val2.m_cookTime > 0f) ? Mathf.Clamp01(zDO.GetFloat("slot" + i, 0f) / val2.m_cookTime) : 0f);
						return true;
					}
				}
			}
			return false;
		}

		private bool AnyFor(List<Container> chests, Feed kind)
		{
			foreach (Container chest in chests)
			{
				Inventory val = (((Object)(object)chest != (Object)null) ? chest.GetInventory() : null);
				if (val == null)
				{
					continue;
				}
				foreach (ItemData allItem in val.GetAllItems())
				{
					if (Allows(allItem, kind))
					{
						return true;
					}
				}
			}
			return false;
		}

		internal string Starved(List<Container> inputs)
		{
			if (inputs == null || inputs.Count == 0)
			{
				return Txt.T("nsi_machine_no_input");
			}
			if (UsesFuel && FuelNow < 1f && Room(Feed.Fuel) > 0 && !AnyFor(inputs, Feed.Fuel))
			{
				return Txt.T("nsi_machine_no_fuel", FuelName);
			}
			if (HasQueue && Queued == 0 && !AnyFor(inputs, Feed.Input))
			{
				return Txt.T("nsi_machine_nothing");
			}
			return null;
		}

		internal string Blocked(List<Container> outputs)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			if (outputs == null || outputs.Count == 0)
			{
				return Txt.T("nsi_machine_no_output");
			}
			ItemData val = null;
			if ((Object)(object)_cooking != (Object)null && _cooking.m_slots != null)
			{
				for (int i = 0; i < _cooking.m_slots.Length; i++)
				{
					if (val != null)
					{
						break;
					}
					val = CookedOutput(i);
				}
			}
			else
			{
				foreach (MachineOutput item in MachineOutput.For(Id))
				{
					if ((Object)(object)item != (Object)null && (Object)(object)item.Item != (Object)null)
					{
						val = item.Item.m_itemData;
						break;
					}
				}
			}
			if (val == null)
			{
				return null;
			}
			if (Deposit.Rank(val, outputs, ((Component)this).transform.position, Deposit.Band.FreeSlot).Count != 0)
			{
				return null;
			}
			return Txt.T("nsi_machine_output_full");
		}
	}
	internal static class CoreVisual
	{
		private class Spin : MonoBehaviour
		{
			public CoreTier Tier;

			public float Glow;

			private Vector3 _rest;

			private bool _hasRest;

			private float _made;

			private CoreFloatStyle _style;

			private StorageTerminal _terminal;

			public void RestAt(Vector3 at)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				_rest = at;
				_hasRest = true;
			}

			private void Awake()
			{
				_made = Time.time;
				_terminal = ((Component)this).GetComponentInParent<StorageTerminal>();
			}

			private void Remake()
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: 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_0054: Unknown result type (might be due to invalid IL or missing references)
				Transform parent = ((Component)this).transform.parent;
				Vector3 localScale = ((Component)this).transform.localScale;
				Apply(parent, Tier);
				Transform val = (((Object)(object)parent != (Object)null) ? parent.Find("nsi_core_visual") : null);
				if (!((Object)(object)val == (Object)null))
				{
					val.localScale = localScale;
					((Component)val).GetComponent<Spin>().RestAt(_rest);
				}
			}

			private void Update()
			{
				//IL_000f: 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_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ee: 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_0132: 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)
				if (!_hasRest)
				{
					_rest = ((Component)this).transform.localPosition;
					_hasRest = true;
				}
				if (NSIPlugin.CoreGlow.Value != Glow && Time.time - _made >= 0.5f)
				{
					Remake();
					return;
				}
				CoreFloatStyle coreFloatStyle = (((Object)(object)_terminal != (Object)null) ? _terminal.Float : CoreFloatStyle.Tumble);
				if (coreFloatStyle != _style)
				{
					_style = coreFloatStyle;
					((Component)this).transform.localRotation = Quaternion.identity;
				}
				switch (coreFloatStyle)
				{
				case CoreFloatStyle.Tumble:
					((Component)this).transform.Rotate(Vector3.up, 25f * Time.deltaTime, (Space)0);
					((Component)this).transform.Rotate(Vector3.right, 17f * Time.deltaTime, (Space)0);
					((Component)this).transform.Rotate(Vector3.forward, 11f * Time.deltaTime, (Space)1);
					break;
				case CoreFloatStyle.Spin:
					((Component)this).transform.Rotate(Vector3.up, 25f * Time.deltaTime, (Space)0);
					break;
				}
				float num = ((coreFloatStyle == CoreFloatStyle.Still) ? 0f : (Mathf.Sin(Time.time * 1.4f) * 0.015f));
				((Component)this).transform.localPosition = _rest + Vector3.up * num;
			}
		}

		private const string HolderName = "nsi_core_visual";

		public static void Apply(Transform parent, CoreTier tier)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: 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_0235: 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_0255: 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_0267: 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_02df: Expected O, but got Unknown
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_030f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0403: Unknown result type (might be due to invalid IL or missing references)
			//IL_0404: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)parent == (Object)null)
			{
				return;
			}
			Transform val = parent.Find("nsi_core_visual");
			if ((Object)(object)val != (Object)null)
			{
				((Object)val).name = "nsi_core_visual_old";
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
			if ((int)tier == 0)
			{
				return;
			}
			string text = CoreInfo.ToPrefab(tier);
			if (string.IsNullOrEmpty(text) || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			GameObject val2 = Stand.Prefab(text);
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			bool activeSelf = val2.activeSelf;
			val2.SetActive(false);
			GameObject val3 = Object.Instantiate<GameObject>(val2);
			val2.SetActive(activeSelf);
			ZSyncTransform[] componentsInChildren = val3.GetComponentsInChildren<ZSyncTransform>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			ZNetView[] componentsInChildren2 = val3.GetComponentsInChildren<ZNetView>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			ItemDrop[] componentsInChildren3 = val3.GetComponentsInChildren<ItemDrop>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
			}
			Collider[] componentsInChildren4 = val3.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren4.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren4[i]);
			}
			Rigidbody[] componentsInChildren5 = val3.GetComponentsInChildren<Rigidbody>(true);
			for (int i = 0; i < componentsInChildren5.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren5[i]);
			}
			ParticleSystem[] componentsInChildren6 = val3.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val4 in componentsInChildren6)
			{
				if ((Object)(object)val4 == (Object)null)
				{
					continue;
				}
				if (((Object)((Component)val4).gameObject).name.StartsWith("nif_core_fx"))
				{
					MainModule main = val4.main;
					((MainModule)(ref main)).scalingMode = (ParticleSystemScalingMode)0;
					continue;
				}
				ParticleSystemRenderer component = ((Component)val4).GetComponent<ParticleSystemRenderer>();
				if ((Object)(object)component != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)component);
				}
				Object.DestroyImmediate((Object)(object)val4);
			}
			float value = NSIPlugin.CoreGlow.Value;
			Light[] componentsInChildren7 = val3.GetComponentsInChildren<Light>(true);
			foreach (Light obj in componentsInChildren7)
			{
				obj.intensity *= value;
				obj.range = Mathf.Min(obj.range * 1.25f, 7f);
				obj.shadows = (LightShadows)0;
			}
			val3.transform.SetParent(parent, false);
			val3.transform.localScale = Vector3.one;
			val3.transform.localRotation = Quaternion.identity;
			bool any = false;
			Bounds box = default(Bounds);
			Matrix4x4 worldToLocalMatrix = val3.transform.worldToLocalMatrix;
			MeshFilter[] componentsInChildren8 = val3.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val5 in componentsInChildren8)
			{
				if (!((Object)(object)val5.sharedMesh == (Object)null) && !((Object)(object)((Component)val5).GetComponent<MeshRenderer>() == (Object)null))
				{
					Stand.GrowByCorners(ref box, ref any, val5.sharedMesh.bounds, worldToLocalMatrix * ((Component)val5).transform.localToWorldMatrix);
				}
			}
			GameObject val6 = new GameObject("nsi_core_visual");
			val6.transform.SetParent(parent, false);
			val6.transform.localPosition = (Vector3)(Stand.Built ? Stand.CoreAt : new Vector3(0f, NSIPlugin.CoreHeight.Value, 0f));
			val6.transform.localRotation = Quaternion.identity;
			val6.transform.localScale = Scale(1f);
			((Object)val3).name = "core";
			val3.transform.SetParent(val6.transform, false);
			val3.transform.localPosition = (any ? (-((Bounds)(ref box)).center) : Vector3.zero);
			val3.SetActive(true);
			ManualLogSource log = NSIPlugin.Log;
			string[] obj2 = new string[7] { "core visual: ", text, " drawn middle ", null, null, null, null };
			Vector3 val7 = ((Bounds)(ref box)).center;
			obj2[3] = ((Vector3)(ref val7)).ToString("0.000");
			obj2[4] = " size ";
			val7 = ((Bounds)(ref box)).size;
			obj2[5] = ((Vector3)(ref val7)).ToString("0.000");
			obj2[6] = " from its origin";
			log.LogInfo((object)string.Concat(obj2));
			Spin spin = val6.AddComponent<Spin>();
			spin.Tier = tier;
			spin.Glow = value;
		}

		public static void Place(Transform parent, Vector3 at, float size)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			Transform val = (((Object)(object)parent != (Object)null) ? parent.Find("nsi_core_visual") : null);
			if (!((Object)(object)val == (Object)null))
			{
				Spin component = ((Component)val).GetComponent<Spin>();
				if ((Object)(object)component != (Object)null)
				{
					component.RestAt(at);
				}
				else
				{
					val.localPosition = at;
				}
				val.localScale = Scale(size);
			}
		}

		private static Vector3 Scale(float size)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			return Vector3.one * NSIPlugin.CoreScale.Value * (Stand.Built ? 0.55f : 1f) * size;
		}
	}
	public enum CoreFloatStyle
	{
		Tumble,
		Spin,
		Hover,
		Still
	}
	internal static class Network
	{
		private static readonly List<StorageTerminal> Terminals = new List<StorageTerminal>();

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

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

		private static Dictionary<string, int[]> _totals = new Dictionary<string, int[]>();

		private static float _freshUntil;

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

		public static void Register(StorageTerminal t)
		{
			if ((Object)(object)t != (Object)null && !Terminals.Contains(t))
			{
				Terminals.Add(t);
			}
		}

		public static void Unregister(StorageTerminal t)
		{
			Terminals.Remove(t);
		}

		public static void Invalidate()
		{
			_freshUntil = 0f;
		}

		private static void Refresh()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time < _freshUntil)
			{
				return;
			}
			_freshUntil = Time.time + 0.5f;
			_pool = new List<Container>();
			_ours = new List<Container>();
			_totals = new Dictionary<string, int[]>();
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			long playerID = localPlayer.GetPlayerID();
			HashSet<Container> hashSet = new HashSet<Container>();
			for (int num = Terminals.Count - 1; num >= 0; num--)
			{
				StorageTerminal storageTerminal = Terminals[num];
				if ((Object)(object)storageTerminal == (Object)null)
				{
					Terminals.RemoveAt(num);
				}
				else if ((int)storageTerminal.Tier != 0)
				{
					float effectiveRadius = storageTerminal.EffectiveRadius;
					if (!(Vector3.Distance(position, ((Component)storageTerminal).transform.position) > effectiveRadius))
					{
						foreach (Container item in Indexer.Containers(((Component)storageTerminal).transform.position, effectiveRadius, playerID))
						{
							if (hashSet.Add(item))
							{
								_pool.Add(item);
							}
						}
					}
				}
			}
			foreach (Container item2 in _pool)
			{
				if (!Writeback.Claim(item2))
				{
					continue;
				}
				Inventory inventory = item2.GetInventory();
				if (inventory == null)
				{
					continue;
				}
				_ours.Add(item2);
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem != null && allItem.m_shared != null)
					{
						if (!_totals.TryGetValue(allItem.m_shared.m_name, out var value))
						{
							value = (_totals[allItem.m_shared.m_name] = new int[2]);
						}
						value[0] += allItem.m_stack;
						if (allItem.m_worldLevel >= Game.m_worldLevel)
						{
							value[1] += allItem.m_stack;
						}
					}
				}
			}
		}

		public static void AskIfShort(string name, int needed)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || needed <= 0 || CraftContext.BagCount(((Humanoid)localPlayer).GetInventory(), name, -1, matchWorldLevel: true) >= needed || (NextAsk.TryGetValue(name, out var value) && Time.time < value))
			{
				return;
			}
			NextAsk[name] = Time.time + 3f;
			Refresh();
			List<Container> list = new List<Container>();
			foreach (Container item in _pool)
			{
				if (!((Object)(object)item == (Object)null) && !Writeback.Mine(item))
				{
					Inventory inventory = item.GetInventory();
					if (inventory != null && inventory.ContainsItemByName(name))
					{
						list.Add(item);
					}
				}
			}
			if (list.Count > 0)
			{
				Handoff.With(list, delegate
				{
					Invalidate();
				});
			}
		}

		public static int Count(string name, int quality, bool matchWorldLevel)
		{
			Refresh();
			if (quality < 0)
			{
				if (!_totals.TryGetValue(name, out var value))
				{
					return 0;
				}
				return value[matchWorldLevel ? 1u : 0u];
			}
			int num = 0;
			foreach (Container our in _ours)
			{
				Inventory val = (((Object)(object)our != (Object)null) ? our.GetInventory() : null);
				if (val == null)
				{
					continue;
				}
				foreach (ItemData allItem in val.GetAllItems())
				{
					if (Matches(allItem, name, quality, matchWorldLevel))
					{
						num += allItem.m_stack;
					}
				}
			}
			return num;
		}

		private static bool Matches(ItemData item, string name, int quality, bool worldLevel)
		{
			if (item == null || item.m_shared == null || item.m_shared.m_name != name)
			{
				return false;
			}
			if (quality >= 0 && item.m_quality != quality)
			{
				return false;
			}
			if (worldLevel)
			{
				return item.m_worldLevel >= Game.m_worldLevel;
			}
			return true;
		}

		public static int Take(string name, int amount, int quality, bool worldLevel)
		{
			Refresh();
			int num = 0;
			List<Container> list = new List<Container>(_ours);
			list.RemoveAll((Container c) => (Object)(object)c == (Object)null);
			Func<Container, int> priority = Priority.Remembered();
			list.Sort((Container a, Container b) => priority(a).CompareTo(priority(b)));
			foreach (Container item in list)
			{
				if (amount <= 0)
				{
					break;
				}
				if ((Object)(object)item == (Object)null || item.GetInventory() == null || !Writeback.Claim(item))
				{
					continue;
				}
				Inventory inventory = item.GetInventory();
				bool flag = false;
				foreach (ItemData item2 in new List<ItemData>(inventory.GetAllItems()))
				{
					if (amount <= 0)
					{
						break;
					}
					if (Matches(item2, name, quality, worldLevel))
					{
						int num2 = Mathf.Min(amount, item2.m_stack);
						item2.m_stack -= num2;
						if (item2.m_stack <= 0)
						{
							inventory.RemoveItem(item2);
						}
						amount -= num2;
						num += num2;
						flag = true;
					}
				}
				if (flag)
				{
					Writeback.Commit(item);
				}
			}
			Invalidate();
			return num;
		}
	}
	internal static class CraftContext
	{
		public static int Depth;

		public static int Raw;

		public static bool Active
		{
			get
			{
				if (Depth > 0 && Raw == 0)
				{
					return NSIPlugin.CraftFromNetwork.Value;
				}
				return false;
			}
		}

		public static bool IsLocalBag(Inventory inv)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && inv != null)
			{
				return inv == ((Humanoid)localPlayer).GetInventory();
			}
			return false;
		}

		public static int BagCount(Inventory inv, string name, int quality, bool matchWorldLevel)
		{
			Raw++;
			try
			{
				return inv.CountItems(name, quality, matchWorldLevel);
			}
			finally
			{
				Raw--;
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_CraftContext
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(Player), "HaveRequirements", new Type[2]
			{
				typeof(Piece),
				AccessTools.Inner(typeof(Player), "RequirementMode")
			}, (Type[])null);
			yield return AccessTools.Method