Decompiled source of Street Talk v1.0.2

Mods/WoodStudios.StreetTalk.dll

Decompiled 28 minutes ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using FybCommon;
using HarmonyLib;
using HoldTheFort;
using Il2CppFishNet;
using Il2CppFishNet.Connection;
using Il2CppFishNet.Object;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Audio;
using Il2CppScheduleOne.AvatarFramework;
using Il2CppScheduleOne.AvatarFramework.Animation;
using Il2CppScheduleOne.AvatarFramework.Emotions;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Dialogue;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Employees;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.Instancing;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.Money;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.NPCs.Relation;
using Il2CppScheduleOne.Networking;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Police;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Phone;
using Il2CppScheduleOne.VoiceOver;
using Il2CppScheduleOne.Weather;
using Il2CppSteamworks;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using S1API.Lifecycle;
using StreetTalkMod;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(TalkCore), "Street Talk", "1.0.2", "Wood Studios", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: MelonOptionalDependencies(new string[] { "HoldTheFort" })]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("WoodStudios.StreetTalk")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WoodStudios.StreetTalk")]
[assembly: AssemblyTitle("WoodStudios.StreetTalk")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 FybCommon
{
	internal static class FortifyApi
	{
		private sealed class SaveDoc
		{
			public int Version { get; set; } = 1;

			public Dictionary<string, string> Data { get; set; } = new Dictionary<string, string>();
		}

		private static Instance _log;

		private static string _folder;

		private static MelonPreferences_Entry<bool> _devKeys;

		private static KeyCode _use = (KeyCode)101;

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

		private static Harmony _harmony;

		private static bool _loaded;

		private static int _inGameFrame = -1;

		private static bool _inGame;

		private static string _iconItem;

		private static Sprite _icon;

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

		private static string _file;

		private static bool _readThisSession;

		private static bool _patched;

		private static bool _gameKeysOff;

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

		private static Shader _lit;

		private static readonly HashSet<IntPtr> Drawn = new HashSet<IntPtr>();

		private static float _nextDraw;

		private static readonly List<(string label, AudioClip clip)> NoSongs = new List<(string, AudioClip)>();

		public static bool Linked => FybLink.Present;

		public static string LinkedVersion
		{
			get
			{
				if (!FybLink.Present)
				{
					return null;
				}
				return Safe(FybLink.Version, "?");
			}
		}

		public static bool InGame
		{
			get
			{
				if (Time.frameCount == _inGameFrame)
				{
					return _inGame;
				}
				_inGameFrame = Time.frameCount;
				_inGame = false;
				if (_loaded)
				{
					try
					{
						LoadManager instance = Singleton<LoadManager>.Instance;
						_inGame = (Object)(object)instance != (Object)null && instance.IsGameLoaded;
					}
					catch
					{
					}
				}
				return _inGame;
			}
		}

		public static bool IsGuest
		{
			get
			{
				try
				{
					return InstanceFinder.IsClient && !InstanceFinder.IsServer;
				}
				catch
				{
					return false;
				}
			}
		}

		public static bool IsHost => !IsGuest;

		public static bool DevKeys
		{
			get
			{
				MelonPreferences_Entry<bool> devKeys = _devKeys;
				if (devKeys == null || !devKeys.Value)
				{
					if (FybLink.Present)
					{
						return Safe(FybLink.DevKeys, fallback: false);
					}
					return false;
				}
				return true;
			}
		}

		public static bool DataReady { get; private set; }

		public static KeyCode UseKey
		{
			get
			{
				//IL_0007: 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_002d: Unknown result type (might be due to invalid IL or missing references)
				if (!FybLink.Present)
				{
					return _use;
				}
				return Safe(FybLink.UseKey, _use);
			}
		}

		public static bool GameKeysOff => _gameKeysOff;

		public static IReadOnlyList<(string label, AudioClip clip)> YourSongs
		{
			get
			{
				if (FybLink.Present)
				{
					try
					{
						return FybLink.Songs() ?? NoSongs;
					}
					catch
					{
					}
				}
				return NoSongs;
			}
		}

		public static event Action BeforeSave;

		public static event Action AfterLoad;

		public static event Action Unloaded;

		public static void Init(MelonMod mod, string folder, string title, params string[] keepDrawnIdPrefixes)
		{
			//IL_0066: 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)
			_log = ((MelonBase)mod).LoggerInstance;
			_folder = folder;
			DrawnIds.AddRange(keepDrawnIdPrefixes);
			MelonPreferences_Category obj = MelonPreferences.CreateCategory(folder, title);
			_devKeys = obj.CreateEntry<bool>("DevKeys", false, "Developer keys", "Test keys (for the mod's author).", false, false, (ValueValidator)null, (string)null);
			_use = Keys.Parse(obj.CreateEntry<string>("UseKey", "E", "Use key", "Key for using things. With Fortify Your Base installed, its own use key is used instead.", false, false, (ValueValidator)null, (string)null).Value, (KeyCode)101);
			GameLifecycle.OnLoadComplete += OnLoaded;
			GameLifecycle.OnSaveStart += OnSaving;
			GameLifecycle.OnPreSceneChange += OnLeaving;
			_harmony = ((MelonBase)mod).HarmonyInstance;
		}

		public static void Log(string msg)
		{
			Instance log = _log;
			if (log != null)
			{
				log.Msg(msg);
			}
		}

		public static void Frame()
		{
			Ui.Capture();
			Shared.Update();
			DrawPass();
			RainCover.Update();
			TreeCut.Update();
		}

		public static void SetNotifyIcon(string itemId)
		{
			_iconItem = itemId;
			_icon = null;
		}

		public static void Notify(string title, string text)
		{
			try
			{
				NotificationsManager instance = Singleton<NotificationsManager>.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Log(title + ": " + text);
					return;
				}
				if ((Object)(object)_icon == (Object)null && !string.IsNullOrEmpty(_iconItem))
				{
					try
					{
						ItemDefinition item = Registry.GetItem<ItemDefinition>(_iconItem);
						_icon = ((item != null) ? ((BaseItemDefinition)item).Icon : null);
					}
					catch
					{
					}
				}
				instance.SendNotification(title, text, _icon, 6f, true);
			}
			catch (Exception ex)
			{
				Log($"{title}: {text} ({ex.Message})");
			}
		}

		public static void LogEvent(string kind, string place, int crew, string outcome)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.LogEvent(kind, place, crew, outcome);
				}
				catch
				{
				}
			}
		}

		public static string GetData(string key)
		{
			if (key == null || !_data.TryGetValue(key, out var value))
			{
				return null;
			}
			return value;
		}

		public static void SetData(string key, string value)
		{
			if (key != null)
			{
				_data[key] = value ?? "";
			}
		}

		private static void OnLoaded()
		{
			_loaded = true;
			if (!_patched)
			{
				_patched = true;
				try
				{
					Pins.Patch(_harmony);
				}
				catch (Exception ex)
				{
					Log("Pins: " + ex.Message);
				}
			}
			_data = new Dictionary<string, string>();
			_file = FileFor(SavePath());
			try
			{
				if (_file != null && File.Exists(_file))
				{
					SaveDoc saveDoc = JsonSerializer.Deserialize<SaveDoc>(File.ReadAllText(_file));
					if (saveDoc?.Data != null)
					{
						_data = saveDoc.Data;
					}
				}
				else if (_file != null)
				{
					Migrate();
				}
			}
			catch (Exception ex2)
			{
				Log("Couldn't read the save (" + ex2.Message + "); starting fresh.");
			}
			_readThisSession = true;
			DataReady = true;
			Log(FybLink.Present ? ("Linked up with Fortify Your Base " + LinkedVersion + ".") : "Running on its own.");
			try
			{
				FortifyApi.AfterLoad?.Invoke();
			}
			catch (Exception ex3)
			{
				Log("Load: " + ex3.Message);
			}
		}

		private static void Migrate()
		{
			try
			{
				string path = Path.Combine(MelonEnvironment.UserDataDirectory, "HoldTheFort", "Saves", Path.GetFileName(_file));
				if (!File.Exists(path))
				{
					return;
				}
				using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(path));
				if (!jsonDocument.RootElement.TryGetProperty("Addons", out var value) || value.ValueKind != JsonValueKind.Object)
				{
					return;
				}
				int num = 0;
				foreach (JsonProperty item in value.EnumerateObject())
				{
					if (item.Value.ValueKind == JsonValueKind.String)
					{
						_data[item.Name] = item.Value.GetString();
						num++;
					}
				}
				if (num > 0)
				{
					Log("Picked up this save's progress from Fortify Your Base's save file.");
				}
			}
			catch (Exception ex)
			{
				Log("Couldn't read Fortify Your Base's save file (" + ex.Message + ").");
			}
		}

		private static void OnSaving()
		{
			if (!DataReady || !_readThisSession || IsGuest)
			{
				return;
			}
			try
			{
				FortifyApi.BeforeSave?.Invoke();
			}
			catch (Exception ex)
			{
				Log("Save: " + ex.Message);
			}
			string text = _file ?? FileFor(SavePath());
			if (text == null)
			{
				return;
			}
			try
			{
				string text2 = text + ".tmp";
				File.WriteAllText(text2, JsonSerializer.Serialize(new SaveDoc
				{
					Data = _data
				}, new JsonSerializerOptions
				{
					WriteIndented = true
				}));
				if (File.Exists(text))
				{
					File.Delete(text);
				}
				File.Move(text2, text);
			}
			catch (Exception ex2)
			{
				Log("Couldn't save: " + ex2.Message);
			}
		}

		private static void OnLeaving()
		{
			if (DataReady)
			{
				try
				{
					FortifyApi.Unloaded?.Invoke();
				}
				catch
				{
				}
			}
			DataReady = false;
			_loaded = false;
			_readThisSession = false;
			_file = null;
			_data = new Dictionary<string, string>();
			Shared.Reset();
			Pins.Reset();
			Drawn.Clear();
			RainCover.Reset();
			TreeCut.Reset();
		}

		private static string SavePath()
		{
			LoadManager instance = Singleton<LoadManager>.Instance;
			string text = null;
			try
			{
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					SaveInfo activeSaveInfo = instance.ActiveSaveInfo;
					obj = ((activeSaveInfo != null) ? activeSaveInfo.SavePath : null);
				}
				text = (string)obj;
			}
			catch
			{
			}
			if (string.IsNullOrEmpty(text))
			{
				try
				{
					text = ((instance != null) ? instance.LoadedGameFolderPath : null);
				}
				catch
				{
				}
			}
			return text;
		}

		private static string FileFor(string savePath)
		{
			if (string.IsNullOrWhiteSpace(savePath))
			{
				return null;
			}
			string text = savePath.TrimEnd('/', '\\');
			StringBuilder stringBuilder = new StringBuilder();
			string fileName = Path.GetFileName(text);
			foreach (char c in fileName)
			{
				stringBuilder.Append((char.IsLetterOrDigit(c) || c == '_' || c == '-') ? c : '_');
			}
			uint num = 2166136261u;
			fileName = text.ToLowerInvariant().Replace('\\', '/');
			foreach (char c2 in fileName)
			{
				num ^= c2;
				num *= 16777619;
			}
			string text2 = Path.Combine(MelonEnvironment.UserDataDirectory, _folder ?? "FortifyAddon", "Saves");
			Directory.CreateDirectory(text2);
			return Path.Combine(text2, $"{stringBuilder}_{num:x8}.json");
		}

		public static bool KeyDown(KeyCode k)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Keys.Down(k);
		}

		public static bool KeyHeld(KeyCode k)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Keys.Held(k);
		}

		public static void Typing(bool on)
		{
			Keys.Suppressed = on;
			try
			{
				GameInput.IsTyping = on;
			}
			catch
			{
			}
			if (FybLink.Present)
			{
				try
				{
					FybLink.Suppress(on);
				}
				catch
				{
				}
			}
		}

		public static void GameKeys(bool on)
		{
			try
			{
				GameInput instance = Singleton<GameInput>.Instance;
				PlayerInput val = (((Object)(object)instance != (Object)null) ? instance.PlayerInput : null);
				if ((Object)(object)val == (Object)null)
				{
					if (on)
					{
						_gameKeysOff = false;
					}
				}
				else if (!on)
				{
					if (!_gameKeysOff)
					{
						val.DeactivateInput();
						_gameKeysOff = true;
					}
				}
				else if (_gameKeysOff)
				{
					val.ActivateInput();
					_gameKeysOff = false;
				}
			}
			catch
			{
				if (on)
				{
					_gameKeysOff = false;
				}
			}
		}

		private static Shader LitShader()
		{
			if ((Object)(object)_lit != (Object)null)
			{
				return _lit;
			}
			_lit = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Universal Render Pipeline/Simple Lit");
			if ((Object)(object)_lit == (Object)null)
			{
				foreach (Material item in Resources.FindObjectsOfTypeAll<Material>())
				{
					if ((Object)(object)item != (Object)null && (Object)(object)item.shader != (Object)null && ((Object)item.shader).name.Contains("Lit"))
					{
						_lit = item.shader;
						break;
					}
				}
			}
			if ((Object)(object)_lit == (Object)null)
			{
				_lit = Shader.Find("Standard");
			}
			return _lit;
		}

		private static Material MakeMat(string key, Color color, float metallic, float smoothness, Color? emission)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			if (Mats.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			Material val = new Material(LitShader())
			{
				name = "FYBA_" + key
			};
			val.color = color;
			if (val.HasProperty("_BaseColor"))
			{
				val.SetColor("_BaseColor", color);
			}
			if (val.HasProperty("_Metallic"))
			{
				val.SetFloat("_Metallic", metallic);
			}
			if (val.HasProperty("_Smoothness"))
			{
				val.SetFloat("_Smoothness", smoothness);
			}
			if (val.HasProperty("_Glossiness"))
			{
				val.SetFloat("_Glossiness", smoothness);
			}
			if (emission.HasValue)
			{
				val.EnableKeyword("_EMISSION");
				if (val.HasProperty("_EmissionColor"))
				{
					val.SetColor("_EmissionColor", emission.Value);
				}
				val.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)1;
			}
			((Object)val).hideFlags = (HideFlags)32;
			Mats[key] = val;
			return val;
		}

		public static Material Mat(string key, Color c, float metallic = 0f, float smoothness = 0.3f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return MakeMat(key, c, metallic, smoothness, null);
		}

		public static Material Emissive(string key, Color c, Color emission, float smoothness = 0.4f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return MakeMat(key, c, 0f, smoothness, emission);
		}

		public static Material Glow(string key, Color c)
		{
			//IL_0001: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			return MakeMat(key, c, 0f, 0.5f, c * 2.5f);
		}

		public static GameObject Part(Transform parent, PrimitiveType type, Vector3 pos, Vector3 scale, Material m, Vector3? euler = null, bool collider = false, string name = null)
		{
			//IL_0000: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.CreatePrimitive(type);
			if (!collider)
			{
				Object.DestroyImmediate((Object)(object)val.GetComponent<Collider>());
			}
			val.transform.SetParent(parent, false);
			val.transform.localPosition = pos;
			val.transform.localRotation = Quaternion.Euler((Vector3)(((??)euler) ?? Vector3.zero));
			val.transform.localScale = scale;
			((Renderer)val.GetComponent<MeshRenderer>()).sharedMaterial = m;
			if (name != null)
			{
				((Object)val).name = name;
			}
			return val;
		}

		public static void UiFill(Rect r, Color c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Ui.Fill(r, c);
		}

		public static void UiFrame(Rect r, Color c, float t = 2f)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Ui.Frame(r, c, t);
		}

		public static void UiText(Rect r, string s, int size, Color c, TextAnchor a = (TextAnchor)4, bool bold = true)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			Ui.Text(r, s, size, c, a, bold);
		}

		public static bool UiButton(Rect r, string label, bool enabled = true, bool selected = false, int size = 17)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Ui.Button(r, label, enabled, selected, size);
		}

		public static void OpenMenu(string name)
		{
			try
			{
				PlayerCamera instance = PlayerSingleton<PlayerCamera>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.AddActiveUIElement(name);
					instance.SetCanLook(false);
				}
			}
			catch
			{
			}
			try
			{
				PlayerMovement instance2 = PlayerSingleton<PlayerMovement>.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					instance2.CanMove = false;
				}
			}
			catch
			{
			}
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
		}

		public static void CloseMenu(string name)
		{
			try
			{
				PlayerCamera instance = PlayerSingleton<PlayerCamera>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.RemoveActiveUIElement(name);
					instance.SetCanLook(true);
				}
			}
			catch
			{
			}
			try
			{
				PlayerMovement instance2 = PlayerSingleton<PlayerMovement>.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					instance2.CanMove = true;
				}
			}
			catch
			{
			}
			Cursor.lockState = (CursorLockMode)1;
			Cursor.visible = false;
		}

		public static void Hint(string text)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(text) || (Cursor.visible && (int)Cursor.lockState != 1))
			{
				return;
			}
			float num = Screen.width;
			float num2 = Screen.height;
			float num3 = Mathf.Clamp(num2 / 1080f, 0.85f, 2f);
			int num4 = Mathf.RoundToInt(18f * num3);
			float num5 = Mathf.Min(num - 40f, 920f * num3);
			float num6 = 14f * num3;
			int num7 = Mathf.Clamp(Mathf.CeilToInt((float)(text.Length * num4) * 0.56f / (num5 - 2f * num6)), 1, 4);
			for (int i = 0; i < text.Length; i++)
			{
				if (text[i] == '\n')
				{
					num7 = Mathf.Min(4, num7 + 1);
				}
			}
			float num8 = (float)(num7 * num4) * 1.4f + 12f * num3;
			float num9 = HintStack(num8 + 6f * num3);
			Rect r = default(Rect);
			((Rect)(ref r))..ctor((num - num5) * 0.5f, num2 * 0.72f - num9, num5, num8);
			Ui.Fill(r, new Color(0f, 0f, 0f, 0.66f));
			Ui.Text(new Rect(((Rect)(ref r)).x + num6, ((Rect)(ref r)).y, ((Rect)(ref r)).width - 2f * num6, ((Rect)(ref r)).height), text, num4, Color.white, (TextAnchor)4);
		}

		private static float HintStack(float take)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			float num = 0f;
			try
			{
				Event current = Event.current;
				string text = Time.frameCount + ":" + ((current == null) ? (-1) : ((int)current.type));
				AppDomain currentDomain = AppDomain.CurrentDomain;
				if (currentDomain.GetData("WoodStudios.HintPass") as string == text && currentDomain.GetData("WoodStudios.HintUsed") is float num2)
				{
					num = num2;
				}
				currentDomain.SetData("WoodStudios.HintPass", text);
				currentDomain.SetData("WoodStudios.HintUsed", num + take);
			}
			catch
			{
			}
			return num;
		}

		public static void ShareState(string key, string value)
		{
			Shared.Set(key, value);
		}

		public static string SharedState(string key)
		{
			return Shared.Get(key);
		}

		public static void SendRequest(string key, string value)
		{
			Shared.Request(key, value);
		}

		public static List<string> TakeRequests(string key)
		{
			Shared.Listen(key);
			return Shared.Take(key);
		}

		public static void Pin(GameObject npc, bool on)
		{
			try
			{
				NPC val = (((Object)(object)npc != (Object)null) ? npc.GetComponent<NPC>() : null);
				if ((Object)(object)val != (Object)null)
				{
					Pins.Set(val, on);
				}
			}
			catch
			{
			}
		}

		public static void KeepDrawn(NPC n)
		{
			if ((Object)(object)n == (Object)null)
			{
				return;
			}
			try
			{
				Avatar avatar = n.Avatar;
				if (!((Object)(object)avatar == (Object)null))
				{
					if (avatar._cullingRange < 130f)
					{
						avatar._cullingRange = 130f;
					}
					if (avatar._visibilityRangeSqr < 16900f)
					{
						avatar._visibilityRangeSqr = 16900f;
					}
				}
			}
			catch
			{
			}
		}

		private static void DrawPass()
		{
			if (DrawnIds.Count == 0 || Time.unscaledTime < _nextDraw || !_loaded)
			{
				return;
			}
			_nextDraw = Time.unscaledTime + 2f;
			try
			{
				List<NPC> nPCRegistry = NPCManager.NPCRegistry;
				for (int i = 0; nPCRegistry != null && i < nPCRegistry.Count; i++)
				{
					NPC val = nPCRegistry[i];
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					bool flag = Drawn.Contains(((Il2CppObjectBase)val).Pointer);
					if (!flag)
					{
						string text = val.ID ?? "";
						foreach (string drawnId in DrawnIds)
						{
							if (text.StartsWith(drawnId, StringComparison.Ordinal))
							{
								flag = true;
								break;
							}
						}
						if (!flag)
						{
							continue;
						}
						Drawn.Add(((Il2CppObjectBase)val).Pointer);
					}
					KeepDrawn(val);
				}
			}
			catch
			{
			}
		}

		public static void ReserveArea(string key, Vector3 centre, float radius, float lot = 0f)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (FybLink.Present)
			{
				try
				{
					FybLink.ReserveArea(key, centre, radius, lot);
				}
				catch
				{
				}
			}
		}

		public static void AddBuildArea(string key, Func<Vector3, bool> inside, Transform gridFrame = null)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.AddBuildArea(key, inside, gridFrame);
				}
				catch
				{
				}
			}
		}

		public static void RemoveBuildArea(string key)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.RemoveBuildArea(key);
				}
				catch
				{
				}
			}
		}

		public static void AddShelter(string key, Func<Vector3, bool> inside)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.AddShelter(key, inside);
					return;
				}
				catch
				{
					return;
				}
			}
			RainCover.Add(key, inside);
		}

		public static void RemoveShelter(string key)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.RemoveShelter(key);
					return;
				}
				catch
				{
					return;
				}
			}
			RainCover.Remove(key);
		}

		public static void AddTreeClearing(string key, Vector3 centre, float radius)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (FybLink.Present)
			{
				try
				{
					FybLink.AddTreeClearing(key, centre, radius);
					return;
				}
				catch
				{
					return;
				}
			}
			TreeCut.Add(key, centre, radius);
		}

		public static void RemoveTreeClearing(string key)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.RemoveTreeClearing(key);
					return;
				}
				catch
				{
					return;
				}
			}
			TreeCut.Remove(key);
		}

		public static bool ParkFoodTruck(string key, Vector3 pos, float yaw)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (FybLink.Present)
			{
				try
				{
					return FybLink.ParkFoodTruck(key, pos, yaw);
				}
				catch
				{
				}
			}
			return false;
		}

		public static void ReleaseFoodTruck(string key)
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.ReleaseFoodTruck(key);
				}
				catch
				{
				}
			}
		}

		public static bool FoodTruckParkedBy(string key)
		{
			if (FybLink.Present)
			{
				try
				{
					return FybLink.FoodTruckParkedBy(key);
				}
				catch
				{
				}
			}
			return false;
		}

		public static void DevView(Vector3 from, Vector3 at)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (FybLink.Present)
			{
				try
				{
					FybLink.DevView(from, at);
				}
				catch
				{
				}
			}
		}

		public static void DevViewEnd()
		{
			if (FybLink.Present)
			{
				try
				{
					FybLink.DevViewEnd();
				}
				catch
				{
				}
			}
		}

		private static T Safe<T>(Func<T> f, T fallback)
		{
			try
			{
				return f();
			}
			catch
			{
				return fallback;
			}
		}
	}
	internal static class FybLink
	{
		private static int _present = -1;

		public static bool Present
		{
			get
			{
				if (_present >= 0)
				{
					return _present == 1;
				}
				_present = 0;
				try
				{
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					for (int i = 0; i < assemblies.Length; i++)
					{
						if (assemblies[i].GetName().Name == "HoldTheFort")
						{
							_present = ((Level() >= 3) ? 1 : 0);
							break;
						}
					}
				}
				catch
				{
					_present = 0;
				}
				return _present == 1;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static int Level()
		{
			try
			{
				return LevelInner();
			}
			catch
			{
				return 0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static int LevelInner()
		{
			return FortifyApi.Level;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static string Version()
		{
			return FortifyApi.Version;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool DevKeys()
		{
			return FortifyApi.DevKeys;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static KeyCode UseKey()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return FortifyApi.UseKey;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void LogEvent(string kind, string place, int crew, string outcome)
		{
			FortifyApi.LogEvent(kind, place, crew, outcome);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static IReadOnlyList<(string label, AudioClip clip)> Songs()
		{
			return FortifyApi.YourSongs;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void ReserveArea(string key, Vector3 c, float r, float lot)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			FortifyApi.ReserveArea(key, c, r, lot);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void AddBuildArea(string key, Func<Vector3, bool> inside, Transform frame)
		{
			FortifyApi.AddBuildArea(key, inside, frame);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void RemoveBuildArea(string key)
		{
			FortifyApi.RemoveBuildArea(key);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void AddShelter(string key, Func<Vector3, bool> inside)
		{
			FortifyApi.AddShelter(key, inside);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void RemoveShelter(string key)
		{
			FortifyApi.RemoveShelter(key);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void AddTreeClearing(string key, Vector3 c, float r)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			FortifyApi.AddTreeClearing(key, c, r);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void RemoveTreeClearing(string key)
		{
			FortifyApi.RemoveTreeClearing(key);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool ParkFoodTruck(string key, Vector3 p, float yaw)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return FortifyApi.ParkFoodTruck(key, p, yaw);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void ReleaseFoodTruck(string key)
		{
			FortifyApi.ReleaseFoodTruck(key);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool FoodTruckParkedBy(string key)
		{
			return FortifyApi.FoodTruckParkedBy(key);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void DevView(Vector3 from, Vector3 at)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			FortifyApi.DevView(from, at);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void DevViewEnd()
		{
			FortifyApi.DevViewEnd();
		}

		public static void Suppress(bool on)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!(assembly.GetName().Name != "HoldTheFort"))
				{
					(assembly.GetType("HoldTheFort.InputUtil")?.GetField("Suppressed", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))?.SetValue(null, on);
					break;
				}
			}
		}
	}
	internal static class Keys
	{
		private static bool _legacyBroken;

		public static bool Suppressed;

		private const string TextBoxKey = "WoodStudios.TextBoxFrame";

		public static KeyCode Parse(string name, KeyCode fallback)
		{
			//IL_0018: 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)
			if (string.IsNullOrWhiteSpace(name) || !Enum.TryParse<KeyCode>(name.Trim(), ignoreCase: true, out KeyCode result))
			{
				return fallback;
			}
			return result;
		}

		public static bool Down(KeyCode key)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!Suppressed && !TextBoxElsewhere())
			{
				return RawDown(key);
			}
			return false;
		}

		public static bool Held(KeyCode key)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!Suppressed && !TextBoxElsewhere())
			{
				return RawHeld(key);
			}
			return false;
		}

		public static void MarkTextBox()
		{
			try
			{
				AppDomain.CurrentDomain.SetData("WoodStudios.TextBoxFrame", Time.frameCount);
			}
			catch
			{
			}
		}

		private static bool TextBoxElsewhere()
		{
			try
			{
				return AppDomain.CurrentDomain.GetData("WoodStudios.TextBoxFrame") is int num && Time.frameCount - num <= 2;
			}
			catch
			{
				return false;
			}
		}

		public static bool RawDown(KeyCode key)
		{
			//IL_0019: 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 (!_legacyBroken)
			{
				try
				{
					return Input.GetKeyDown(key);
				}
				catch
				{
					_legacyBroken = true;
				}
			}
			KeyControl val = Control(key);
			if (val != null)
			{
				return ((ButtonControl)val).wasPressedThisFrame;
			}
			return false;
		}

		public static bool RawHeld(KeyCode key)
		{
			//IL_0019: 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 (!_legacyBroken)
			{
				try
				{
					return Input.GetKey(key);
				}
				catch
				{
					_legacyBroken = true;
				}
			}
			KeyControl val = Control(key);
			if (val != null)
			{
				return ((ButtonControl)val).isPressed;
			}
			return false;
		}

		public static bool MouseDown(int button)
		{
			if (!_legacyBroken)
			{
				try
				{
					return Input.GetMouseButtonDown(button);
				}
				catch
				{
					_legacyBroken = true;
				}
			}
			try
			{
				Mouse current = Mouse.current;
				return current != null && ((button == 0) ? current.leftButton.wasPressedThisFrame : current.rightButton.wasPressedThisFrame);
			}
			catch
			{
				return false;
			}
		}

		public static string Typed(bool shift)
		{
			if (!_legacyBroken)
			{
				try
				{
					return Input.inputString ?? "";
				}
				catch
				{
					_legacyBroken = true;
				}
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (char c = 'a'; c <= 'z'; c = (char)(c + 1))
			{
				if (RawDown((KeyCode)(97 + (c - 97))))
				{
					stringBuilder.Append(shift ? char.ToUpperInvariant(c) : c);
				}
			}
			for (int i = 0; i <= 9; i++)
			{
				if (RawDown((KeyCode)(48 + i)))
				{
					stringBuilder.Append(shift ? ")!@#$%^&*("[i] : ((char)(48 + i)));
				}
			}
			if (RawDown((KeyCode)32))
			{
				stringBuilder.Append(' ');
			}
			if (RawDown((KeyCode)45))
			{
				stringBuilder.Append('-');
			}
			if (RawDown((KeyCode)39))
			{
				stringBuilder.Append('\'');
			}
			if (RawDown((KeyCode)46))
			{
				stringBuilder.Append('.');
			}
			if (RawDown((KeyCode)8))
			{
				stringBuilder.Append('\b');
			}
			return stringBuilder.ToString();
		}

		private unsafe static KeyControl Control(KeyCode key)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Keyboard current = Keyboard.current;
				if (current == null)
				{
					return null;
				}
				string text = ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
				if (text.StartsWith("Alpha"))
				{
					text = "Digit" + text.Substring(5);
				}
				else if (text == "Return")
				{
					text = "Enter";
				}
				else if (text == "KeypadEnter")
				{
					text = "NumpadEnter";
				}
				else if (text.StartsWith("Keypad"))
				{
					text = "Numpad" + text.Substring(6);
				}
				Key result;
				return Enum.TryParse<Key>(text, ignoreCase: true, out result) ? current[result] : null;
			}
			catch
			{
				return null;
			}
		}
	}
	internal static class Ui
	{
		private static Vector2 _mouse;

		private static bool _click;

		private static int _clickFrame;

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

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

		public static void Capture()
		{
			//IL_0002: 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_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_0039: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = default(Vector2);
			bool flag = false;
			try
			{
				val = Vector2.op_Implicit(Input.mousePosition);
				flag = true;
			}
			catch
			{
			}
			if (!flag)
			{
				try
				{
					Mouse current = Mouse.current;
					if (current != null)
					{
						val = ((InputControl<Vector2>)(object)((Pointer)current).position).ReadValue();
					}
				}
				catch
				{
				}
			}
			_mouse = new Vector2(val.x, (float)Screen.height - val.y);
			if (Keys.MouseDown(0))
			{
				_click = true;
				_clickFrame = Time.frameCount;
			}
			else if (_click && Time.frameCount - _clickFrame > 1)
			{
				_click = false;
			}
		}

		public static bool Hover(Rect r)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return ((Rect)(ref r)).Contains(_mouse);
		}

		public static bool Click(Rect r)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (!_click || !((Rect)(ref r)).Contains(_mouse))
			{
				return false;
			}
			_click = false;
			return true;
		}

		private static GUIStyle SolidStyle(Color c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Expected O, but got Unknown
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Expected O, but got Unknown
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Expected O, but got Unknown
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Expected O, but got Unknown
			int num = (int)(Math.Clamp(c.r, 0f, 1f) * 255f + 0.5f);
			int num2 = (int)(Math.Clamp(c.g, 0f, 1f) * 255f + 0.5f);
			int num3 = (int)(Math.Clamp(c.b, 0f, 1f) * 255f + 0.5f);
			int num4 = (int)(Math.Clamp(c.a, 0f, 1f) * 255f + 0.5f);
			int key = (num << 24) | (num2 << 16) | (num3 << 8) | num4;
			if (Solid.TryGetValue(key, out var value) && value != null && (Object)(object)value.normal.background != (Object)null)
			{
				return value;
			}
			if (Solid.Count > 600)
			{
				foreach (GUIStyle value2 in Solid.Values)
				{
					if (value2 != null && (Object)(object)value2.normal.background != (Object)null)
					{
						Object.Destroy((Object)(object)value2.normal.background);
					}
				}
				Solid.Clear();
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			Color32 val2 = default(Color32);
			((Color32)(ref val2))..ctor((byte)num, (byte)num2, (byte)num3, (byte)num4);
			val.SetPixels32(new Il2CppStructArray<Color32>((Color32[])(object)new Color32[4] { val2, val2, val2, val2 }));
			val.Apply();
			((Object)val).hideFlags = (HideFlags)32;
			value = new GUIStyle();
			value.normal.background = val;
			value.border = new RectOffset(0, 0, 0, 0);
			value.padding = new RectOffset(0, 0, 0, 0);
			value.margin = new RectOffset(0, 0, 0, 0);
			Solid[key] = value;
			return value;
		}

		public static void Fill(Rect r, Color c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: 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)
			if (!(c.a <= 0.003f))
			{
				GUI.Label(r, "", SolidStyle(c));
			}
		}

		public static void Frame(Rect r, Color c, float t = 2f)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			Fill(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, ((Rect)(ref r)).width, t), c);
			Fill(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).yMax - t, ((Rect)(ref r)).width, t), c);
			Fill(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, t, ((Rect)(ref r)).height), c);
			Fill(new Rect(((Rect)(ref r)).xMax - t, ((Rect)(ref r)).y, t, ((Rect)(ref r)).height), c);
		}

		public static void Text(Rect r, string s, int size, Color c, TextAnchor a = (TextAnchor)4, bool bold = true, bool wrap = true)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected I4, but got Unknown
			//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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			int key = size * 64 + a * 4 + (bold ? 2 : 0) + wrap;
			if (!Styles.TryGetValue(key, out var value) || value == null)
			{
				value = new GUIStyle(GUI.skin.label)
				{
					fontSize = size,
					alignment = a,
					fontStyle = (FontStyle)(bold ? 1 : 0),
					wordWrap = wrap
				};
				Styles[key] = value;
			}
			value.normal.textColor = c;
			GUI.Label(r, s ?? "", value);
		}

		public static bool Button(Rect r, string label, bool enabled = true, bool selected = false, int size = 17)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_002a: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			bool flag = enabled && Hover(r);
			Color c = ((!enabled) ? new Color(0.18f, 0.18f, 0.2f, 0.9f) : (selected ? new Color(0.85f, 0.65f, 0.2f, 0.97f) : (flag ? new Color(0.36f, 0.32f, 0.46f, 0.97f) : new Color(0.24f, 0.22f, 0.3f, 0.95f))));
			Fill(r, c);
			Frame(r, enabled ? new Color(1f, 1f, 1f, flag ? 0.55f : 0.25f) : new Color(1f, 1f, 1f, 0.08f));
			Text(r, label, size, (Color)((!enabled) ? new Color(0.5f, 0.5f, 0.55f) : (selected ? Color.black : Color.white)), (TextAnchor)4);
			if (enabled)
			{
				return Click(r);
			}
			return false;
		}
	}
	internal static class Shared
	{
		private const string Prefix = "fyb_";

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

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

		private static readonly Dictionary<string, (string value, float at)> Read = new Dictionary<string, (string, float)>();

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

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

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

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

		private static float _nextFlush;

		private static bool InLobby(out CSteamID lobby)
		{
			//IL_0001: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			lobby = default(CSteamID);
			try
			{
				Lobby instance = Singleton<Lobby>.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsInLobby || instance.LobbyID == 0L)
				{
					return false;
				}
				lobby = new CSteamID
				{
					m_SteamID = instance.LobbyID
				};
				return instance.PlayerCount > 1 || FortifyApi.IsGuest;
			}
			catch
			{
				return false;
			}
		}

		public static void Set(string key, string value)
		{
			if (key != null)
			{
				Local[key] = value ?? "";
			}
		}

		public static string Get(string key)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			if (key == null)
			{
				return null;
			}
			if (!FortifyApi.IsGuest)
			{
				if (!Local.TryGetValue(key, out var value))
				{
					return null;
				}
				return value;
			}
			if (Read.TryGetValue(key, out (string, float) value2) && Time.unscaledTime - value2.Item2 < 0.5f)
			{
				return value2.Item1;
			}
			string text = null;
			try
			{
				if (InLobby(out var lobby))
				{
					text = SteamMatchmaking.GetLobbyData(lobby, "fyb_" + key);
				}
			}
			catch
			{
			}
			if (string.IsNullOrEmpty(text))
			{
				text = null;
			}
			Read[key] = (text, Time.unscaledTime);
			return text;
		}

		public static void Request(string key, string value)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if (key == null)
			{
				return;
			}
			if (!FortifyApi.IsGuest)
			{
				Queue(key, value);
				return;
			}
			try
			{
				if (InLobby(out var lobby))
				{
					int value3;
					int value2 = (MySeq.TryGetValue(key, out value3) ? value3 : Random.Range(1, 1000)) + 1;
					MySeq[key] = value2;
					SteamMatchmaking.SetLobbyMemberData(lobby, "fyb_rq_" + key, value2 + "|" + value);
				}
			}
			catch
			{
			}
		}

		public static List<string> Take(string key)
		{
			List<string> list = new List<string>();
			if (key != null && Inbox.TryGetValue(key, out var value))
			{
				list.AddRange(value);
				value.Clear();
			}
			return list;
		}

		private static void Queue(string key, string value)
		{
			if (!Inbox.TryGetValue(key, out var value2))
			{
				value2 = (Inbox[key] = new List<string>());
			}
			if (value2.Count < 20)
			{
				value2.Add(value ?? "");
			}
		}

		public static void Update()
		{
			//IL_011f: 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)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			if (FortifyApi.IsGuest || Time.unscaledTime < _nextFlush)
			{
				return;
			}
			_nextFlush = Time.unscaledTime + 0.5f;
			if (!InLobby(out var lobby))
			{
				return;
			}
			try
			{
				foreach (KeyValuePair<string, string> item in Local)
				{
					if ((!Sent.TryGetValue(item.Key, out var value) || !(value == item.Value)) && SteamMatchmaking.SetLobbyData(lobby, "fyb_" + item.Key, item.Value))
					{
						Sent[item.Key] = item.Value;
					}
				}
				foreach (string key2 in Inbox.Keys)
				{
					Watched.Add(key2);
				}
				int numLobbyMembers = SteamMatchmaking.GetNumLobbyMembers(lobby);
				ulong num = 0uL;
				try
				{
					num = SteamUser.GetSteamID().m_SteamID;
				}
				catch
				{
				}
				for (int i = 0; i < numLobbyMembers; i++)
				{
					CSteamID lobbyMemberByIndex = SteamMatchmaking.GetLobbyMemberByIndex(lobby, i);
					if (lobbyMemberByIndex.m_SteamID == num)
					{
						continue;
					}
					foreach (string item2 in Watched)
					{
						string lobbyMemberData = SteamMatchmaking.GetLobbyMemberData(lobby, lobbyMemberByIndex, "fyb_rq_" + item2);
						if (string.IsNullOrEmpty(lobbyMemberData))
						{
							continue;
						}
						int num2 = lobbyMemberData.IndexOf('|');
						if (num2 <= 0 || !int.TryParse(lobbyMemberData.Substring(0, num2), out var result))
						{
							continue;
						}
						string key = lobbyMemberByIndex.m_SteamID + "/" + item2;
						if (!SeenSeq.TryGetValue(key, out var value2) || value2 != result)
						{
							bool num3 = !SeenSeq.ContainsKey(key);
							SeenSeq[key] = result;
							if (!num3)
							{
								Queue(item2, lobbyMemberData.Substring(num2 + 1));
							}
						}
					}
				}
			}
			catch
			{
			}
		}

		public static void Listen(string key)
		{
			if (key != null && !Inbox.ContainsKey(key))
			{
				Inbox[key] = new List<string>();
			}
		}

		public static void Reset()
		{
			Local.Clear();
			Sent.Clear();
			Read.Clear();
			Inbox.Clear();
			SeenSeq.Clear();
			Watched.Clear();
		}
	}
	internal static class Pins
	{
		private static readonly HashSet<IntPtr> Held = new HashSet<IntPtr>();

		public static void Set(NPC nat, bool on)
		{
			try
			{
				NPCMovement val = (((Object)(object)nat != (Object)null) ? nat.Movement : null);
				if (!((Object)(object)val == (Object)null))
				{
					if (on)
					{
						Held.Add(((Il2CppObjectBase)val).Pointer);
					}
					else
					{
						Held.Remove(((Il2CppObjectBase)val).Pointer);
					}
				}
			}
			catch
			{
			}
		}

		public static bool IsHeld(NPC nat)
		{
			try
			{
				NPCMovement val = (((Object)(object)nat != (Object)null) ? nat.Movement : null);
				return (Object)(object)val != (Object)null && Held.Contains(((Il2CppObjectBase)val).Pointer);
			}
			catch
			{
				return false;
			}
		}

		public static void Reset()
		{
			Held.Clear();
		}

		public static void Patch(Harmony h)
		{
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			if (h == null)
			{
				return;
			}
			Type typeFromHandle = typeof(NPCMovement);
			foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(typeFromHandle))
			{
				try
				{
					if (declaredMethod.Name == "Warp" || declaredMethod.Name == "Warp_Client")
					{
						h.Patch((MethodBase)declaredMethod, new HarmonyMethod(typeof(Pins), "WarpPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					else if (declaredMethod.Name == "IsNPCPositionValid" && declaredMethod.ReturnType == typeof(bool))
					{
						h.Patch((MethodBase)declaredMethod, new HarmonyMethod(typeof(Pins), "ValidPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
				catch
				{
				}
			}
			try
			{
				MethodInfo methodInfo = AccessTools.DeclaredPropertyGetter(typeFromHandle, "Velocity");
				if (methodInfo != null)
				{
					h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Pins), "VelocityPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch
			{
			}
			try
			{
				MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(NPCAnimation), "UpdateMovementAnimation", (Type[])null, (Type[])null);
				if (methodInfo2 != null)
				{
					h.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(Pins), "AnimPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch
			{
			}
		}

		private static bool WarpPrefix(NPCMovement __instance)
		{
			try
			{
				return (Object)(object)__instance == (Object)null || !Held.Contains(((Il2CppObjectBase)__instance).Pointer);
			}
			catch
			{
				return true;
			}
		}

		private static void VelocityPostfix(NPCMovement __instance, ref Vector3 __result)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)__instance != (Object)null && Held.Contains(((Il2CppObjectBase)__instance).Pointer))
				{
					__result = Vector3.zero;
				}
			}
			catch
			{
			}
		}

		private static bool AnimPrefix(NPCAnimation __instance)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NPC val = (((Object)(object)__instance != (Object)null) ? __instance.npc : null);
				if ((Object)(object)val == (Object)null || !IsHeld(val))
				{
					return true;
				}
				AvatarAnimation val2 = (((Object)(object)val.Avatar != (Object)null) ? val.Avatar.Animation : null);
				if ((Object)(object)val2 != (Object)null)
				{
					val2.SetMotion(Vector3.zero, false);
					val2.SetDirection(0f);
					val2.SetStrafe(0f);
				}
				return false;
			}
			catch
			{
				return true;
			}
		}

		private static bool ValidPrefix(NPCMovement __instance, ref bool __result)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || !Held.Contains(((Il2CppObjectBase)__instance).Pointer))
				{
					return true;
				}
				__result = true;
				return false;
			}
			catch
			{
				return true;
			}
		}
	}
	internal static class RainCover
	{
		private static readonly Dictionary<string, Func<Vector3, bool>> Shelters = new Dictionary<string, Func<Vector3, bool>>();

		private static readonly List<Renderer> Rain = new List<Renderer>();

		private static readonly List<Renderer> Hidden = new List<Renderer>();

		private static readonly List<ScriptableRendererFeature> HiddenFeatures = new List<ScriptableRendererFeature>();

		private static bool _scanned;

		private static bool _inside;

		private static float _next;

		public static void Add(string key, Func<Vector3, bool> inside)
		{
			if (key != null && inside != null)
			{
				Shelters[key] = inside;
			}
		}

		public static void Remove(string key)
		{
			if (key != null)
			{
				Shelters.Remove(key);
			}
		}

		public static void Update()
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if ((Shelters.Count == 0 && !_inside) || Time.unscaledTime < _next)
			{
				return;
			}
			_next = Time.unscaledTime + 0.2f;
			Vector3 position;
			try
			{
				PlayerCamera instance = PlayerSingleton<PlayerCamera>.Instance;
				Transform val = (((Object)(object)instance != (Object)null && (Object)(object)instance.Camera != (Object)null) ? ((Component)instance.Camera).transform : (((Object)(object)Camera.main != (Object)null) ? ((Component)Camera.main).transform : null));
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				position = val.position;
			}
			catch
			{
				return;
			}
			bool flag = false;
			foreach (Func<Vector3, bool> value in Shelters.Values)
			{
				try
				{
					if (value(position))
					{
						flag = true;
						break;
					}
				}
				catch
				{
				}
			}
			if (flag != _inside)
			{
				_inside = flag;
				if (flag)
				{
					Hide();
				}
				else
				{
					Restore();
				}
			}
		}

		private static void Hide()
		{
			try
			{
				if (!_scanned)
				{
					_scanned = true;
					HashSet<int> hashSet = new HashSet<int>();
					foreach (RainController item in Object.FindObjectsOfType<RainController>())
					{
						foreach (Renderer componentsInChild in ((Component)item).GetComponentsInChildren<Renderer>(true))
						{
							if ((Object)(object)componentsInChild != (Object)null && hashSet.Add(((Object)componentsInChild).GetInstanceID()))
							{
								Rain.Add(componentsInChild);
							}
						}
					}
				}
				foreach (Renderer item2 in Rain)
				{
					if ((Object)(object)item2 != (Object)null && item2.enabled)
					{
						item2.enabled = false;
						Hidden.Add(item2);
					}
				}
				RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
				UniversalRenderPipelineAsset val = ((currentRenderPipeline != null) ? ((Il2CppObjectBase)currentRenderPipeline).TryCast<UniversalRenderPipelineAsset>() : null);
				Il2CppReferenceArray<ScriptableRendererData> val2 = (((Object)(object)val != (Object)null) ? val.m_RendererDataList : null);
				int num = 0;
				while (val2 != null && num < ((Il2CppArrayBase<ScriptableRendererData>)(object)val2).Length)
				{
					ScriptableRendererData val3 = ((Il2CppArrayBase<ScriptableRendererData>)(object)val2)[num];
					if (!((Object)(object)val3 == (Object)null) && val3.rendererFeatures != null)
					{
						Enumerator<ScriptableRendererFeature> enumerator4 = val3.rendererFeatures.GetEnumerator();
						while (enumerator4.MoveNext())
						{
							ScriptableRendererFeature current3 = enumerator4.Current;
							if (!((Object)(object)current3 == (Object)null) && current3.isActive && (((Object)current3).name + " " + ((MemberInfo)((Object)current3).GetIl2CppType()).Name).IndexOf("rain", StringComparison.OrdinalIgnoreCase) >= 0)
							{
								current3.SetActive(false);
								HiddenFeatures.Add(current3);
							}
						}
					}
					num++;
				}
			}
			catch
			{
			}
		}

		private static void Restore()
		{
			foreach (Renderer item in Hidden)
			{
				if ((Object)(object)item != (Object)null)
				{
					item.enabled = true;
				}
			}
			Hidden.Clear();
			foreach (ScriptableRendererFeature hiddenFeature in HiddenFeatures)
			{
				try
				{
					if ((Object)(object)hiddenFeature != (Object)null)
					{
						hiddenFeature.SetActive(true);
					}
				}
				catch
				{
				}
			}
			HiddenFeatures.Clear();
		}

		public static void Reset()
		{
			Restore();
			_inside = false;
			_scanned = false;
			Rain.Clear();
			Shelters.Clear();
		}
	}
	internal static class TreeCut
	{
		private static readonly Dictionary<string, (Vector3 c, float r)> Clearings = new Dictionary<string, (Vector3, float)>();

		private static readonly Dictionary<int, (Texture2D tex, byte[] orig, int count)> Textures = new Dictionary<int, (Texture2D, byte[], int)>();

		private static readonly List<GameObject> Trunks = new List<GameObject>();

		private static bool _dirty;

		public static void Add(string key, Vector3 centre, float radius)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (key != null)
			{
				Clearings[key] = (centre, radius);
				_dirty = true;
			}
		}

		public static void Remove(string key)
		{
			if (key != null && Clearings.Remove(key))
			{
				_dirty = true;
			}
		}

		public static void Update()
		{
			if (_dirty)
			{
				_dirty = false;
				Apply();
			}
		}

		private static bool Cleared(float x, float z, float pad)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			foreach (var value in Clearings.Values)
			{
				Vector3 item = value.c;
				float item2 = value.r;
				float num = x - item.x;
				float num2 = z - item.z;
				float num3 = item2 + pad;
				if (num * num + num2 * num2 < num3 * num3)
				{
					return true;
				}
			}
			return false;
		}

		private static void Apply()
		{
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			int num2 = 0;
			try
			{
				Find();
				foreach (KeyValuePair<int, (Texture2D, byte[], int)> texture in Textures)
				{
					var (val, array, num3) = texture.Value;
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					float[] array2 = new float[array.Length / 4];
					Buffer.BlockCopy(array, 0, array2, 0, array.Length);
					for (int i = 0; i < num3; i++)
					{
						int num4 = i * 4;
						if (!(array2[num4 + 3] <= 0f) && Cleared(array2[num4], array2[num4 + 2], 2.5f))
						{
							array2[num4 + 3] = 0f;
							num++;
						}
					}
					byte[] array3 = new byte[array.Length];
					Buffer.BlockCopy(array2, 0, array3, 0, array3.Length);
					val.LoadRawTextureData(new Il2CppStructArray<byte>(array3));
					val.Apply(false, false);
				}
				foreach (GameObject trunk in Trunks)
				{
					if ((Object)(object)trunk != (Object)null)
					{
						trunk.SetActive(true);
					}
				}
				Trunks.Clear();
				if (Clearings.Count > 0)
				{
					foreach (FoliageRustleSound item in Object.FindObjectsOfType<FoliageRustleSound>())
					{
						if (!((Object)(object)item == (Object)null) && ((Object)item).name.StartsWith("Tree", StringComparison.OrdinalIgnoreCase))
						{
							Vector3 position = ((Component)item).transform.position;
							if (Cleared(position.x, position.z, 2.5f))
							{
								((Component)item).gameObject.SetActive(false);
								Trunks.Add(((Component)item).gameObject);
								num2++;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				FortifyApi.Log("Trees: couldn't clear the lot (" + ex.Message + ").");
				return;
			}
			if (Clearings.Count > 0)
			{
				FortifyApi.Log($"Trees: {num} tree(s) cleared off the lot ({num2} trunk(s)).");
			}
		}

		private static void Find()
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Invalid comparison between Unknown and I4
			List<InstanceObjectData> list = new List<InstanceObjectData>();
			try
			{
				InstancingManager val = Object.FindObjectOfType<InstancingManager>();
				List<InstanceObjectData> val2 = (((Object)(object)val != (Object)null) ? val.BackedInstanceObjects : null);
				int num = 0;
				while (val2 != null && num < val2.Count)
				{
					if ((Object)(object)val2[num] != (Object)null)
					{
						list.Add(val2[num]);
					}
					num++;
				}
			}
			catch
			{
			}
			foreach (InstanceObjectData item in list)
			{
				try
				{
					if ((item.Id ?? "").IndexOf("tree", StringComparison.OrdinalIgnoreCase) < 0)
					{
						continue;
					}
					Texture2D positionData = item.PositionData;
					if ((Object)(object)positionData == (Object)null || !((Texture)positionData).isReadable || (int)positionData.format != 20)
					{
						continue;
					}
					int instanceID = ((Object)positionData).GetInstanceID();
					if (!Textures.ContainsKey(instanceID))
					{
						Il2CppStructArray<byte> rawTextureData = positionData.GetRawTextureData();
						byte[] array = new byte[((Il2CppArrayBase<byte>)(object)rawTextureData).Length];
						for (int i = 0; i < array.Length; i++)
						{
							array[i] = ((Il2CppArrayBase<byte>)(object)rawTextureData)[i];
						}
						Textures[instanceID] = (positionData, array, Math.Min(item.InstanceCount, array.Length / 16));
					}
				}
				catch
				{
				}
			}
		}

		public static void Reset()
		{
			try
			{
				foreach (KeyValuePair<int, (Texture2D, byte[], int)> texture in Textures)
				{
					var (val, array, _) = texture.Value;
					if (!((Object)(object)val == (Object)null))
					{
						val.LoadRawTextureData(new Il2CppStructArray<byte>(array));
						val.Apply(false, false);
					}
				}
			}
			catch
			{
			}
			foreach (GameObject trunk in Trunks)
			{
				if ((Object)(object)trunk != (Object)null)
				{
					trunk.SetActive(true);
				}
			}
			Trunks.Clear();
			Textures.Clear();
			Clearings.Clear();
			_dirty = false;
		}
	}
}
namespace StreetTalkMod
{
	internal sealed class AiAsk
	{
		public int Ticket;

		public string System = "";

		public readonly List<(bool you, string text)> Turns = new List<(bool, string)>();

		public string Name = "";

		public string Full = "";

		public float Timeout = 10f;

		public string Mode = "";

		public string Key = "";

		public string Model = "";

		public string Url = "";
	}
	internal sealed class AiAnswer
	{
		public int Ticket;

		public string Text;

		public string Error;

		public double Seconds;
	}
	internal static class Ai
	{
		public enum Provider
		{
			Off,
			Claude,
			OpenAI,
			Ollama,
			Custom
		}

		public static readonly ConcurrentQueue<AiAnswer> Answers = new ConcurrentQueue<AiAnswer>();

		private static HttpClient _http;

		private static readonly object Gate = new object();

		private static int _running;

		private static readonly Regex Stars = new Regex("\\*[^*\\n]{0,80}\\*");

		private static readonly Regex Brackets = new Regex("\\[[^\\]\\n]{0,60}\\]");

		private static readonly Regex StageParens = new Regex("\\((?:[a-z][^()\\n]{0,40})\\)");

		private static readonly Regex Spaces = new Regex("\\s+");

		private static readonly Regex SpaceBefore = new Regex("\\s+([,.!?;:])");

		private static readonly Regex Think = new Regex("<think>.*?</think>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

		public static Provider Mode => Parse(Settings.AiMode);

		public static bool Configured
		{
			get
			{
				switch (Mode)
				{
				case Provider.Claude:
				case Provider.OpenAI:
					return Settings.AiKey.Length >= 20;
				case Provider.Ollama:
					return true;
				case Provider.Custom:
					return Settings.AiUrl.Length > 7;
				default:
					return false;
				}
			}
		}

		public static Provider Parse(string s)
		{
			s = (s ?? "").Trim().ToLowerInvariant();
			if (s.Length != 0)
			{
				switch (s)
				{
				case "off":
				case "none":
				case "false":
				case "no":
					break;
				default:
					if (s.Contains("claude") || s.Contains("anthropic"))
					{
						return Provider.Claude;
					}
					if (s.Contains("openai") || s.Contains("chatgpt") || s.Contains("gpt"))
					{
						return Provider.OpenAI;
					}
					if (s.Contains("ollama") || s == "local")
					{
						return Provider.Ollama;
					}
					if (s.Contains("custom") || s.Contains("lm studio") || s.Contains("lmstudio") || s.Contains("compatible"))
					{
						return Provider.Custom;
					}
					return Provider.Off;
				}
			}
			return Provider.Off;
		}

		public static string DefaultModel(Provider p)
		{
			return p switch
			{
				Provider.Claude => "claude-haiku-4-5", 
				Provider.OpenAI => "gpt-4o-mini", 
				Provider.Ollama => "llama3.2", 
				_ => "local-model", 
			};
		}

		public static string Describe()
		{
			Provider mode = Mode;
			if (mode == Provider.Off)
			{
				return "off";
			}
			string value = ((Settings.AiModel.Length > 0) ? Settings.AiModel : DefaultModel(mode));
			if (!Configured)
			{
				if (mode == Provider.Custom)
				{
					return $"{mode} (no AIUrl set, using the built-in generator)";
				}
				return $"{mode} (no API key set, using the built-in generator)";
			}
			return $"{mode}, {value}";
		}

		public static void Ask(AiAsk a)
		{
			a.Mode = Mode.ToString();
			a.Key = Settings.AiKey;
			a.Model = Settings.AiModel;
			a.Url = Settings.AiUrl;
			a.Timeout = Settings.AiTimeout;
			if (Interlocked.Increment(ref _running) > 4)
			{
				Interlocked.Decrement(ref _running);
				Answers.Enqueue(new AiAnswer
				{
					Ticket = a.Ticket,
					Error = "too many questions at once"
				});
				return;
			}
			Task.Run(async delegate
			{
				try
				{
					await Run(a).ConfigureAwait(continueOnCapturedContext: false);
				}
				finally
				{
					Interlocked.Decrement(ref _running);
				}
			});
		}

		public static void Shutdown()
		{
			lock (Gate)
			{
				try
				{
					_http?.Dispose();
				}
				catch
				{
				}
				_http = null;
			}
		}

		private static HttpClient Http()
		{
			lock (Gate)
			{
				if (_http == null)
				{
					_http = new HttpClient
					{
						Timeout = Timeout.InfiniteTimeSpan
					};
					_http.DefaultRequestHeaders.UserAgent.ParseAdd("StreetTalk/1.0");
				}
				return _http;
			}
		}

		private static async Task Run(AiAsk a)
		{
			Stopwatch sw = Stopwatch.StartNew();
			AiAnswer ans = new AiAnswer
			{
				Ticket = a.Ticket
			};
			try
			{
				Provider provider = Parse(a.Mode);
				using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(Math.Max(3f, a.Timeout)));
				ans.Text = Clean(provider switch
				{
					Provider.Claude => await Claude(a, cts.Token).ConfigureAwait(continueOnCapturedContext: false), 
					Provider.OpenAI => await OpenAi(a, "https://api.openai.com/v1/chat/completions", a.Key, (a.Model.Length > 0) ? a.Model : DefaultModel(provider), cts.Token).ConfigureAwait(continueOnCapturedContext: false), 
					Provider.Ollama => await Ollama(a, cts.Token).ConfigureAwait(continueOnCapturedContext: false), 
					Provider.Custom => await OpenAi(a, ChatUrl(a.Url), a.Key, (a.Model.Length > 0) ? a.Model : DefaultModel(provider), cts.Token).ConfigureAwait(continueOnCapturedContext: false), 
					_ => throw new InvalidOperationException("AI replies are off"), 
				}, a.Name, a.Full);
				if (string.IsNullOrWhiteSpace(ans.Text))
				{
					ans.Error = "the AI's answer was empty";
				}
			}
			catch (OperationCanceledException)
			{
				ans.Error = $"no answer within {a.Timeout:0} seconds";
			}
			catch (HttpRequestException ex2)
			{
				ans.Error = "couldn't reach the AI (" + Short(ex2.Message) + ")";
			}
			catch (Exception ex3)
			{
				ans.Error = Short(ex3.Message);
			}
			ans.Seconds = sw.Elapsed.TotalSeconds;
			Answers.Enqueue(ans);
		}

		private static async Task<string> Claude(AiAsk a, CancellationToken ct)
		{
			List<object> list = new List<object>();
			foreach (var (flag, content) in Merge(a.Turns))
			{
				list.Add(new
				{
					role = (flag ? "user" : "assistant"),
					content = content
				});
			}
			var body = new
			{
				model = ((a.Model.Length > 0) ? a.Model : DefaultModel(Provider.Claude)),
				max_tokens = 120,
				temperature = 0.9,
				system = a.System,
				messages = list
			};
			using HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://api.anthropic.com/v1/messages");
			req.Headers.Add("x-api-key", a.Key);
			req.Headers.Add("anthropic-version", "2023-06-01");
			req.Content = Json(body);
			using JsonDocument jsonDocument = await Send(req, ct).ConfigureAwait(continueOnCapturedContext: false);
			JsonElement rootElement = jsonDocument.RootElement;
			if (rootElement.TryGetProperty("content", out var value) && value.ValueKind == JsonValueKind.Array)
			{
				StringBuilder stringBuilder = new StringBuilder();
				foreach (JsonElement item in value.EnumerateArray())
				{
					if (item.TryGetProperty("type", out var value2) && value2.GetString() == "text" && item.TryGetProperty("text", out var value3))
					{
						stringBuilder.Append(value3.GetString());
					}
				}
				return stringBuilder.ToString();
			}
			throw new InvalidOperationException(ErrorOf(rootElement) ?? "unexpected answer from Claude");
		}

		private static async Task<string> OpenAi(AiAsk a, string url, string key, string model, CancellationToken ct)
		{
			List<object> list = new List<object>
			{
				new
				{
					role = "system",
					content = a.System
				}
			};
			foreach (var (flag, content) in Merge(a.Turns))
			{
				list.Add(new
				{
					role = (flag ? "user" : "assistant"),
					content = content
				});
			}
			var body = new
			{
				model = model,
				messages = list,
				max_tokens = 120,
				temperature = 0.9
			};
			using HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
			if (!string.IsNullOrEmpty(key))
			{
				req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
			}
			req.Content = Json(body);
			using JsonDocument jsonDocument = await Send(req, ct).ConfigureAwait(continueOnCapturedContext: false);
			JsonElement rootElement = jsonDocument.RootElement;
			if (rootElement.TryGetProperty("choices", out var value) && value.ValueKind == JsonValueKind.Array)
			{
				foreach (JsonElement item in value.EnumerateArray())
				{
					if (item.TryGetProperty("message", out var value2) && value2.TryGetProperty("content", out var value3) && value3.ValueKind == JsonValueKind.String)
					{
						return value3.GetString();
					}
					if (item.TryGetProperty("text", out var value4) && value4.ValueKind == JsonValueKind.String)
					{
						return value4.GetString();
					}
				}
			}
			throw new InvalidOperationException(ErrorOf(rootElement) ?? "unexpected answer from the AI");
		}

		private static async Task<string> Ollama(AiAsk a, CancellationToken ct)
		{
			string text = (a.Url ?? "").Trim();
			if (text.Length == 0)
			{
				text = "http://localhost:11434";
			}
			if (text.IndexOf("/v1", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return await OpenAi(a, ChatUrl(text), a.Key, (a.Model.Length > 0) ? a.Model : DefaultModel(Provider.Ollama), ct).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (!text.EndsWith("/api/chat", StringComparison.OrdinalIgnoreCase))
			{
				text = text.TrimEnd('/') + "/api/chat";
			}
			List<object> list = new List<object>
			{
				new
				{
					role = "system",
					content = a.System
				}
			};
			foreach (var (flag, content) in Merge(a.Turns))
			{
				list.Add(new
				{
					role = (flag ? "user" : "assistant"),
					content = content
				});
			}
			var body = new
			{
				model = ((a.Model.Length > 0) ? a.Model : DefaultModel(Provider.Ollama)),
				messages = list,
				stream = false,
				options = new
				{
					temperature = 0.9,
					num_predict = 120
				}
			};
			using HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, text)
			{
				Content = Json(body)
			};
			using JsonDocument jsonDocument = await Send(req, ct).ConfigureAwait(continueOnCapturedContext: false);
			JsonElement rootElement = jsonDocument.RootElement;
			if (rootElement.TryGetProperty("message", out var value) && value.TryGetProperty("content", out var value2))
			{
				return value2.GetString();
			}
			throw new InvalidOperationException(ErrorOf(rootElement) ?? "unexpected answer from Ollama");
		}

		public static string ChatUrl(string url)
		{
			url = (url ?? "").Trim().TrimEnd('/');
			if (url.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase))
			{
				return url;
			}
			if (url.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
			{
				return url + "/chat/completions";
			}
			return url + "/v1/chat/completions";
		}

		private static StringContent Json(object body)
		{
			return new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
		}

		private static async Task<JsonDocument> Send(HttpRequestMessage req, CancellationToken ct)
		{
			using HttpResponseMessage res = await Http().SendAsync(req, ct).ConfigureAwait(continueOnCapturedContext: false);
			string text = await res.Content.ReadAsStringAsync(ct).ConfigureAwait(continueOnCapturedContext: false);
			JsonDocument jsonDocument;
			try
			{
				jsonDocument = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "{}" : text);
			}
			catch
			{
				throw new InvalidOperationException($"the AI answered with HTTP {res.StatusCode} and no readable reply");
			}
			if (!res.IsSuccessStatusCode)
			{
				string text2 = ErrorOf(jsonDocument.RootElement);
				jsonDocument.Dispose();
				int statusCode = (int)res.StatusCode;
				object obj2;
				switch (statusCode)
				{
				default:
					obj2 = "";
					break;
				case 429:
					obj2 = " (rate limit or no credit left)";
					break;
				case 404:
					obj2 = " (check AIModel and AIUrl)";
					break;
				case 401:
				case 403:
					obj2 = " (check your AIKey)";
					break;
				}
				string value = (string)obj2;
				throw new InvalidOperationException($"HTTP {statusCode}{value}" + ((text2 != null) ? (": " + Short(text2)) : ""));
			}
			return jsonDocument;
		}

		private static string ErrorOf(JsonElement root)
		{
			try
			{
				if (root.ValueKind != JsonValueKind.Object)
				{
					return null;
				}
				if (root.TryGetProperty("error", out var value))
				{
					if (value.ValueKind == JsonValueKind.String)
					{
						return value.GetString();
					}
					if (value.ValueKind == JsonValueKind.Object && value.TryGetProperty("message", out var value2))
					{
						return value2.GetString();
					}
				}
				if (root.TryGetProperty("message", out var value3) && value3.ValueKind == JsonValueKind.String)
				{
					return value3.GetString();
				}
			}
			catch
			{
			}
			return null;
		}

		private static List<(bool you, string text)> Merge(List<(bool you, string text)> turns)
		{
			List<(bool, string)> list = new List<(bool, string)>();
			foreach (var (flag, text) in turns)
			{
				if (!string.IsNullOrWhiteSpace(text) && (list.Count != 0 || flag))
				{
					if (list.Count > 0 && list[list.Count - 1].Item1 == flag)
					{
						list[list.Count - 1] = (flag, list[list.Count - 1].Item2 + " " + text);
					}
					else
					{
						list.Add((flag, text));
					}
				}
			}
			if (list.Count == 0)
			{
				list.Add((true, "Hey."));
			}
			if (!list[list.Count - 1].Item1)
			{
				list.Add((true, "..."));
			}
			return list;
		}

		private static string Short(string s)
		{
			if (!string.IsNullOrEmpty(s))
			{
				if (s.Length > 160)
				{
					return s.Substring(0, 157) + "...";
				}
				return s;
			}
			return "";
		}

		public static string Clean(string raw, string first, string full)
		{
			if (string.IsNullOrWhiteSpace(raw))
			{
				return null;
			}
			string text = Think.Replace(raw, " ");
			int num = text.IndexOf("<think>", StringComparison.OrdinalIgnoreCase);
			if (num >= 0)
			{
				text = text.Substring(0, num);
			}
			text = text.Replace('‘', '\'').Replace('’', '\'').Replace('“', '"')
				.Replace('”', '"')
				.Replace("—", ", ")
				.Replace("–", "-")
				.Replace("…", "...")
				.Replace('\u00a0', ' ');
			text = Stars.Replace(text, " ");
			text = Brackets.Replace(text, " ");
			text = StageParens.Replace(text, " ");
			text = text.Replace("*", "").Replace("#", "").Replace("_", " ")
				.Replace("~", "");
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			string text2 = text;
			foreach (char c in text2)
			{
				if (!char.IsSurrogate(c))
				{
					if (char.IsLetterOrDigit(c) || c == ' ' || ".,!?'\"-:;$%&()/+=@".IndexOf(c) >= 0)
					{
						stringBuilder.Append(c);
					}
					else if (char.IsWhiteSpace(c))
					{
						stringBuilder.Append(' ');
					}
				}
			}
			text = Spaces.Replace(stringBuilder.ToString(), " ").Trim();
			text = SpaceBefore.Replace(text, "$1");
			while (text.Contains(",,"))
			{
				text = text.Replace(",,", ",");
			}
			string[] array = new string[2] { full, first };
			foreach (string text3 in array)
			{
				if (!string.IsNullOrEmpty(text3) && text.StartsWith(text3 + ":", StringComparison.OrdinalIgnoreCase))
				{
					text = text.Substring(text3.Length + 1).Trim();
				}
			}
			if (text.Length > 2 && text[0] == '"' && text.IndexOf('"', 1) == text.Length - 1)
			{
				text = text.Substring(1, text.Length - 2).Trim();
			}
			text = text.Trim('"', ' ');
			int num2 = 0;
			for (int j = 0; j < text.Length; j++)
			{
				char c2 = text[j];
				if ((c2 == '.' || c2 == '!' || c2 == '?') && (j + 1 >= text.Length || text[j + 1] == ' ') && (j <= 0 || c2 != '.' || text[j - 1] != '.') && ++num2 >= 3 && j + 1 < text.Length)
				{
					text = text.Substring(0, j + 1);
					break;
				}
			}
			if (text.Length > 260)
			{
				int num3 = text.LastIndexOfAny(new char[3] { '.', '!', '?' }, 259);
				text = ((num3 > 40) ? text.Substring(0, num3 + 1) : (text.Substring(0, 257).TrimEnd() + "..."));
			}
			if (text.Length != 0)
			{
				return text;
			}
			return null;
		}
	}
	internal sealed class Reply
	{
		public string Text = "";

		public string Emotion;

		public bool Ends;

		public bool Ignored;

		public bool Fixed;
	}
	internal sealed class Ctx
	{
		public Mind M;

		public Situation S;

		public Traits T;

		public Utterance U;

		public Random R;

		public bool Greeted;

		public int Fam;

		public string Topic = "";

		public string X = "";

		public string Old = "";

		public string Other = "";

		public string When = "";

		public string Name = "";

		public string Region2 = "";

		public string ForcedEmotion;

		public bool IsGreeting;

		public bool AskedSomething;

		public bool NoExtra;
	}
	internal static class Brain
	{
		private static readonly Random Rng = new Random();

		private static readonly Queue<string> GlobalUsed = new Queue<string>();

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

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

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

		private static Dictionary<string, string> _names;

		private static float _namesAt = -100f;

		private static readonly string[] ThreatPhrases = new string[37]
		{
			"kill you", "hurt you", "shoot you", "beat you", "punch you", "stab you", "rob you", "mug you", "smack you", "slap you",
			"choke you", "end you", "murder you", "break your", "give me your money", "give me your wallet", "give me your stuff", "give me your cash", "hand it over", "hand over your",
			"you are dead", "you are going to die", "watch your back", "i will find you", "hands up", "i have a gun", "i got a gun", "i will kill", "i am going to kill", "you are next",
			"or else", "run while you can", "i will hurt", "i am going to hurt", "beat you up", "kick your", "your money or"
		};

		private static readonly string[] InsultPhrases = new string[15]
		{
			"shut up", "screw you", "fuck you", "fuck off", "piss off", "go to hell", "you suck", "i hate you", "nobody likes you", "drop dead",
			"eat shit", "kiss my", "get lost", "you stink", "you smell"
		};

		private static readonly HashSet<string> InsultWords = new HashSet<string>
		{
			"idiot", "stupid", "dumb", "moron", "loser", "ugly", "fat", "jerk", "clown", "trash",
			"garbage", "freak", "weirdo", "creep", "lame", "worthless", "pathetic", "dork", "bozo", "dummy",
			"imbecile", "scum", "idiots", "morons", "bitch", "asshole", "dick", "bastard", "prick", "douche",
			"douchebag", "dipshit", "shithead", "jackass", "twat", "cunt", "motherfucker", "retard", "simp", "nerd",
			"goofy", "clueless", "useless", "wimp", "coward", "snitch", "rat"
		};

		private static readonly HashSet<string> SwearWords = new HashSet<string>
		{
			"fuck", "fucking", "shit", "damn", "hell", "crap", "goddamn", "bullshit", "fucked", "shitty",
			"dammit"
		};

		private static readonly string[] Products = new string[34]
		{
			"weed", "kush", "marijuana", "meth", "cocaine", "coke", "crack", "shrooms", "mushrooms", "drugs",
			"drug", "dope", "molly", "ecstasy", "mdma", "heroin", "lsd", "dmt", "pcp", "angel dust",
			"product", "pills", "blunt", "joint", "baggie", "stash", "acid", "tabs", "edibles", "pre rolls",
			"pre roll", "vape", "black tar", "blotter"
		};

		private static readonly string[] CopWords = new string[15]
		{
			"cop", "cops", "police", "officer", "officers", "pig", "pigs", "feds", "fed", "detective",
			"sheriff", "arrest", "arrested", "the law", "five oh"
		};

		private static readonly string[] RegionWords = new string[11]
		{
			"northtown", "westville", "downtown", "docks", "the docks", "suburbia", "uptown", "bayside", "copper mesa", "hyland point",
			"hyland"
		};

		private static readonly Regex RxName = new Regex(" (?:my name is|call me|the name is|name is|i am called|they call me|people call me|you can call me|it is|i go by) ([a-z]+)");

		private static readonly Regex RxIAm = new Regex("^ (?:i am|this is|it is) ([a-z]+) $");

		private static readonly HashSet<string> NotNames = new HashSet<string>
		{
			"not", "fine", "good", "okay", "here", "back", "sorry", "tired", "hungry", "bored",
			"ready", "done", "home", "lost", "new", "nobody", "none", "me", "you", "him",
			"her", "no", "yes", "just", "so", "very", "really", "a", "an", "the",
			"going", "leaving", "busy", "great", "awesome", "sad", "happy", "mad", "angry", "high",
			"drunk", "broke", "sick", "scared", "alone", "lonely", "late", "early", "cool", "alright",
			"well", "on", "in", "out", "off", "over", "nice", "your", "his", "her",
			"kidding", "joking", "serious", "rich", "poor", "free", "single", "taken"
		};

		private static readonly HashSet<string> NotNameWords = new HashSet<string>
		{
			"cop", "cops", "police", "pig", "pigs", "gun", "guns", "weed", "meth", "coke",
			"cocaine", "drugs", "drug", "product", "stuff", "money", "cash", "deal", "deals", "work",
			"job", "jobs", "around", "here", "there", "today", "tonight", "now", "later", "sure",
			"maybe", "nah", "yeah", "yep", "nope", "ok", "okay", "hey", "hi", "hello",
			"yo", "sup", "bro", "man", "dude", "boss", "buddy", "thanks", "thank", "please",
			"sorry", "what", "huh", "why", "who", "nothing", "something", "anything", "everything", "buy",
			"sell", "selling", "buying", "need", "want", "got", "get", "give", "take", "come",
			"go", "look", "see", "help", "stop", "wait", "shut", "up", "lol", "haha",
			"bye", "later", "cool", "nice", "bad", "good", "fine", "great", "town", "street",
			"car", "house"
		};

		private static readonly Regex RxPlan = new Regex(" i (?:am going to|will|am about to|plan to|am planning to|might) (.+)");

		private static readonly Regex RxIdentity = new Regex(" i am (?:a|an) (.+)");

		private static readonly Regex RxHome = new Regex(" i (?:am from|live in|live at|live on|live near|live by|stay in|grew up in) (.+)");

		private static readonly Regex RxWork = new Regex(" i work (?:at|in|for|as|with|on) (.+)");

		private static readonly Regex RxFeel = new Regex(" i (?:am|feel|am feeling|have been|been|am getting) (?:so |really |very |pretty |kind of |sort of |a bit |a little |super |extremely |totally |just |getting )*([a-z]+)");

		private static readonly Regex RxLike = new Regex(" i (?:really |totally |absolutely |kind of |also )?(?:like|love|enjoy|adore|dig|am into|am a fan of|am a big fan of|am obsessed with) (.+)");

		private static readonly Regex RxHate = new Regex(" i (?:really |totally |kind of )?(?:hate|dislike|despise|cannot stand|do not like|do not love|am not into|am sick of|am tired of) (.+)");

		private static readonly Regex RxHave = new Regex(" i (?:have|have got|got|own|bought|found|just got|just bought) (?:a |an |some |the |my |this |new )?(.+)");

		private static readonly Regex RxWant = new Regex(" i (?:want|need|would like|wish i had|could use) (?:a |an |some |the |to )?(.+)");

		private static readonly HashSet<string> GoodFeel = new HashSet<string>
		{
			"good", "great", "fine", "okay", "awesome", "amazing", "happy", "excited", "fantastic", "wonderful",
			"blessed", "chill", "relaxed", "alright", "well", "better", "glad", "pumped", "stoked", "perfect",
			"lucky"
		};

		private static readonly HashSet<string> TiredFeel = new HashSet<string> { "tired", "sleepy", "exhausted", "beat", "drained", "wiped" };

		private static readonly HashSet<string> SadFeel = new HashSet<string>
		{
			"sad", "depressed", "down", "upset", "blue", "miserable", "heartbroken", "unhappy", "crying", "hurt",
			"stressed"
		};

		private static readonly HashSet<string> AngryFeel = new HashSet<string> { "angry", "mad", "pissed", "furious", "annoyed", "irritated", "frustrated" };

		private static readonly HashSet<string> HighFeel = new HashSet<string>
		{
			"high", "stoned", "baked", "drunk", "wasted", "buzzed", "faded", "lit", "tipsy", "hammered",
			"blazed", "zooted"
		};

		private static readonly HashSet<string> ScaredFeel = new HashSet<string> { "scared", "afraid", "nervous", "anxious", "worried", "terrified", "paranoid", "spooked" };

		private static readonly HashSet<string> WhWords = new HashSet<string> { "what", "who", "where", "when", "why", "how", "which" };

		private static readonly HashSet<string> AuxWords = new HashSet<string>
		{
			"do", "does", "did", "are", "is", "can", "could", "will", "would", "have",
			"has", "were", "was", "should"
		};

		private static readonly HashSet<string> NotAnAnswer = new HashSet<string>
		{
			"you", "your", "what", "why", "how", "who", "where", "when", "are", "do",
			"did", "is", "can", "could", "would", "will", "get", "go", "shut", "stop",
			"hey", "hi", "hello", "bye", "thanks", "thank", "sorry", "no", "yes", "nah",
			"yeah", "okay", "please", "just", "let", "tell", "give"
		};

		private static readonly string[] SlangAddr = new string[6] { "man", "dude", "bro", "my guy", "homie", "chief" };

		private static readonly string[] PlainAddr = new string[3] { "friend", "buddy", "pal" };

		public static Reply Respond(Mind m, Situation s, string said)
		{
			m.Settle(s);
			Utterance utterance = Utterance.Parse(said);
			Ctx ctx = new Ctx
			{
				M = m,
				S = s,
				T = m.T,
				R = Rng
			};
			ctx.U = utterance.WithoutGreeting(out ctx.Greeted);
			ctx.Fam = m.Familiarity(s);
			ctx.Name = m.D.PlayerName ?? "";
			ctx.Region2 = People.RandomRegion(Rng, s.Region);
			Reply reply = new Reply();
			string text;
			try
			{
				text = Think(ctx, reply);
			}
			catch (Exception ex)
			{
				Instance log = TalkCore.Log;
				if (log != null)
				{
					log.Warning("Reply: " + ex.Message);
				}
				text = Pick(ctx, "ack", Lines.Ack);
			}
			if (string.IsNullOrWhiteSpace(text))
			{
				text = Pick(ctx, "ack", Lines.Ack);
			}
			string text2 = (reply.Ignored ? text : Dress(ctx, reply, text));
			reply.Text = Finish(ctx, text2);
			Clamp(m);
			reply.Emotion = ctx.ForcedEmotion ?? m.Emotion();
			m.LastHeard = Time.unscaledTime;
			m.LastSeen = Time.unscaledTime;
			m.LastSaidNorm = utterance.Norm;
			return reply;
		}

		public static Reply DidntCatch(Mind m, Situation s)
		{
			m.Settle(s);
			Ctx c = new Ctx
			{
				M = m,
				S = s,
				T = m.T,
				R = Rng,
				U = Utterance.Parse(""),
				Fam = m.Familiarity(s)
			};
			return new Reply
			{
				Text = Finish(c, Pick(c, "didnt", Lines.DidntCatch)),
				Emotion = m.Emotion()
			};
		}

		private static void Clamp(Mind m)
		{
			m.Mood = Mathf.Clamp(m.Mood, -1f, 1f);
			m.Fear = Mathf.Clamp01(m.Fear);
			m.Annoy = Mathf.Clamp01(m.Annoy);
			m.D.Warmth = Mathf.Clamp(m.D.Warmth, -1f, 1f);
		}

		private static bool Boss(Situation s)
		{
			if ((s.Role != Role.Dealer || !s.Recruited) && s.Role != Role.Worker)
			{
				return s.Role == Role.Crew;
			}
			return true;
		}

		private static bool HasProduct(Utterance u)
		{
			return u.Any(Products);
		}

		private static bool Directed(Utterance u)
		{
			if (u.Any(InsultPhrases))
			{
				return true;
			}
			bool flag = u.Has("you") || u.Has("your") || u.Has("you are");
			for (int i = 0; i < u.Words.Length; i++)
			{
				if (InsultWords.Contains(u.Words[i]) && (flag || i == 0 || u.Words.Length <= 2))
				{
					return true;
				}
			}
			return false;
		}

		private static string Think(Ctx c, Reply r)
		{
			Mind m = c.M;
			Situation s = c.S;
			Utterance u = c.U;
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < m.IgnoreUntil)
			{
				r.Ignored = true;
				r.Fixed = true;
				m.Annoy = Mathf.Min(1f, m.Annoy + 0.05f);
				return Pick(c, "ignore", Lines.Ignore);
			}
			if (s.Pursuit >= 2 && s.Role == Role.Cop)
			{
				r.Fixed = true;
				c.ForcedEmotion = "Angry";
				return Pick(c, "wantedcop", Lines.WantedCop);
			}
			if (!u.Empty && c.U.Norm == m.LastSaidNorm && unscaledTime - m.LastHeard < 90f && u.Words.Length > 1)
			{
				m.Annoy += 0.15f;
				r.Fixed = true;
				return Pick(c, "repeat", Lines.Repeat);
			}
			if (unscaledTime - m.LastHeard < 1.2f)
			{
				m.Annoy += 0.06f;
				r.Fixed = true;
				return Pick(c, "spam", Lines.Spam);
			}
			if (m.Pending != Ask.None)
			{
				Ask pending = m.Pending;
				m.Pending = Ask.None;
				string text = ((u.Words.Length != 0 && (WhWords.Contains(u.Words[0]) || (u.Question && u.Words.Length > 2 && AuxWords.Contains(u.Words[0]) && (u.Words[1] == "you" || u.Words[1] == "your"))) && pending != Ask.Name) ? null : Answer(c, pending));
				if (text != null)
				{
					return text;
				}
			}
			if (u.Empty)
			{
				if (c.Greeted)
				{
					c.IsGreeting = true;
					return Greet(c);
				}
				return Pick(c, "didnt", Lines.DidntCatch);
			}
			if (u.Any(ThreatPhrases))
			{
				return Threat(c);
			}
			if (Directed(u))
			{
				return Insult(c, r);
			}
			if ((u.Any("how do i", "how do you", "how to", "teach me", "show me how", "recipe for", "recipe") && u.Any("make", "cook", "grow", "brew", "mix", "produce", "synthesize", "craft", "build", "recipe", "manufacture") && (HasProduct(u) || u.Any("bomb", "explosive", "explosives", "gun", "guns", "weapon", "poison", "silencer"))) || u.Any("recipe for meth", "how to cook meth"))
			{
				r.Fixed = true;
				return Pick(c, "howto", Lines.HowTo);
			}
			if (u.Any("are you real", "are you a robot", "are you an ai", "are you human", "is this a game", "npc", "npcs", "simulation", "are you a bot", "chatgpt", "artificial intelligence", "video game", "are you alive"))
			{
				r.Fixed = true;
				return Pick(c, "meta", Lines.Meta);
			}
			string text2 = ToldName(c);
			if (text2 != null)
			{
				return Introduced(c, text2);
			}
			if (u.Words.Length == 1 && Words.FirstNames.Contains(u.Words[0]) && !u.Question && u.Raw.IndexOf(Words.Cap(u.Words[0]), StringComparison.Ordinal) >= 0)
			{
				return Introduced(c, Words.Cap(u.Words[0]));
			}
			if (u.Any("what is my name", "do you know my name", "say my name", "who am i"))
			{
				if (c.Name.Length > 0)
				{
					return Fill(c, (c.R.Next(2) == 0) ? "{name}. Did you forget your own name?" : "You're {name}. Obviously.");
				}
				return Fill(c, (c.R.Next(2) == 0) ? "You never told me your name." : "No idea. You never said.");
			}
			if (u.Any("do you remember me", "remember me", "do you know me", "know who i am", "do you recognize me", "have we met"))
			{
				return Remember(c);
			}
			if (u.Any("what is your name", "who are you", "your name", "what do they call you", "what should i call you", "do you have a name", "what is ur name", "and you are"))
			{
				return AskName(c);
			}
			if (u.StartsWith("bye", "goodbye", "see you", "see ya", "later", "take care", "peace", "farewell", "good night", "night", "catch you later", "i got to go", "got to go", "i have to go", "i am leaving", "i am out", "laters", "adios") || u.Any("goodbye", "bye bye", "see you later", "see you around", "catch you later", "i got to go", "i have to go", "talk to you later"))
			{
				r.Ends = true;
				return Bye(c);
			}
			if (u.Any("thanks", "thank you", "appreciate it", "appreciate you", "cheers", "much appreciated"))
			{
				return Thanks(c);
			}
			if (u.Any("sorry", "my bad", "apologize", "apologies", "forgive me", "i did not mean"))
			{
				return Sorry(c);
			}
			if (u.Any("do you like me", "do you hate me", "are we friends", "am i your friend", "do you trust me", "what do you think of me", "what do you think about me", "how do you feel about me", "you like me"))
			{
				return LikesYou(c);
			}
			if (u.Any("you are cute", "you are hot", "you are sexy", "you are gorgeous", "you look cute", "you look hot", "you look sexy", "go out with me", "date me", "on a date", "kiss me", "kiss you", "marry me", "are you single", "your number", "i love you", "be my girlfriend", "be my boyfriend", "girlfriend", "boyfriend", "want to date", "i like you", "you are beautiful", "you are handsome", "you are pretty", "you are fine", "come home with me"))
			{
				return Flirt(c);
			}
			if (u.Any("you look nice", "you look good", "you look great", "you look amazing", "you look cool", "you look sharp", "nice shirt", "n