Decompiled source of Nivalis Better Time v2.2.3

BepInEx/plugins/NivalisSlowDays/NivalisSlowDays.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.CompilerServices;
using HarmonyLib;
using Hvizeu.NivalisMods;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Il2CppSystem.Threading;
using Microsoft.CodeAnalysis;
using Nivalis;
using Nivalis.Dialogue;
using Nivalis.GhostSystem;
using Nivalis.GhostSystem.Ai;
using Nivalis.GhostSystem.CustomerLoop;
using Nivalis.Localization;
using Nivalis.Player;
using Nivalis.UI.CharacterEditor;
using Nivalis.UI.Concrete;
using Nivalis.UI.InGameMenu;
using Nivalis.Utility;
using NivalisCompatibility;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.UI;
using UnityEngine.InputSystem.Users;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyMetadata("Nivalis.Requirements.Schema", "1")]
[assembly: AssemblyMetadata("Nivalis.NativeBuild", "F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A")]
[assembly: AssemblyMetadata("Nivalis.MetadataBuild", "61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA")]
[assembly: AssemblyMetadata("Nivalis.BindingRequirements", "compiled-member-references;Assembly-CSharp:Nivalis.SerializationManager.Load(System.String);Assembly-CSharp:Nivalis.SerializationManager.Save(System.String,System.Boolean)")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Hvizeu")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Configurable time and curfew-aware waiting for Nivalis Nights.")]
[assembly: AssemblyFileVersion("2.2.3.0")]
[assembly: AssemblyInformationalVersion("2.2.3")]
[assembly: AssemblyProduct("NivalisSlowDays")]
[assembly: AssemblyTitle("NivalisSlowDays")]
[assembly: AssemblyMetadata("Nivalis.Capabilities", "native-clock-v1;optional-greenhouse-v1")]
[assembly: AssemblyVersion("2.2.3.0")]
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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace NivalisCompatibility
{
	internal static class NativeCompatibility
	{
		internal const string SupportedHash = "F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A";

		internal const string SupportedMetadata = "61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA";

		internal static bool Check(string game, Action<string> error, bool verifyNative = true)
		{
			try
			{
				if (!Environment.Is64BitProcess)
				{
					throw new NotSupportedException("Windows x64 IL2CPP is required.");
				}
				if (verifyNative)
				{
					using FileStream inputStream = File.OpenRead(Path.Combine(game, "GameAssembly.dll"));
					using SHA256 sHA = SHA256.Create();
					string text = Convert.ToHexString(sHA.ComputeHash(inputStream));
					if (text != "F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A")
					{
						throw new NotSupportedException("Unsupported GameAssembly: expected F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A, observed " + text);
					}
					using FileStream inputStream2 = File.OpenRead(Path.Combine(game, "Nivalis Nights_Data", "il2cpp_data", "Metadata", "global-metadata.dat"));
					string text2 = Convert.ToHexString(sHA.ComputeHash(inputStream2));
					if (text2 != "61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA")
					{
						throw new NotSupportedException("Unsupported IL2CPP metadata: expected 61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA, observed " + text2);
					}
				}
				Type type = (AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "Assembly-CSharp") ?? Assembly.Load("Assembly-CSharp")).GetType("Nivalis.SerializationManager", throwOnError: true);
				if (type.GetMethod("Load", new Type[1] { typeof(string) }) == null || type.GetMethod("Save", new Type[2]
				{
					typeof(string),
					typeof(bool)
				}) == null)
				{
					throw new MissingMethodException("Generated bindings do not provide the required native save/load contract. Refresh bindings before retrying.");
				}
				return true;
			}
			catch (Exception ex)
			{
				error("Compatibility validation failed before activation: " + ex);
				return false;
			}
		}
	}
	internal sealed class FeatureHooks
	{
		private readonly string owner;

		private readonly Action<string, Exception> report;

		private readonly List<Harmony> installed = new List<Harmony>();

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

		internal static bool Available(string owner, string root)
		{
			return !disabled.Contains(owner + "/" + root);
		}

		internal FeatureHooks(string owner, Action<string, Exception> report)
		{
			this.owner = owner;
			this.report = report;
		}

		internal void Install(Assembly assembly, IReadOnlySet<string> optionalRoots)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			foreach (IGrouping<Type, Type> item in (from t in assembly.GetTypes()
				where t.IsDefined(typeof(HarmonyPatch), inherit: false)
				select t).GroupBy(Root))
			{
				if (disabled.Contains(owner + "/" + item.Key.Name))
				{
					continue;
				}
				Harmony val = new Harmony(optionalRoots.Contains(item.Key.Name) ? (owner + ".feature." + item.Key.Name) : owner);
				installed.Add(val);
				try
				{
					foreach (Type item2 in item)
					{
						val.CreateClassProcessor(item2).Patch();
					}
				}
				catch (Exception ex)
				{
					disabled.Add(owner + "/" + item.Key.Name);
					try
					{
						val.UnpatchSelf();
						installed.Remove(val);
					}
					catch (Exception ex2)
					{
						throw new AggregateException("Feature hook rollback unresolved: " + item.Key.Name, ex, ex2);
					}
					if (!optionalRoots.Contains(item.Key.Name))
					{
						throw;
					}
					report(item.Key.Name + " disabled before activation for this session", ex);
				}
			}
		}

		private static Type Root(Type type)
		{
			while (type.DeclaringType != null)
			{
				type = type.DeclaringType;
			}
			return type;
		}

		internal void Stop()
		{
			List<Exception> list = new List<Exception>();
			Harmony[] array = installed.ToArray();
			foreach (Harmony val in array)
			{
				try
				{
					val.UnpatchSelf();
					installed.Remove(val);
				}
				catch (Exception item)
				{
					list.Add(item);
				}
			}
			if (list.Count != 0)
			{
				throw new AggregateException("Feature hook cleanup remains pending.", list);
			}
		}
	}
}
namespace Hvizeu.NivalisMods
{
	internal static class CharacterClearance
	{
		internal static void Volume(Character character, out Vector3 lower, out Vector3 upper, out float radius)
		{
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: 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_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: 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)
			Collider collide = character.Collide;
			CapsuleCollider val = ((collide != null) ? ((Il2CppObjectBase)collide).TryCast<CapsuleCollider>() : null);
			Vector3 val2;
			float num;
			if ((Object)(object)val != (Object)null && val.direction == 1)
			{
				Vector3 lossyScale = ((Component)val).transform.lossyScale;
				val2 = ((Component)val).transform.TransformPoint(val.center);
				radius = val.radius * Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.z));
				num = val.height * Mathf.Abs(lossyScale.y);
			}
			else
			{
				if ((Object)(object)collide != (Object)null && collide.enabled)
				{
					Bounds bounds = collide.bounds;
					Vector3 size = ((Bounds)(ref bounds)).size;
					if (((Vector3)(ref size)).sqrMagnitude > 0.01f)
					{
						Bounds bounds2 = collide.bounds;
						val2 = ((Bounds)(ref bounds2)).center;
						radius = Mathf.Max(((Bounds)(ref bounds2)).extents.x, ((Bounds)(ref bounds2)).extents.z);
						num = ((Bounds)(ref bounds2)).size.y;
						goto IL_013a;
					}
				}
				NavMeshAgent agent = character.Movement.Agent;
				radius = agent.radius;
				num = agent.height;
				val2 = ((BaseCharacter)character).ThisTransform.position + Vector3.up * (num * 0.5f + agent.baseOffset);
			}
			goto IL_013a;
			IL_013a:
			radius = Mathf.Max(0.1f, radius);
			float num2 = Mathf.Max(0f, num * 0.5f - radius);
			lower = val2 - Vector3.up * num2;
			upper = val2 + Vector3.up * num2;
		}

		internal static bool Blocks(Character character, Collider collider)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Character componentInParent = ((Component)collider).GetComponentInParent<Character>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return ((Il2CppObjectBase)componentInParent).Pointer != ((Il2CppObjectBase)character).Pointer;
			}
			Collider collide = character.Collide;
			if ((Object)(object)collide == (Object)null)
			{
				return true;
			}
			int layer = ((Component)collider).gameObject.layer;
			if (Singleton<CharacterManager>.InstanceExist() && (LayerMask.op_Implicit(Singleton<CharacterManager>.Instance.EnvironmentLayer) & (1 << layer)) != 0)
			{
				return true;
			}
			return !Physics.GetIgnoreLayerCollision(((Component)collide).gameObject.layer, layer);
		}
	}
}
namespace NivalisSlowDays
{
	internal static class BindingJson
	{
		internal const string WaitId = "495c85ec-ebbd-47ae-8b9c-91a662d095eb";

		internal const string WaitGamepadId = "73a613ea-91c5-4aac-af1c-ff77e2968d34";

		internal static string WithoutWait(string json)
		{
			if (string.IsNullOrEmpty(json))
			{
				return json;
			}
			using (JsonDocument jsonDocument = JsonDocument.Parse(json))
			{
				JsonElement rootElement = jsonDocument.RootElement;
				if (!rootElement.TryGetProperty("bindings", out var value) || value.ValueKind != JsonValueKind.Array)
				{
					return json;
				}
				if (!value.EnumerateArray().Any(IsWait))
				{
					return json;
				}
				using MemoryStream memoryStream = new MemoryStream();
				using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter((Stream)memoryStream, default(JsonWriterOptions)))
				{
					utf8JsonWriter.WriteStartObject();
					foreach (JsonProperty item in rootElement.EnumerateObject())
					{
						if (item.Name != "bindings")
						{
							item.WriteTo(utf8JsonWriter);
							continue;
						}
						utf8JsonWriter.WriteStartArray("bindings");
						foreach (JsonElement item2 in value.EnumerateArray())
						{
							if (!IsWait(item2))
							{
								item2.WriteTo(utf8JsonWriter);
							}
						}
						utf8JsonWriter.WriteEndArray();
					}
					utf8JsonWriter.WriteEndObject();
				}
				return Encoding.UTF8.GetString(memoryStream.ToArray());
			}
			static bool IsWait(JsonElement entry)
			{
				if (entry.ValueKind == JsonValueKind.Object && entry.TryGetProperty("id", out var value2) && value2.ValueKind == JsonValueKind.String)
				{
					if (!string.Equals(value2.GetString(), "495c85ec-ebbd-47ae-8b9c-91a662d095eb", StringComparison.OrdinalIgnoreCase))
					{
						return string.Equals(value2.GetString(), "73a613ea-91c5-4aac-af1c-ff77e2968d34", StringComparison.OrdinalIgnoreCase);
					}
					return true;
				}
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(VisitVenueAgentActionType), "MeetsRequirements")]
	internal static class CustomerArrivalPatch
	{
		private static void Postfix(ref bool __result)
		{
			if (__result && Plugin.BalanceArrivals.Value)
			{
				__result = CustomerArrivalPolicy.Admit(Plugin.Rate.Value, WaitFaults.Active);
			}
		}
	}
	internal static class CustomerArrivalPolicy
	{
		internal static bool Admit(float rate, bool explicitWait)
		{
			if (!float.IsFinite(rate))
			{
				rate = 1f;
			}
			rate = Math.Clamp(rate, 0f, 2f);
			return rate > 0f || explicitWait;
		}
	}
	internal static class GreenhouseOwnership
	{
		private static readonly GreenhouseWorkerOwnership owner = new GreenhouseWorkerOwnership(FindPeer, HashFile, delegate(string message, Exception error)
		{
			Plugin.ModLog.LogError((object)(message + " " + error));
		}, delegate(AgentGhost agent)
		{
			Person person = agent.Person;
			return (person == null) ? null : person.Guid;
		}, (AgentGhost agent) => ((Ghost)agent).Id);

		internal static string? BlockReason => owner.BlockReason;

		private static GreenhousePeer? FindPeer()
		{
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("nivalis.greenhouse", out var value))
			{
				return null;
			}
			Assembly assembly = value.Instance?.GetType().Assembly ?? throw new InvalidOperationException("Installed greenhouse plugin has no initialized instance.");
			return new GreenhousePeer(assembly, ((object)value.Metadata.Version).ToString(), assembly.Location);
		}

		private static string HashFile(string path)
		{
			using FileStream inputStream = File.OpenRead(path);
			using SHA256 sHA = SHA256.Create();
			return Convert.ToHexString(sHA.ComputeHash(inputStream));
		}

		internal static bool OwnsView(Agent agent)
		{
			return owner.OwnsView(agent);
		}

		internal static void Begin()
		{
			owner.Begin();
		}

		internal static void End()
		{
			owner.End();
		}

		internal static GreenhouseWorkerOwnership.SyncLease NativeSync()
		{
			return owner.NativeSync();
		}

		internal static bool SuppressSync(Agent agent)
		{
			return owner.SuppressSync(agent);
		}
	}
	internal sealed record GreenhousePeer(Assembly Assembly, string Version, string Location);
	internal sealed class GreenhouseWorkerContract
	{
		internal const string PluginId = "nivalis.greenhouse";

		internal const string Version = "1.0.11";

		internal const string BinaryHash = "19FD21C339A996093FC90C2B4E3C9D1A4C7D5A1C339CA0D72EEC346B29FA3CDF";

		private readonly IList hires;

		private readonly FieldInfo person;

		private readonly Func<AgentGhost, object?> jobOf;

		private GreenhouseWorkerContract(IList hires, FieldInfo person, Func<AgentGhost, object?> jobOf)
		{
			this.hires = hires;
			this.person = person;
			this.jobOf = jobOf;
		}

		internal static GreenhouseWorkerContract Bind(GreenhousePeer peer, string hash)
		{
			if (peer.Version != "1.0.11" || !StringComparer.OrdinalIgnoreCase.Equals(hash, "19FD21C339A996093FC90C2B4E3C9D1A4C7D5A1C339CA0D72EEC346B29FA3CDF"))
			{
				throw new InvalidDataException($"Unsupported Nivalis Greenhouse {peer.Version}; binary SHA256={hash}.");
			}
			Assembly assembly = peer.Assembly;
			if (assembly.GetName().Name != "NivalisGreenhouse")
			{
				throw new InvalidDataException("Unexpected greenhouse assembly identity.");
			}
			Type type = assembly.GetType("NivalisGreenhouse.Plugin", throwOnError: true);
			if (!(type.GetField("Guid", BindingFlags.Static | BindingFlags.Public)?.GetRawConstantValue() is string text) || text != "nivalis.greenhouse" || !(type.GetField("Version", BindingFlags.Static | BindingFlags.Public)?.GetRawConstantValue() is string text2) || text2 != "1.0.11")
			{
				throw new MissingFieldException("NivalisGreenhouse.Plugin identity constants do not match.");
			}
			Type type2 = assembly.GetType("NivalisGreenhouse.Hire", throwOnError: true);
			FieldInfo field = assembly.GetType("NivalisGreenhouse.Staff", throwOnError: true).GetField("Hires", BindingFlags.Static | BindingFlags.Public);
			FieldInfo field2 = type2.GetField("<Person>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
			if (type2.IsValueType || field == null || !field.IsInitOnly || field.FieldType != typeof(List<>).MakeGenericType(type2) || field2?.FieldType != typeof(string) || type2.GetProperty("Person")?.PropertyType != typeof(string))
			{
				throw new MissingFieldException("NivalisGreenhouse.Staff.Hires/Hire.Person ownership fields do not match.");
			}
			Type? type3 = assembly.GetType("NivalisGreenhouse.Tend", throwOnError: true);
			Type nestedType = type3.GetNestedType("Job", BindingFlags.NonPublic);
			MethodInfo method = type3.GetMethod("JobOf", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(AgentGhost) }, null);
			if (nestedType == null || nestedType.IsValueType || nestedType.GetField("Agent")?.FieldType != typeof(AgentGhost) || nestedType.GetField("Leaving")?.FieldType != typeof(bool) || method == null || method.IsGenericMethod || method.ReturnType != nestedType)
			{
				throw new MissingMethodException("NivalisGreenhouse.Tend.JobOf(AgentGhost) ownership signature does not match.");
			}
			IList obj = (field.GetValue(null) as IList) ?? throw new InvalidDataException("Greenhouse workforce is unavailable.");
			Func<AgentGhost, object> func = (Func<AgentGhost, object>)method.CreateDelegate(typeof(Func<AgentGhost, object>));
			GreenhouseWorkerContract greenhouseWorkerContract = new GreenhouseWorkerContract(obj, field2, func);
			greenhouseWorkerContract.CopyRoster(new HashSet<string>(StringComparer.Ordinal));
			return greenhouseWorkerContract;
		}

		private string PersonAt(int index)
		{
			object obj = hires[index];
			if (obj == null || !(person.GetValue(obj) is string { Length: not 0 } text))
			{
				throw new InvalidDataException($"Greenhouse workforce entry {index} has no person identity.");
			}
			return text;
		}

		internal void CopyRoster(HashSet<string> destination)
		{
			for (int i = 0; i < hires.Count; i++)
			{
				destination.Add(PersonAt(i));
			}
		}

		internal bool Owns(AgentGhost agent, string? personId)
		{
			if (jobOf(agent) != null)
			{
				return true;
			}
			if (personId == null)
			{
				return false;
			}
			for (int i = 0; i < hires.Count; i++)
			{
				if (PersonAt(i) == personId)
				{
					return true;
				}
			}
			return false;
		}
	}
	internal sealed class GreenhouseWorkerOwnership
	{
		internal readonly struct SyncLease : IDisposable
		{
			private readonly GreenhouseWorkerOwnership owner;

			private readonly int previous;

			internal SyncLease(GreenhouseWorkerOwnership owner)
			{
				this.owner = owner;
				previous = owner.syncDepth;
				owner.syncDepth++;
			}

			public void Dispose()
			{
				owner.syncDepth = previous;
			}
		}

		private readonly Func<GreenhousePeer?> discover;

		private readonly Func<string, string> hashFile;

		private readonly Action<string, Exception> report;

		private readonly Func<AgentGhost, string?> personId;

		private readonly Func<AgentGhost, string> ghostId;

		private GreenhousePeer? resolved;

		private GreenhouseWorkerContract? contract;

		private readonly HashSet<string> retainedPeople = new HashSet<string>(StringComparer.Ordinal);

		private readonly HashSet<string> retainedGhosts = new HashSet<string>(StringComparer.Ordinal);

		private readonly HashSet<string> checkedRoster = new HashSet<string>(StringComparer.Ordinal);

		private readonly Dictionary<nint, string> retainedViews = new Dictionary<IntPtr, string>();

		private bool active;

		private int syncDepth;

		private string? problem;

		internal Exception? Failure { get; private set; }

		internal string? BlockReason
		{
			get
			{
				Resolve();
				if (problem == null && contract != null)
				{
					try
					{
						checkedRoster.Clear();
						contract.CopyRoster(checkedRoster);
					}
					catch (Exception error)
					{
						Fail(error);
					}
				}
				return problem;
			}
		}

		internal GreenhouseWorkerOwnership(Func<GreenhousePeer?> discover, Func<string, string> hashFile, Action<string, Exception> report, Func<AgentGhost, string?> personId, Func<AgentGhost, string> ghostId)
		{
			this.discover = discover;
			this.hashFile = hashFile;
			this.report = report;
			this.personId = personId;
			this.ghostId = ghostId;
		}

		private void Fail(Exception error)
		{
			if (Failure == null)
			{
				Failure = error;
				contract = null;
				problem = "Waiting is unavailable: Nivalis Greenhouse " + (resolved?.Version ?? "ownership") + " could not be verified. Normal gameplay and clock settings remain available; check the log.";
				report(problem, error);
			}
		}

		private void Resolve()
		{
			try
			{
				GreenhousePeer greenhousePeer = discover();
				if (greenhousePeer == null)
				{
					resolved = null;
					contract = null;
					problem = null;
					Failure = null;
				}
				else if (!(resolved == greenhousePeer))
				{
					resolved = greenhousePeer;
					contract = null;
					problem = null;
					Failure = null;
					GreenhouseWorkerContract greenhouseWorkerContract = GreenhouseWorkerContract.Bind(greenhousePeer, hashFile(greenhousePeer.Location));
					contract = greenhouseWorkerContract;
				}
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		internal void Begin()
		{
			string blockReason = BlockReason;
			if (blockReason != null)
			{
				throw new InvalidOperationException(blockReason, Failure);
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			try
			{
				contract?.CopyRoster(hashSet);
			}
			catch (Exception ex)
			{
				Fail(ex);
				throw new InvalidOperationException(problem, ex);
			}
			retainedPeople.Clear();
			retainedPeople.UnionWith(hashSet);
			retainedGhosts.Clear();
			retainedViews.Clear();
			active = true;
		}

		internal bool OwnsView(Agent agent)
		{
			try
			{
				AgentGhost myGhost = ((GhostView<AgentGhost>)(object)agent).MyGhost;
				if (myGhost == null)
				{
					return active && retainedViews.ContainsKey(((Il2CppObjectBase)agent).Pointer);
				}
				if (active && retainedViews.TryGetValue(((Il2CppObjectBase)agent).Pointer, out string value))
				{
					if (ghostId(myGhost) == value)
					{
						return true;
					}
					retainedViews.Remove(((Il2CppObjectBase)agent).Pointer);
				}
				bool num = OwnsGhost(myGhost);
				if (num && active)
				{
					retainedViews[((Il2CppObjectBase)agent).Pointer] = ghostId(myGhost);
				}
				return num;
			}
			catch (Exception error)
			{
				Fail(error);
				throw new InvalidOperationException(problem, Failure);
			}
		}

		internal bool OwnsGhost(AgentGhost agent)
		{
			if (!active)
			{
				Resolve();
			}
			if (contract == null && problem == null && retainedPeople.Count == 0 && retainedGhosts.Count == 0)
			{
				return false;
			}
			try
			{
				string item = ghostId(agent);
				if (active && retainedGhosts.Contains(item))
				{
					return true;
				}
				string text = personId(agent);
				if (active && text != null && retainedPeople.Contains(text))
				{
					retainedGhosts.Add(item);
					return true;
				}
				if (problem != null)
				{
					throw new InvalidOperationException(problem, Failure);
				}
				GreenhouseWorkerContract? greenhouseWorkerContract = contract;
				int num;
				if (greenhouseWorkerContract == null)
				{
					num = 0;
				}
				else
				{
					num = (greenhouseWorkerContract.Owns(agent, text) ? 1 : 0);
					if (num != 0 && active)
					{
						retainedGhosts.Add(item);
						if (text != null)
						{
							retainedPeople.Add(text);
						}
					}
				}
				return (byte)num != 0;
			}
			catch (Exception error)
			{
				Fail(error);
				throw new InvalidOperationException(problem, Failure);
			}
		}

		internal void End()
		{
			active = false;
			retainedPeople.Clear();
			retainedGhosts.Clear();
			retainedViews.Clear();
			syncDepth = 0;
		}

		internal SyncLease NativeSync()
		{
			string blockReason = BlockReason;
			if (blockReason != null)
			{
				throw new InvalidOperationException(blockReason, Failure);
			}
			return new SyncLease(this);
		}

		internal bool SuppressSync(Agent agent)
		{
			if (syncDepth != 0)
			{
				return OwnsView(agent);
			}
			return false;
		}
	}
	internal static class HourlyWork
	{
		[HarmonyPatch(typeof(VenueManager), "OnDestroyInternal")]
		private static class OwnerRetirement
		{
			private static void Prefix(VenueManager __instance)
			{
				Retiring(__instance);
			}
		}

		private static UniTask task = null;

		private static VenueManager? owner;

		private static int queued;

		private static bool ownerLeaving;

		private static Stopwatch? acceleratedTime;

		internal static bool Pending { get; private set; }

		internal static bool NeedsUnpausedDrain { get; private set; }

		internal static int FaultSequence { get; private set; }

		internal static string ProgressText { get; private set; } = "Updating venues for the new hour...";

		internal static void Retiring(VenueManager venue)
		{
			if (Pending)
			{
				VenueManager? obj = owner;
				if (((obj != null) ? new IntPtr?(((Il2CppObjectBase)obj).Pointer) : ((IntPtr?)null)) == ((Il2CppObjectBase)venue).Pointer)
				{
					ownerLeaving = true;
				}
			}
		}

		internal static bool Start(VenueManager venue)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00c0: Expected O, but got Unknown
			if ((Object)(object)TimeController.Current == (Object)null)
			{
				return false;
			}
			if (Pending)
			{
				if ((Object)(object)owner != (Object)null && ((Il2CppObjectBase)owner).Pointer == ((Il2CppObjectBase)venue).Pointer)
				{
					queued++;
					return true;
				}
				return false;
			}
			if (TimeController.Current.Busy)
			{
				try
				{
					WaitVenueHour.Run(venue);
				}
				catch (Exception ex)
				{
					FaultSequence++;
					ManualLogSource modLog = Plugin.ModLog;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(35, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Native venue catch-up hour failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					modLog.LogError(val);
				}
				return true;
			}
			owner = venue;
			ownerLeaving = false;
			if (venue.onDestroyCancelToken == null)
			{
				CancellationTokenSource val2 = new CancellationTokenSource();
				CancellationTokenSource val3 = val2;
				venue.onDestroyCancelToken = val2;
			}
			task = venue.HourlyUpdateTask(venue.onDestroyCancelToken.Token);
			Pending = true;
			ProgressText = "Updating venues for the new hour...";
			acceleratedTime = null;
			return true;
		}

		internal static void Poll()
		{
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Invalid comparison between Unknown and I4
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			if (!Pending)
			{
				return;
			}
			UniTaskStatus status;
			bool flag = default(bool);
			try
			{
				status = task.Status;
				if ((int)status == 0)
				{
					if (!NeedsUnpausedDrain)
					{
						TimeController? current = TimeController.Current;
						if (current != null && current.Busy)
						{
							ExpediteOwnedDelay();
						}
					}
					return;
				}
			}
			catch (Exception ex)
			{
				if (!NeedsUnpausedDrain)
				{
					NeedsUnpausedDrain = true;
					FaultSequence++;
					ManualLogSource modLog = Plugin.ModLog;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(91, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cannot accelerate the active venue hour. Returning to gameplay to drain its original task: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					modLog.LogError(val);
				}
				return;
			}
			Pending = false;
			NeedsUnpausedDrain = false;
			try
			{
				task.GetAwaiter().GetResult();
				if (acceleratedTime != null)
				{
					ManualLogSource modLog2 = Plugin.ModLog;
					BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(55, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Venue hour completed after ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<double>(acceleratedTime.Elapsed.TotalSeconds, "0.00");
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("s of wait catch-up; venues=");
						VenueManager? obj = owner;
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int?>((obj != null) ? new int?(obj._venueGhosts.Count) : ((int?)null));
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(".");
					}
					modLog2.LogInfo(val2);
				}
				task = null;
				while (queued > 0 && (Object)(object)owner != (Object)null && !Pending)
				{
					queued--;
					Start(owner);
				}
			}
			catch (Exception ex2)
			{
				queued = 0;
				if ((int)status == 3 && ownerLeaving)
				{
					Plugin.ModLog.LogDebug((object)"Venue hourly update cancelled during its owner's teardown.");
					return;
				}
				FaultSequence++;
				ManualLogSource modLog3 = Plugin.ModLog;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(35, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Native venue hourly update failed: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex2);
				}
				modLog3.LogError(val);
			}
			finally
			{
				if (!Pending)
				{
					owner = null;
					task = null;
					acceleratedTime = null;
				}
			}
		}

		private static void ExpediteOwnedDelay()
		{
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			IUniTaskSource source = task.source;
			_HourlyUpdateTask_d__49 val = NativeHourState.Read(((source != null) ? ((Il2CppObjectBase)source).TryCast<AsyncUniTask<_HourlyUpdateTask_d__49>>() : null) ?? throw new InvalidOperationException("Unknown native venue-hour task runner; cannot safely remove its paused delay."));
			if ((Object)(object)owner == (Object)null || ((Il2CppObjectBase)val.__4__this).Pointer != ((Il2CppObjectBase)owner).Pointer || val.__1__state != 0)
			{
				throw new InvalidOperationException($"Native venue-hour await state or owner does not match: state={val.__1__state}, ownerMatches={(Object)(object)owner != (Object)null && ((Il2CppObjectBase)val.__4__this).Pointer == ((Il2CppObjectBase)owner).Pointer}.");
			}
			UniTask val2 = val.__u__1.task;
			if ((int)val2.Status == 0)
			{
				IUniTaskSource source2 = val2.source;
				DelayPromise obj = ((source2 != null) ? ((Il2CppObjectBase)source2).TryCast<DelayPromise>() : null) ?? throw new InvalidOperationException("Venue hour is awaiting an unexpected task instead of its pacing delay.");
				if (acceleratedTime == null)
				{
					acceleratedTime = Stopwatch.StartNew();
				}
				obj.delayTimeSpan = 0f;
				ProgressText = $"Updating venues {val._i_5__2 + 1}/{owner._venueGhosts.Count}...";
			}
		}
	}
	internal static class NativeHourState
	{
		private static readonly IntPtr field = IL2CPP.il2cpp_class_get_field_from_name(Il2CppClassPointerStore<AsyncUniTask<_HourlyUpdateTask_d__49>>.NativeClassPtr, "stateMachine");

		internal static _HourlyUpdateTask_d__49 Read(AsyncUniTask<_HourlyUpdateTask_d__49> runner)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			if (field == IntPtr.Zero)
			{
				throw new MissingFieldException("Native venue-hour stateMachine field was not found.");
			}
			IntPtr intPtr = IL2CPP.il2cpp_field_get_value_object(field, ((Il2CppObjectBase)runner).Pointer);
			if (intPtr == IntPtr.Zero)
			{
				throw new InvalidOperationException("Native venue-hour state could not be read.");
			}
			return new _HourlyUpdateTask_d__49(intPtr);
		}
	}
	internal static class NativeSettings
	{
		private sealed class RowCheck
		{
			internal GameObject Source;

			internal GameObject Row;

			internal int RowId;

			internal int VisibleFrame = -1;

			internal bool Reported;
		}

		private const string RateName = "HvizeuClockRate";

		private const string WaitName = "Hvizeu.Wait";

		private static InputAction? action;

		private static bool inputReady;

		private static Exception? inputFailure;

		private static readonly List<ControlsSettingsUI> pendingControls = new List<ControlsSettingsUI>();

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

		private static InputActionReference? reference;

		private static InputActionAsset? owner;

		private static LocObjRef<LocStringSingle>? waitText;

		private static readonly WaitShortcut controls = new WaitShortcut(delegate(string message, Exception ex)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			ManualLogSource modLog = Plugin.ModLog;
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("\n");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
			}
			modLog.LogError(val);
		});

		private static bool refreshBindingDisplays;

		private static Action<InputDevice, InputDeviceChange>? deviceChanged;

		private static Action? bindingChanged;

		private static WaitInputSubscriptions? inputSubscriptions;

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

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

		private static readonly List<RowCheck> layoutChecks = new List<RowCheck>();

		private static InputAction? rollbackAction;

		private static InputActionReference? rollbackReference;

		internal static string InputStatus
		{
			get
			{
				if (!inputReady)
				{
					if (inputFailure != null)
					{
						return "Failed: " + inputFailure.Message;
					}
					return "Pending";
				}
				return "Ready";
			}
		}

		internal static bool Pressed
		{
			get
			{
				if (inputReady && action != null)
				{
					WaitInputSubscriptions? waitInputSubscriptions = inputSubscriptions;
					if (waitInputSubscriptions != null && waitInputSubscriptions.Active)
					{
						return controls.PollBindings(action);
					}
				}
				return false;
			}
		}

		private static void WatchDevices()
		{
			if (inputSubscriptions == null)
			{
				deviceChanged = Action<InputDevice, InputDeviceChange>.op_Implicit((Action<InputDevice, InputDeviceChange>)delegate
				{
					controls.Clear();
					refreshBindingDisplays = true;
				});
				bindingChanged = Action.op_Implicit((Action)controls.Clear);
				inputSubscriptions = new WaitInputSubscriptions(delegate
				{
					InputSystem.onDeviceChange += deviceChanged;
				}, delegate
				{
					InputSystem.onDeviceChange -= deviceChanged;
				}, delegate
				{
					PlayerInputManager.OnRebindComplete += bindingChanged;
				}, delegate
				{
					PlayerInputManager.OnRebindComplete -= bindingChanged;
				}, delegate
				{
					PlayerInputManager.OnRebindCanceled += bindingChanged;
				}, delegate
				{
					PlayerInputManager.OnRebindCanceled -= bindingChanged;
				});
			}
			inputSubscriptions.Start();
		}

		internal static void RestoreBinding()
		{
			controls.Clear();
			if (action != null)
			{
				InputActionRebindingExtensions.ApplyBindingOverride(action, 0, Plugin.BindingPath.Value);
				InputActionRebindingExtensions.ApplyBindingOverride(action, 1, Plugin.GamepadBindingPath.Value);
			}
		}

		internal static void SaveBinding()
		{
			if (action != null)
			{
				controls.RefreshBindings(action);
				string text = controls.BindingPath(action, 0);
				string text2 = controls.BindingPath(action, 1);
				if (!(text == Plugin.BindingPath.Value) || !(text2 == Plugin.GamepadBindingPath.Value))
				{
					Plugin.BindingPath.Value = text;
					Plugin.GamepadBindingPath.Value = text2;
					((ConfigEntryBase)Plugin.BindingPath).ConfigFile.Save();
				}
			}
		}

		internal static void Attach(GameplaySettingsUI settings)
		{
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Expected O, but got Unknown
			if ((Object)(object)((Component)settings).transform.parent.Find("Hvizeu.ModsOptions") != (Object)null)
			{
				Transform previous = ((Transform)settings.scroll.content).Find("HvizeuClockRate");
				if ((Object)(object)previous != (Object)null)
				{
					int id = ((Object)((Component)previous).gameObject).GetInstanceID();
					((SettingsTabPanel)settings)._elements = Il2CppReferenceArray<SettingUIElementBase>.op_Implicit(((IEnumerable<SettingUIElementBase>)((SettingsTabPanel)settings)._elements).Where((SettingUIElementBase e) => (Object)(object)e != (Object)null && (Object)(object)((Component)e).gameObject != (Object)(object)((Component)previous).gameObject).ToArray());
					if (canvasOwners.Remove(id, out CanvasBehaviourManager value) && (Object)(object)value != (Object)null)
					{
						CanvasBehaviourManager.UnregisterRuntimeChildren(previous, value);
					}
					rows.RemoveAll((GameObject r) => (Object)(object)r == (Object)null || (Object)(object)r == (Object)(object)((Component)previous).gameObject);
					layoutChecks.RemoveAll((RowCheck r) => r.RowId == id);
					((Component)previous).gameObject.SetActive(false);
					Object.Destroy((Object)(object)((Component)previous).gameObject);
					settings.UpdateManualUINavigation();
				}
			}
			else
			{
				if ((Object)(object)((Transform)settings.scroll.content).Find("HvizeuClockRate") != (Object)null)
				{
					return;
				}
				SettingsCategory category = ((SettingsTabPanel)settings)._category;
				category.DefaultSettings["HvizeuClockRate"] = "0.3";
				category._settings["HvizeuClockRate"] = Plugin.Rate.Value.ToString("R", CultureInfo.InvariantCulture);
				GameObject val = new GameObject("SlowDays.SettingsConstruction");
				val.SetActive(false);
				try
				{
					GameObject val2 = CloneRow(((Component)settings.mouseSensitivity).gameObject, val.transform);
					((Object)val2).name = "HvizeuClockRate";
					SliderSettingUI slider = val2.GetComponent<SliderSettingUI>();
					((SettingUIElementBase)slider).settingName = "HvizeuClockRate";
					((SettingUIElementBase)slider).OnValueChanged = null;
					((SettingUIElement<float>)(object)slider).defaultValue = 0.3f;
					slider.valueTextFormat = "F1";
					slider.slider.onValueChanged = new SliderEvent();
					slider.slider.minValue = 0f;
					slider.slider.maxValue = 2f;
					slider.slider.wholeNumbers = false;
					slider.slider.SetValueWithoutNotify(Plugin.Rate.Value);
					TextMeshProUGUI component = ((Component)val2.transform.Find("Label")).GetComponent<TextMeshProUGUI>();
					foreach (MonoBehaviour component2 in ((Component)component).GetComponents<MonoBehaviour>())
					{
						if (((MemberInfo)((Object)component2).GetIl2CppType()).Name != "TextMeshProUGUI")
						{
							((Behaviour)component2).enabled = false;
						}
					}
					((TMP_Text)component).text = "CLOCK SPEED";
					TMP_InputField precise = AddPreciseValue(slider);
					((SettingUIElementBase)slider).OnValueChanged += Action<SettingUIElementBase>.op_Implicit((Action<SettingUIElementBase>)delegate(SettingUIElementBase element)
					{
						//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
						//IL_00ab: Expected O, but got Unknown
						try
						{
							slider.slider.SetValueWithoutNotify(TimePolicy.SnapRate(((SettingUIElement<float>)(object)slider).CurrentChoice));
							slider.RefreshValueText();
							((SettingsTabPanel)settings).ApplySetting(element);
							Plugin.Rate.Value = ((SettingUIElement<float>)(object)slider).CurrentChoice;
							((ConfigEntryBase)Plugin.Rate).ConfigFile.Save();
							precise.SetTextWithoutNotify(((SettingUIElement<float>)(object)slider).CurrentChoice.ToString("F1", CultureInfo.InvariantCulture) + "x");
							((SettingsTabPanel)settings).CheckButtonsInteractability();
						}
						catch (Exception ex)
						{
							ManualLogSource modLog = Plugin.ModLog;
							bool flag = default(bool);
							BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(27, 1, ref flag);
							if (flag)
							{
								((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Unable to save clock rate: ");
								((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
							}
							modLog.LogError(val3);
						}
					});
					List<SettingUIElementBase> list = ((IEnumerable<SettingUIElementBase>)((SettingsTabPanel)settings)._elements).ToList();
					list.Add((SettingUIElementBase)(object)slider);
					((SettingsTabPanel)settings)._elements = Il2CppReferenceArray<SettingUIElementBase>.op_Implicit(list.ToArray());
					PlaceRow(val2, ((Component)settings.mouseSensitivity).gameObject);
					val2.SetActive(true);
					RegisterRow(val2);
					((TMP_Text)component).text = "CLOCK SPEED";
					slider.RefreshValueText();
					rows.Add(val2);
					settings.UpdateManualUINavigation();
					LayoutRebuilder.ForceRebuildLayoutImmediate(settings.scroll.content);
					Plugin.ModLog.LogInfo((object)"Added native Clock Speed slider to Settings > Gameplay.");
				}
				finally
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}

		internal static void Attach(ControlsSettingsUI settings)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Expected O, but got Unknown
			if ((Object)(object)((Transform)settings.scroll.content).Find("Hvizeu.Wait") != (Object)null)
			{
				return;
			}
			if (!inputReady || (Object)(object)reference == (Object)null)
			{
				if (!pendingControls.Any((ControlsSettingsUI c) => (Object)(object)c != (Object)null && ((Il2CppObjectBase)c).Pointer == ((Il2CppObjectBase)settings).Pointer))
				{
					pendingControls.Add(settings);
				}
				Transform val = ((Transform)settings.scroll.content).Find("Hvizeu.WaitStatus");
				if ((Object)(object)val == (Object)null)
				{
					GameObject val2 = new GameObject("Hvizeu.WaitStatus", (Type[])(object)new Type[2]
					{
						Il2CppType.Of<RectTransform>(),
						Il2CppType.Of<TextMeshProUGUI>()
					});
					val2.transform.SetParent((Transform)(object)settings.scroll.content, false);
					val2.GetComponent<RectTransform>().sizeDelta = new Vector2(600f, 40f);
					TextMeshProUGUI component = val2.GetComponent<TextMeshProUGUI>();
					if (settings.controls.Count > 0)
					{
						((TMP_Text)component).font = ((TMP_Text)settings.controls[0].actionText).font;
						((TMP_Text)component).fontSize = ((TMP_Text)settings.controls[0].actionText).fontSize;
					}
					RegisterRow(val2);
					inputStatusRows.Add(val2);
					val = val2.transform;
				}
				((TMP_Text)((Component)val).GetComponent<TextMeshProUGUI>()).text = ((inputFailure == null) ? "WAIT — Initializing input" : "WAIT — Input unavailable. Check the BepInEx log.");
				return;
			}
			Transform val3 = ((Transform)settings.scroll.content).Find("Hvizeu.WaitStatus");
			if ((Object)(object)val3 != (Object)null)
			{
				inputStatusRows.Remove(((Component)val3).gameObject);
				RetireInputStatus(((Component)val3).gameObject);
			}
			if (waitText == null)
			{
				ScriptableObjectSingleton<LocObjectsDB>.Instance.AddNewObjWithGuid("hvizeu.slowdays.wait-label", (LocObjPlain)new LocStringSingle
				{
					Text = "WAIT"
				});
				LocObjRef<LocStringSingle> obj = new LocObjRef<LocStringSingle>(false);
				((LocObjRef)obj).locObjGuid = "hvizeu.slowdays.wait-label";
				waitText = obj;
			}
			GameObject val4 = new GameObject("SlowDays.BindingConstruction");
			val4.SetActive(false);
			try
			{
				InputRebindUI val5 = null;
				Enumerator<InputRebindUI> enumerator = settings.controls.GetEnumerator();
				while (enumerator.MoveNext())
				{
					InputRebindUI current = enumerator.Current;
					Enumerator<InputBinding> enumerator2 = ((InputDisplayUI)current).action.actionReference.action.bindings.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						if (WaitBindingGroups.MatchesLayout(enumerator2.Current.path, "Keyboard"))
						{
							val5 = current;
							break;
						}
					}
					if ((Object)(object)val5 != (Object)null)
					{
						break;
					}
				}
				if ((Object)(object)val5 == (Object)null)
				{
					throw new InvalidOperationException("A native keyboard rebind row was not found.");
				}
				GameObject val6 = CloneRow(((Component)val5).gameObject, val4.transform);
				((Object)val6).name = "Hvizeu.Wait";
				InputRebindUI component2 = val6.GetComponent<InputRebindUI>();
				ActionDisplay val7 = new ActionDisplay();
				val7.actionReference = reference;
				val7.description = ((InputDisplayUI)val5).action.description;
				val7.displayInputText = ((InputDisplayUI)val5).action.displayInputText;
				val7.compositeIndex = Il2CppStructArray<int>.op_Implicit(new int[1]);
				((InputDisplayUI)component2).action = val7;
				component2.actionDescription = "WAIT";
				component2.locObjRef = waitText;
				component2.OnSelected = null;
				component2.OnSelected += Action<GameObject>.op_Implicit((Action<GameObject>)settings.Selected);
				PlaceRow(val6, ((Component)val5).gameObject);
				val6.SetActive(true);
				RegisterRow(val6);
				((TMP_Text)component2.actionText).text = "WAIT";
				settings.controls.Add(component2);
				settings.UpdateManualUINavigation();
				rows.Add(val6);
				LayoutRebuilder.ForceRebuildLayoutImmediate(settings.scroll.content);
				Plugin.ModLog.LogInfo((object)"Added native Wait rebinding row to Settings > Controls.");
			}
			finally
			{
				Object.Destroy((Object)(object)val4);
			}
		}

		private static GameObject CloneRow(GameObject original, Transform staging)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			GameObject val = Object.Instantiate<GameObject>(original, staging, false);
			val.SetActive(false);
			int num = RestoreCanvasBehaviours(original.transform, val.transform, original.GetComponentInParent<CanvasBehaviourManager>());
			CopyGeometry(original.transform, val.transform);
			ManualLogSource modLog = Plugin.ModLog;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(89, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Native Settings clone ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)original).name);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": restored ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" canvas-managed disabled components before registration.");
			}
			modLog.LogInfo(val2);
			return val;
		}

		private static int RestoreCanvasBehaviours(Transform source, Transform target, CanvasBehaviourManager manager)
		{
			if ((Object)(object)manager == (Object)null)
			{
				throw new InvalidOperationException("Native Settings canvas owner is missing.");
			}
			int num = 0;
			Il2CppArrayBase<Behaviour> components = ((Component)source).GetComponents<Behaviour>();
			Il2CppArrayBase<Behaviour> components2 = ((Component)target).GetComponents<Behaviour>();
			for (int i = 0; i < components.Length; i++)
			{
				if (!components[i].enabled && manager.canvasBehaviours.Contains(components[i]))
				{
					components2[i].enabled = true;
					num++;
				}
			}
			for (int j = 0; j < source.childCount; j++)
			{
				num += RestoreCanvasBehaviours(source.GetChild(j), target.GetChild(j), manager);
			}
			return num;
		}

		private static void RegisterRow(GameObject row)
		{
			CanvasBehaviourManager val = default(CanvasBehaviourManager);
			CanvasBehaviourManager.RegisterRuntimeChildren(row, ref val);
			if ((Object)(object)val == (Object)null)
			{
				throw new InvalidOperationException("Native Settings row was not registered with its canvas.");
			}
			canvasOwners[((Object)row).GetInstanceID()] = val;
		}

		private static void CopyGeometry(Transform source, Transform target)
		{
			CopyRect(((Component)source).GetComponent<RectTransform>(), ((Component)target).GetComponent<RectTransform>());
			for (int i = 0; i < source.childCount; i++)
			{
				CopyGeometry(source.GetChild(i), target.GetChild(i));
			}
		}

		private static void CopyRect(RectTransform source, RectTransform target)
		{
			//IL_0002: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			((Transform)target).localScale = ((Transform)source).localScale;
			((Transform)target).localRotation = ((Transform)source).localRotation;
			target.anchorMin = source.anchorMin;
			target.anchorMax = source.anchorMax;
			target.pivot = source.pivot;
			target.sizeDelta = source.sizeDelta;
			target.anchoredPosition3D = source.anchoredPosition3D;
		}

		private static void PlaceRow(GameObject row, GameObject original)
		{
			row.transform.SetParent(original.transform.parent, false);
			CopyRect(original.GetComponent<RectTransform>(), row.GetComponent<RectTransform>());
			layoutChecks.Add(new RowCheck
			{
				Source = original,
				Row = row,
				RowId = ((Object)row).GetInstanceID()
			});
		}

		internal static void CheckVisibleLayouts()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			RefreshPendingInputUi();
			bool flag = default(bool);
			if (refreshBindingDisplays)
			{
				refreshBindingDisplays = false;
				foreach (GameObject row in rows)
				{
					if ((Object)(object)row == (Object)null)
					{
						continue;
					}
					InputRebindUI component = row.GetComponent<InputRebindUI>();
					if ((Object)(object)component == (Object)null)
					{
						continue;
					}
					try
					{
						((InputDisplayUI)component).UpdateBindingDisplayUI();
					}
					catch (Exception ex)
					{
						ManualLogSource modLog = Plugin.ModLog;
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(63, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Unable to refresh Wait key label after an input-device change: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
						}
						modLog.LogError(val);
					}
				}
			}
			int num = 0;
			for (int num2 = layoutChecks.Count - 1; num2 >= 0; num2--)
			{
				RowCheck rowCheck = layoutChecks[num2];
				if (!((Object)(object)rowCheck.Row != (Object)null))
				{
					canvasOwners.Remove(rowCheck.RowId);
					layoutChecks.RemoveAt(num2);
					num++;
				}
			}
			for (int num3 = rows.Count - 1; num3 >= 0; num3--)
			{
				if ((Object)(object)rows[num3] == (Object)null)
				{
					rows.RemoveAt(num3);
				}
			}
			if (num > 0)
			{
				ManualLogSource modLog2 = Plugin.ModLog;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(82, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Released bookkeeping for ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" destroyed native settings row(s); ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(rows.Count);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" live row(s) retained.");
				}
				modLog2.LogInfo(val2);
			}
			foreach (RowCheck layoutCheck in layoutChecks)
			{
				if ((Object)(object)layoutCheck.Row == (Object)null || (Object)(object)layoutCheck.Source == (Object)null || !canvasOwners.TryGetValue(((Object)layoutCheck.Row).GetInstanceID(), out CanvasBehaviourManager value) || (Object)(object)value == (Object)null)
				{
					continue;
				}
				if (!layoutCheck.Row.activeInHierarchy || !value.GetCanvasIsEnabled())
				{
					layoutCheck.VisibleFrame = -1;
					layoutCheck.Reported = false;
					continue;
				}
				if (layoutCheck.Reported)
				{
					continue;
				}
				if (layoutCheck.VisibleFrame < 0)
				{
					layoutCheck.VisibleFrame = Time.frameCount;
				}
				if (Time.frameCount - layoutCheck.VisibleFrame < 5)
				{
					continue;
				}
				layoutCheck.Reported = true;
				RectTransform component2 = layoutCheck.Source.GetComponent<RectTransform>();
				RectTransform component3 = layoutCheck.Row.GetComponent<RectTransform>();
				RectTransform component4 = ((Component)((Transform)component2).GetChild(0)).GetComponent<RectTransform>();
				RectTransform component5 = ((Component)((Transform)component3).GetChild(0)).GetComponent<RectTransform>();
				Rect rect = component5.rect;
				float x = ((Transform)component5).TransformPoint(new Vector3(((Rect)(ref rect)).xMin, 0f, 0f)).x;
				rect = component4.rect;
				float x2 = ((Transform)component4).TransformPoint(new Vector3(((Rect)(ref rect)).xMin, 0f, 0f)).x;
				rect = component3.rect;
				int num4;
				if (((Rect)(ref rect)).width > 0f)
				{
					rect = component3.rect;
					float width = ((Rect)(ref rect)).width;
					rect = component2.rect;
					if (Math.Abs(width - ((Rect)(ref rect)).width) < 2f)
					{
						rect = component5.rect;
						if (((Rect)(ref rect)).width > 50f)
						{
							num4 = ((Math.Abs(x - x2) < 2f) ? 1 : 0);
							goto IL_035d;
						}
					}
				}
				num4 = 0;
				goto IL_035d;
				IL_035d:
				bool flag2 = (byte)num4 != 0;
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(75, 6);
				defaultInterpolatedStringHandler.AppendLiteral("Native Settings layout ");
				defaultInterpolatedStringHandler.AppendFormatted(((Object)layoutCheck.Row).name);
				defaultInterpolatedStringHandler.AppendLiteral(": width=");
				rect = component3.rect;
				defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).width, "0.0");
				defaultInterpolatedStringHandler.AppendLiteral(" native=");
				rect = component2.rect;
				defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).width, "0.0");
				defaultInterpolatedStringHandler.AppendLiteral(", labelWidth=");
				rect = component5.rect;
				defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).width, "0.0");
				defaultInterpolatedStringHandler.AppendLiteral(", leftDelta=");
				defaultInterpolatedStringHandler.AppendFormatted(x - x2, "0.0");
				defaultInterpolatedStringHandler.AppendLiteral(", aligned=");
				defaultInterpolatedStringHandler.AppendFormatted(flag2);
				defaultInterpolatedStringHandler.AppendLiteral(".");
				string text = defaultInterpolatedStringHandler.ToStringAndClear();
				if (flag2)
				{
					Plugin.ModLog.LogInfo((object)text);
				}
				else
				{
					Plugin.ModLog.LogError((object)text);
				}
			}
		}

		private static TMP_InputField AddPreciseValue(SliderSettingUI setting)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: 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_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI valueText = setting.valueText;
			RectTransform rectTransform = ((TMP_Text)valueText).rectTransform;
			RectTransform val = new GameObject("Exact clock rate").AddComponent<RectTransform>();
			((Transform)val).SetParent(((Transform)rectTransform).parent, false);
			((Transform)val).SetSiblingIndex(((Transform)rectTransform).GetSiblingIndex());
			val.anchorMin = rectTransform.anchorMin;
			val.anchorMax = rectTransform.anchorMax;
			val.pivot = rectTransform.pivot;
			val.sizeDelta = rectTransform.sizeDelta;
			val.anchoredPosition = rectTransform.anchoredPosition;
			LayoutElement component = ((Component)rectTransform).GetComponent<LayoutElement>();
			LayoutElement val2 = ((Component)val).gameObject.AddComponent<LayoutElement>();
			Rect rect;
			float minWidth;
			if (!((Object)(object)component != (Object)null))
			{
				rect = rectTransform.rect;
				minWidth = ((Rect)(ref rect)).width;
			}
			else
			{
				minWidth = component.minWidth;
			}
			val2.minWidth = minWidth;
			float preferredWidth;
			if (!((Object)(object)component != (Object)null))
			{
				rect = rectTransform.rect;
				preferredWidth = ((Rect)(ref rect)).width;
			}
			else
			{
				preferredWidth = component.preferredWidth;
			}
			val2.preferredWidth = preferredWidth;
			float minHeight;
			if (!((Object)(object)component != (Object)null))
			{
				rect = rectTransform.rect;
				minHeight = ((Rect)(ref rect)).height;
			}
			else
			{
				minHeight = component.minHeight;
			}
			val2.minHeight = minHeight;
			float preferredHeight;
			if (!((Object)(object)component != (Object)null))
			{
				rect = rectTransform.rect;
				preferredHeight = ((Rect)(ref rect)).height;
			}
			else
			{
				preferredHeight = component.preferredHeight;
			}
			val2.preferredHeight = preferredHeight;
			if ((Object)(object)component != (Object)null)
			{
				val2.flexibleWidth = component.flexibleWidth;
				val2.flexibleHeight = component.flexibleHeight;
				val2.layoutPriority = component.layoutPriority;
			}
			((Transform)rectTransform).SetParent((Transform)(object)val, false);
			rectTransform.anchorMin = Vector2.zero;
			rectTransform.anchorMax = Vector2.one;
			Vector2 offsetMin = (rectTransform.offsetMax = Vector2.zero);
			rectTransform.offsetMin = offsetMin;
			TMP_InputField input = ((Component)val).gameObject.AddComponent<TMP_InputField>();
			input.textViewport = val;
			input.textComponent = (TMP_Text)(object)valueText;
			((Selectable)input).targetGraphic = (Graphic)(object)valueText;
			((Graphic)valueText).raycastTarget = true;
			input.contentType = (ContentType)0;
			input.lineType = (LineType)0;
			input.characterLimit = 16;
			input.richText = false;
			Navigation navigation = ((Selectable)input).navigation;
			navigation.mode = (Mode)0;
			((Selectable)input).navigation = navigation;
			input.SetTextWithoutNotify(Plugin.Rate.Value.ToString("F1", CultureInfo.InvariantCulture) + "x");
			((UnityEvent<string>)(object)input.onEndEdit).AddListener(UnityAction<string>.op_Implicit((Action<string>)delegate(string value)
			{
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Expected O, but got Unknown
				try
				{
					if (TimePolicy.TryRate(value.Trim().TrimEnd('x', 'X'), out var value2))
					{
						setting.slider.value = TimePolicy.SnapRate(value2);
					}
					input.SetTextWithoutNotify(((SettingUIElement<float>)(object)setting).CurrentChoice.ToString("F1", CultureInfo.InvariantCulture) + "x");
				}
				catch (Exception ex)
				{
					ManualLogSource modLog = Plugin.ModLog;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(27, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Unable to edit clock rate: ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
					}
					modLog.LogError(val3);
				}
			}));
			return input;
		}

		internal static void StopInputWatch()
		{
			inputSubscriptions?.Stop();
		}

		private static void RetireInputStatus(GameObject row)
		{
			int instanceID = ((Object)row).GetInstanceID();
			if (canvasOwners.TryGetValue(instanceID, out CanvasBehaviourManager value) && (Object)(object)value != (Object)null)
			{
				CanvasBehaviourManager.UnregisterRuntimeChildren(row.transform, value);
			}
			canvasOwners.Remove(instanceID);
			Object.Destroy((Object)(object)row);
		}

		internal static void Shutdown()
		{
			StopInputWatch();
			FinishInputRollback();
			controls.Clear();
			refreshBindingDisplays = false;
			foreach (GameObject row in rows)
			{
				if ((Object)(object)row == (Object)null)
				{
					continue;
				}
				GameplaySettingsUI componentInParent = row.GetComponentInParent<GameplaySettingsUI>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					((SettingsTabPanel)componentInParent)._elements = Il2CppReferenceArray<SettingUIElementBase>.op_Implicit(((IEnumerable<SettingUIElementBase>)((SettingsTabPanel)componentInParent)._elements).Where((SettingUIElementBase e) => (Object)(object)e != (Object)null && (Object)(object)((Component)e).gameObject != (Object)(object)row).ToArray());
				}
				ControlsSettingsUI componentInParent2 = row.GetComponentInParent<ControlsSettingsUI>();
				if ((Object)(object)componentInParent2 != (Object)null)
				{
					componentInParent2.controls.Remove(row.GetComponent<InputRebindUI>());
				}
				if (canvasOwners.TryGetValue(((Object)row).GetInstanceID(), out CanvasBehaviourManager value) && (Object)(object)value != (Object)null)
				{
					CanvasBehaviourManager.UnregisterRuntimeChildren(row.transform, value);
				}
				Object.Destroy((Object)(object)row);
			}
			rows.Clear();
			foreach (GameObject inputStatusRow in inputStatusRows)
			{
				if ((Object)(object)inputStatusRow != (Object)null)
				{
					RetireInputStatus(inputStatusRow);
				}
			}
			inputStatusRows.Clear();
			canvasOwners.Clear();
			layoutChecks.Clear();
			if (action != null && (Object)(object)owner != (Object)null)
			{
				List<InputAction> list = new List<InputAction>();
				Enumerator<InputActionMap> enumerator2 = owner.actionMaps.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					Enumerator<InputAction> enumerator3 = enumerator2.Current.actions.GetEnumerator();
					while (enumerator3.MoveNext())
					{
						InputAction current2 = enumerator3.Current;
						if (current2.enabled && current2 != action)
						{
							list.Add(current2);
						}
					}
				}
				owner.Disable();
				try
				{
					InputActionSetupExtensions.RemoveAction(action);
				}
				finally
				{
					foreach (InputAction item in list)
					{
						item.Enable();
					}
				}
			}
			if ((Object)(object)reference != (Object)null)
			{
				Object.Destroy((Object)(object)reference);
			}
			action = null;
			reference = null;
			owner = null;
			inputReady = false;
			inputFailure = null;
			pendingControls.Clear();
			inputSubscriptions = null;
			deviceChanged = null;
			bindingChanged = null;
		}

		private static void FinishInputRollback()
		{
			if (rollbackAction != null)
			{
				InputActionSetupExtensions.RemoveAction(rollbackAction);
				rollbackAction = null;
			}
			if ((Object)(object)rollbackReference != (Object)null)
			{
				Object.Destroy((Object)(object)rollbackReference);
				rollbackReference = null;
			}
		}

		internal static void RefreshPendingInputUi()
		{
			if (!inputReady)
			{
				return;
			}
			ControlsSettingsUI[] array = pendingControls.ToArray();
			foreach (ControlsSettingsUI val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					pendingControls.Remove(val);
				}
				else if (((Component)val).gameObject.activeInHierarchy)
				{
					pendingControls.Remove(val);
					try
					{
						Attach(val);
					}
					catch (Exception ex)
					{
						Plugin.ModLog.LogError((object)("Wait input is ready, but its queued Controls row failed: " + ex));
					}
				}
			}
		}

		internal static void InitializeInput(PlayerInputManager manager)
		{
			InputActionAsset asset = manager.Input.asset;
			if ((Object)(object)owner == (Object)(object)asset && inputReady)
			{
				return;
			}
			inputReady = false;
			InputAction val = null;
			InputActionReference val2 = null;
			InputActionMap val3 = null;
			bool flag = false;
			try
			{
				WaitInputSubscriptions waitInputSubscriptions = inputSubscriptions;
				if (waitInputSubscriptions != null && !waitInputSubscriptions.Active)
				{
					inputSubscriptions.Stop();
					inputSubscriptions = null;
					deviceChanged = null;
					bindingChanged = null;
				}
				FinishInputRollback();
				Enumerator<InputActionMap> enumerator = asset.actionMaps.GetEnumerator();
				while (enumerator.MoveNext())
				{
					if (enumerator.Current.enabled)
					{
						throw new InvalidOperationException("Wait must be registered before native input actions are enabled.");
					}
				}
				string text = WaitBindingGroups.Find(asset, "Keyboard", "Mouse");
				if (string.IsNullOrEmpty(text))
				{
					throw new InvalidOperationException("Native keyboard binding group was not found.");
				}
				string text2 = WaitBindingGroups.Find(asset, "Gamepad");
				if (string.IsNullOrEmpty(text2))
				{
					throw new InvalidOperationException("Native controller binding group was not found.");
				}
				val3 = manager.GameplayControls;
				if (val3.FindAction("Wait", false) != null)
				{
					throw new InvalidOperationException("A Wait action already exists without completed Better Time ownership.");
				}
				flag = true;
				val = InputActionSetupExtensions.AddAction(val3, "Wait", (InputActionType)1, "<Keyboard>/t", (string)null, (string)null, text, "Button");
				val.m_Id = "6697fae0-b29e-493c-9cc9-d76d317452c7";
				Il2CppReferenceArray<InputBinding> bindings = val3.m_Bindings;
				InputBinding val4 = ((Il2CppArrayBase<InputBinding>)(object)bindings)[((Il2CppArrayBase<InputBinding>)(object)bindings).Length - 1];
				val4.m_Id = "495c85ec-ebbd-47ae-8b9c-91a662d095eb";
				((Il2CppArrayBase<InputBinding>)(object)bindings)[((Il2CppArrayBase<InputBinding>)(object)bindings).Length - 1] = val4;
				InputActionSetupExtensions.AddBinding(val, "<Gamepad>/leftTrigger", (string)null, (string)null, text2);
				Il2CppReferenceArray<InputBinding> bindings2 = val3.m_Bindings;
				val4 = ((Il2CppArrayBase<InputBinding>)(object)bindings2)[((Il2CppArrayBase<InputBinding>)(object)bindings2).Length - 1];
				val4.m_Id = "73a613ea-91c5-4aac-af1c-ff77e2968d34";
				((Il2CppArrayBase<InputBinding>)(object)bindings2)[((Il2CppArrayBase<InputBinding>)(object)bindings2).Length - 1] = val4;
				val3.ClearActionLookupTable();
				val3.OnSetupChanged();
				val2 = InputActionReference.Create(val);
				InputActionRebindingExtensions.ApplyBindingOverride(val, 0, Plugin.BindingPath.Value);
				InputActionRebindingExtensions.ApplyBindingOverride(val, 1, Plugin.GamepadBindingPath.Value);
				WatchDevices();
				InputActionReference val5 = reference;
				action = val;
				reference = val2;
				owner = asset;
				inputReady = true;
				inputFailure = null;
				controls.Clear();
				try
				{
					foreach (GameObject row in rows)
					{
						if (!((Object)(object)row == (Object)null))
						{
							InputRebindUI component = row.GetComponent<InputRebindUI>();
							if ((Object)(object)component != (Object)null)
							{
								((InputDisplayUI)component).action.actionReference = reference;
							}
						}
					}
					if ((Object)(object)val5 != (Object)null)
					{
						Object.Destroy((Object)(object)val5);
					}
				}
				catch (Exception ex)
				{
					Plugin.ModLog.LogError((object)("Wait input registered, but its Controls UI could not refresh: " + ex));
				}
				Plugin.ModLog.LogInfo((object)"Registered native Wait action before input activation; vanilla input was not disabled or re-enabled.");
			}
			catch (Exception ex2)
			{
				List<Exception> list = new List<Exception> { ex2 };
				try
				{
					inputSubscriptions?.Stop();
					inputSubscriptions = null;
					deviceChanged = null;
					bindingChanged = null;
				}
				catch (Exception item)
				{
					list.Add(item);
				}
				try
				{
					if (val == null && flag)
					{
						val = ((val3 != null) ? val3.FindAction("Wait", false) : null);
					}
					if (val != null)
					{
						rollbackAction = val;
						InputActionSetupExtensions.RemoveAction(val);
						rollbackAction = null;
					}
				}
				catch (Exception item2)
				{
					list.Add(item2);
				}
				try
				{
					if ((Object)(object)val2 != (Object)null)
					{
						rollbackReference = val2;
						Object.Destroy((Object)(object)val2);
						rollbackReference = null;
					}
				}
				catch (Exception item3)
				{
					list.Add(item3);
				}
				action = null;
				reference = null;
				owner = null;
				inputReady = false;
				inputFailure = ((list.Count == 1) ? ex2 : new AggregateException("Wait registration and cleanup failed", list));
				throw inputFailure;
			}
		}
	}
	internal sealed class OverrideLease
	{
		private readonly OverrideLock handle;

		private OverrideableBool? target;

		private Object? owner;

		private int attempts;

		private double due;

		internal bool Requested { get; private set; }

		internal bool Complete { get; private set; }

		internal bool Exhausted
		{
			get
			{
				if (Requested && !Complete)
				{
					return attempts >= 4;
				}
				return false;
			}
		}

		internal Exception? Failure { get; private set; }

		internal OverrideLease(OverrideLock handle)
		{
			this.handle = handle;
		}

		internal void Request(double now, Action<Exception> report)
		{
			if (!Requested)
			{
				Requested = true;
				Attempt(now, report);
			}
		}

		internal void Tick(double now, Action<Exception> report)
		{
			if (Requested && !Complete && attempts < 4 && now >= due)
			{
				Attempt(now, report);
			}
		}

		private void Attempt(double now, Action<Exception> report)
		{
			attempts++;
			due = now + 1.0;
			Exception ex = null;
			try
			{
				if (target == null)
				{
					target = handle._target;
				}
				if (owner == null)
				{
					owner = handle._owner;
				}
				if (target == null || owner == null)
				{
					throw new InvalidOperationException("Override lock target or owner is unavailable; restoration retained.");
				}
				if (!target._overrideOwners.Contains(owner))
				{
					Complete = true;
					return;
				}
				try
				{
					if (handle.IsReleased)
					{
						target.ReleaseOverride(owner);
					}
					else
					{
						handle.Release();
					}
				}
				catch (Exception ex2)
				{
					ex = ex2;
				}
				Complete = !target._overrideOwners.Contains(owner);
				if (!Complete && ex == null)
				{
					ex = new InvalidOperationException("Native override removal did not remove the recorded owner.");
				}
			}
			catch (Exception ex3)
			{
				ex = ((ex == null) ? ex3 : new AggregateException(ex, ex3));
			}
			if (ex == null)
			{
				return;
			}
			if (Failure == null)
			{
				Exception ex4 = (Failure = ex);
			}
			try
			{
				report(Exhausted ? new AggregateException("Override cleanup exhausted its initial attempt and three scheduled retries; owner remains unresolved.", Failure, ex) : ex);
			}
			catch
			{
			}
		}
	}
	internal sealed class PhoneDelayClock
	{
		private bool initialized;

		private int lastEnd;

		private int lastNow;

		private double elapsed;

		internal bool Ready(int now, int ended, float rate, float deltaSeconds, bool paused, int nativeDelay, bool dialogueActive = false)
		{
			if (dialogueActive)
			{
				elapsed = 0.0;
				initialized = true;
				lastEnd = ended;
				lastNow = now;
				return false;
			}
			rate = (float.IsFinite(rate) ? Math.Clamp(rate, 0f, 2f) : 1f);
			double num = ((rate > 0f) ? rate : 1f);
			if (!initialized || ended != lastEnd || now < lastNow)
			{
				elapsed = Math.Max(0.0, (double)now - (double)ended) / num;
				initialized = true;
			}
			else
			{
				double num2 = Math.Max(0.0, (double)now - (double)lastNow);
				double num3 = ((!paused && float.IsFinite(deltaSeconds)) ? (Math.Max(0f, deltaSeconds) * 60f) : 0f);
				elapsed += num3;
				if ((paused && num2 > 0.0) || num2 > Math.Max(2.0, num3 * num + 1.0))
				{
					elapsed += Math.Max(0.0, num2 / num - num3);
				}
			}
			lastEnd = ended;
			lastNow = now;
			return elapsed > (double)nativeDelay;
		}
	}
	[HarmonyPatch(typeof(DialogueTreeProgressManager), "Update")]
	internal static class PhoneDelayPatch
	{
		private static nint owner;

		private static PhoneDelayClock clock = new PhoneDelayClock();

		internal static void Clear()
		{
			owner = 0;
			clock = new PhoneDelayClock();
		}

		private static void Prefix(DialogueTreeProgressManager __instance, out int __state)
		{
			__state = __instance.phoneCallDelay;
			if (owner != ((Il2CppObjectBase)__instance).Pointer)
			{
				Clear();
				owner = ((Il2CppObjectBase)__instance).Pointer;
			}
			bool flag = clock.Ready(TimeOfDayManager.TotalGameSeconds, __instance._lastDialogueEndTime, Plugin.Rate.Value, Time.deltaTime, (Object)(object)Singleton<TimeOfDayManager>.Instance == (Object)null || Singleton<TimeOfDayManager>.Instance.IsPaused, __state, __instance.IsInDialogue);
			if (Plugin.Rate.Value != 1f)
			{
				__instance.phoneCallDelay = (flag ? (-1) : int.MaxValue);
			}
		}

		private static void Finalizer(DialogueTreeProgressManager __instance, int __state)
		{
			__instance.phoneCallDelay = __state;
		}
	}
	[HarmonyPatch(typeof(DialogueTreeProgressManager), "InitializeInternal")]
	internal static class ResetPhoneDelayPatch
	{
		private static void Postfix()
		{
			PhoneDelayPatch.Clear();
		}
	}
	internal static class PlacementCosts
	{
		internal static float Read(int area, bool bound, Func<int, float> agentCost, Func<int, float> worldCost)
		{
			if (!bound)
			{
				return worldCost(area);
			}
			return agentCost(area);
		}
	}
	internal readonly record struct PlacementCapsule(Vector3 Lower, Vector3 Upper, float Radius)
	{
		internal PlacementCapsule Offset(Vector3 delta)
		{
			return new PlacementCapsule(Lower + delta, Upper + delta, Radius);
		}

		internal bool Overlaps(PlacementCapsule other)
		{
			float num = Math.Max(0f, Math.Max(other.Lower.Y - Upper.Y, Lower.Y - other.Upper.Y));
			float num2 = Lower.X - other.Lower.X;
			float num3 = Lower.Z - other.Lower.Z;
			float num4 = Radius + other.Radius + 0.04f;
			return num2 * num2 + num * num + num3 * num3 < num4 * num4;
		}
	}
	internal sealed class PlacementReservations
	{
		private readonly Dictionary<nint, PlacementCapsule> positions = new Dictionary<IntPtr, PlacementCapsule>();

		internal void Reserve(nint character, PlacementCapsule volume)
		{
			positions[character] = volume;
		}

		internal void Release(nint character)
		{
			positions.Remove(character);
		}

		internal bool Overlaps(PlacementCapsule candidate)
		{
			foreach (PlacementCapsule value in positions.Values)
			{
				if (candidate.Overlaps(value))
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class PlacementSearch
	{
		internal const float Range = 3.2f;

		internal static bool CanRetainOrigin(Vector3 origin, Vector3? projected, Func<Vector3, bool> clear)
		{
			if (projected.HasValue && (projected.Value - origin).LengthSquared() < 0.0001f)
			{
				return clear(origin);
			}
			return false;
		}

		internal static Vector3? Find(Vector3 origin, Func<Vector3, Vector3?> project, Func<Vector3, bool> clear)
		{
			Vector3? result = null;
			foreach (byte item in FindSteps(origin, project, clear, delegate(Vector3? value)
			{
				result = value;
			}))
			{
				_ = item;
			}
			return result;
		}

		internal static IEnumerable<byte> FindSteps(Vector3 origin, Func<Vector3, Vector3?> project, Func<Vector3, bool> clear, Action<Vector3?> completed)
		{
			Vector3? best = null;
			float score = float.PositiveInfinity;
			for (int pass = 0; pass < 2; pass++)
			{
				if (best.HasValue)
				{
					break;
				}
				for (int ring = pass; ring <= 8; ring++)
				{
					for (int spoke = 0; spoke < ((ring == 0) ? 1 : 16); spoke++)
					{
						yield return 0;
						float x = ((float)spoke + (float)pass * 0.5f) * ((float)Math.PI / 8f);
						float num = (float)ring * 0.4f - (float)pass * 0.2f;
						Vector3? vector = project(origin + new Vector3(MathF.Cos(x) * num, 0f, MathF.Sin(x) * num));
						if (vector.HasValue)
						{
							Vector3 vector2 = vector.Value - origin;
							float num2 = vector2.LengthSquared();
							if (!(MathF.Abs(vector2.Y) > 0.5f) && !(num2 > 10.240001f) && !(num2 >= score) && clear(vector.Value))
							{
								best = vector;
								score = num2;
							}
						}
					}
				}
			}
			completed(best);
		}
	}
	[BepInPlugin("hvizeu.nivalis.slowdays", "Nivalis Better Time", "2.2.3")]
	[BepInProcess("Nivalis Nights.exe")]
	public sealed class Plugin : BasePlugin
	{
		internal const string Version = "2.2.3";

		internal static ManualLogSource ModLog;

		internal static ConfigEntry<float> Rate;

		internal static ConfigEntry<bool> BalanceArrivals;

		internal static ConfigEntry<Key> MenuKey;

		internal static ConfigEntry<string> BindingPath;

		internal static ConfigEntry<string> GamepadBindingPath;

		internal static ConfigEntry<int> LastWaitDurationSeconds;

		private readonly Harmony harmony = new Harmony("hvizeu.nivalis.slowdays");

		private readonly FeatureHooks featureHooks = new FeatureHooks("hvizeu.nivalis.slowdays", delegate(string feature, Exception error)
		{
			ModLog.LogError((object)(feature + ": " + error));
		});

		internal static int RememberedWait
		{
			get
			{
				int value = LastWaitDurationSeconds.Value;
				if (value <= 0 || value > 86400)
				{
					return 0;
				}
				return LastWaitDurationSeconds.Value;
			}
		}

		internal static void RememberWait(int seconds)
		{
			LastWaitDurationSeconds.Value = seconds;
			if (!((ConfigEntryBase)LastWaitDurationSeconds).ConfigFile.SaveOnConfigSet)
			{
				((ConfigEntryBase)LastWaitDurationSeconds).ConfigFile.Save();
			}
		}

		public override void Load()
		{
			if (NativeCompatibility.Check(Paths.GameRootPath, delegate(string message)
			{
				((BasePlugin)this).Log.LogError((object)message);
			}))
			{
				LoadVerified();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void LoadVerified()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Expected O, but got Unknown
			ModLog = ((BasePlugin)this).Log;
			if (!NativeCompatibility.Check(Paths.GameRootPath, delegate(string message)
			{
				((BasePlugin)this).Log.LogError((object)message);
			}))
			{
				return;
			}
			Rate = ((BasePlugin)this).Config.Bind<float>("Time", "ClockRate", 0.3f, new ConfigDescription("Natural clock speed, rounded to tenths: 1 = original, 0.5 = half, 0.1 = tenth, 0 = frozen. Sleep and waiting keep their targets.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			BalanceArrivals = ((BasePlugin)this).Config.Bind<bool>("Balance", "ScaleCustomerArrivals", true, "Stop new restaurant visits while the clock is frozen, except during an explicit wait. At positive rates, native needs, schedules and visit/search cooldowns follow game time once. No sales-history forecast, first-day exemption or daily income cap. Prices, stock consumption, hourly pay and animation speed retain native rules.");
			MenuKey = ((BasePlugin)this).Config.Bind<Key>("Controls", "TimeMenuKey", (Key)34, "Legacy shortcut, migrated to WaitBinding. Use Settings > Controls to rebind Wait.");
			BindingPath = ((BasePlugin)this).Config.Bind<string>("Controls", "WaitBinding", "<Keyboard>/" + ((object)MenuKey.Value/*cast due to .constrained prefix*/).ToString().ToLowerInvariant(), "Wait shortcut, managed by the native Settings > Controls rebinding row.");
			GamepadBindingPath = ((BasePlugin)this).Config.Bind<string>("Controls", "WaitGamepadBinding", "<Gamepad>/leftTrigger", "Controller Wait shortcut (default LT/L2). Rebind WAIT in Settings > Controls while using a controller.");
			LastWaitDurationSeconds = ((BasePlugin)this).Config.Bind<int>("Wait", "LastWaitDurationSeconds", 0, "Last successfully started wait duration in game seconds. Q recalls it in Wait; 0 means no previous wait.");
			float num = TimePolicy.SnapRate(Rate.Value);
			if (Rate.Value != num)
			{
				Rate.Value = num;
				((BasePlugin)this).Config.Save();
			}
			try
			{
				featureHooks.Install(typeof(Plugin).Assembly, new HashSet<string>());
				((BasePlugin)this).AddComponent<TimeController>();
			}
			catch (Exception ex)
			{
				try
				{
					featureHooks.Stop();
					harmony.UnpatchSelf();
				}
				catch (Exception ex2)
				{
					throw new AggregateException("Better Time initialization and cleanup failed; ownership retained.", ex, ex2);
				}
				throw;
			}
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(260, 5, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Better Time ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("2.2.3");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded (Steam build 25828494 bindings). Clock rate ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Rate.Value, "F1");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; balanced customer arrivals=");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(BalanceArrivals.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; Wait binding ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(BindingPath.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; controller Wait binding ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(GamepadBindingPath.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". Native needs and visit/search cooldowns follow game time once. No additional admission multiplier or sales-history forecast.");
			}
			log.LogInfo(val);
		}

		public override bool Unload()
		{
			TimeController? current = TimeController.Current;
			if ((current != null && current.Busy) || HourlyWork.Pending)
			{
				return false;
			}
			try
			{
				NativeSettings.StopInputWatch();
			}
			catch (Exception ex)
			{
				TimeController.Current?.Fail(ex);
				return false;
			}
			TimeController? current2 = TimeController.Current;
			if (current2 != null && !current2.Shutdown())
			{
				return false;
			}
			NativeSettings.Shutdown();
			PhoneDelayPatch.Clear();
			SustainedAnimationPatch.Clear();
			featureHooks.Stop();
			harmony.UnpatchSelf();
			return true;
		}
	}
	[HarmonyPatch(typeof(TimeOfDayManager), "Update")]
	internal static class ClockUpdatePatch
	{
		internal struct TickState
		{
			public float Original;

			public bool Applied;
		}

		[HarmonyPrefix]
		private static void Prefix(TimeOfDayManager __instance, out TickState __state)
		{
			__state = new TickState
			{
				Original = __instance.timeTickMultiplier
			};
			float value = Plugin.Rate.Value;
			__instance.timeTickMultiplier = __state.Original * (float.IsFinite(value) ? Math.Clamp(value, 0f, 2f) : 1f);
			__state.Applied = true;
		}

		[HarmonyFinalizer]
		private static void Finalizer(TimeOfDayManager __instance, TickState __state)
		{
			if (__state.Applied)
			{
				__instance.timeTickMultiplier = __state.Original;
			}
		}
	}
	[HarmonyPatch(typeof(VenueManager), "OnHourTick")]
	internal static class HourlyPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(VenueManager __instance)
		{
			return !HourlyWork.Start(__instance);
		}
	}
	[HarmonyPatch(typeof(GameplaySettingsUI), "BeforeDisplay")]
	internal static class SettingsEntryPatch
	{
		[HarmonyPostfix]
		private static void Postfix(GameplaySettingsUI __instance)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			try
			{
				NativeSettings.Attach(__instance);
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = Plugin.ModLog;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(45, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Unable to add Better Time gameplay settings: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				modLog.LogError(val);
			}
		}
	}
	[HarmonyPatch(typeof(ControlsSettingsUI), "Start")]
	internal static class ControlsEntryPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ControlsSettingsUI __instance)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			try
			{
				NativeSettings.Attach(__instance);
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = Plugin.ModLog;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(35, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Unable to add native Wait binding: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				modLog.LogError(val);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerInputManager), "LoadBindings")]
	internal static class RestoreWaitBindingPatch
	{
		[HarmonyPrefix]
		private static void Prefix(PlayerInputManagerSave save)
		{
			WaitBindingPersistencePatch.RemoveOwnOverride(save);
		}

		[HarmonyPostfix]
		private static void Postfix()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			try
			{
				NativeSettings.RestoreBinding();
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = Plugin.ModLog;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(49, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Unable to restore Wait shortcut after save load: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				modLog.LogError(val);
			}
		}
	}
	[HarmonyPatch(typeof(InputRebindUI), "UpdateText")]
	internal static class WaitBindingLabelPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(InputRebindUI __instance)
		{
			if (((Object)((Component)__instance).gameObject).name != "Hvizeu.Wait")
			{
				return true;
			}
			((TMP_Text)__instance.actionText).text = "WAIT";
			return false;
		}
	}
	[HarmonyPatch(typeof(PlayerInputManager), "InitializeInternal")]
	internal static class RegisterWaitInputPatch
	{
		[HarmonyPrefix]
		private static void Prefix(ISavePacket packet)
		{
			if (packet != null)
			{
				WaitBindingPersistencePatch.RemoveOwnOverride(((Il2CppObjectBase)packet).TryCast<PlayerInputManagerSave>());
			}
		}

		[HarmonyPostfix]
		private static void Postfix(PlayerInputManager __instance)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			try
			{
				NativeSettings.InitializeInput(__instance);
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = Plugin.ModLog;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(94, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Wait input registration failed; vanilla input was left enabled/disabled as owned by the game: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				modLog.LogError(val);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerInputManager), "SaveBindings")]
	internal static class WaitBindingPersistencePatch
	{
		[HarmonyPostfix]
		private static void Postfix(PlayerInputManagerSave save)
		{
			try
			{
				NativeSettings.SaveBinding();
			}
			finally
			{
				RemoveOwnOverride(save);
			}
		}

		internal static void RemoveOwnOverride(PlayerInputManagerSave? save)
		{
			if (save != null)
			{
				string bindingJsonString = save.BindingJsonString;
				string text = BindingJson.WithoutWait(bindingJsonString);
				if (!(text == bindingJsonString))
				{
					save.BindingJsonString = text;
					Plugin.ModLog.LogInfo((object)"Kept Wait override in mod config; removed its entry from native binding packet. Other bindings retained.");
				}
			}
		}
	}
	[HarmonyPatch(typeof(Debug), "LogException", new Type[] { typeof(Exception) })]
	internal static class ObserveWaitNativeException
	{
		[HarmonyPrefix]
		private static void Prefix(Exception exception)
		{
			if (WaitFaults.Active)
			{
				WaitFaults.ObserveException(((exception != null) ? ((Object)exception).ToString() : null) ?? "Native exception", "Unity Debug.LogException");
			}
		}
	}
	[HarmonyPatch(typeof(Character), "DoLateUpdate")]
	internal static class SustainedAnimationPatch
	{
		private static List<AnimatorClipInfo>? clips;

		private static readonly HashSet<int> reported = new HashSet<int>();

		private static bool failed;

		internal static void Clear()
		{
			clips = null;
			reported.Clear();
			failed = false;
		}

		[HarmonyPrefix]
		internal static void Prefix(Character __instance)
		{
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Expected O, but got Unknown
			if (failed)
			{
				return;
			}
			bool flag2 = default(bool);
			try
			{
				if (__instance.AnimatorUpdateStep > 0 || !((BaseCharacter)__instance).CameraVisible || WaitPresentation.Hold(__instance) || !(Time.deltaTime > 0f))
				{
					return;
				}
				Animator animator = ((BaseCharacter)__instance).Animator;
				if ((Object)(object)animator == (Object)null || !animator.isInitialized || !(animator.speed > 0f) || animator.layerCount == 0 || animator.IsInTransition(0))
				{
					return;
				}
				AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
				string text = SustainedAnimationPolicy.ClipFor(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash);
				if (text == null || !SustainedAnimationPolicy.Completed(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime, ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).speed, ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).speedMultiplier))
				{
					return;
				}
				if (clips == null)
				{
					clips = new List<AnimatorClipInfo>();
				}
				animator.GetCurrentAnimatorClipInfo(0, clips);
				bool flag = false;
				for (int i = 0; i < clips.Count; i++)
				{
					AnimatorClipInfo val = clips[i];
					if (!float.IsFinite(((AnimatorClipInfo)(ref val)).weight) || ((AnimatorClipInfo)(ref val)).weight < 0f)
					{
						return;
					}
					if (((AnimatorClipInfo)(ref val)).weight == 0f)
					{
						continue;
					}
					AnimationClip clip = ((AnimatorClipInfo)(ref val)).clip;
					if ((Object)(object)clip == (Object)null)
					{
						return;
					}
					if (!((Motion)clip).isLooping)
					{
						if (((Object)clip).name != text)
						{
							return;
						}
						flag = true;
					}
				}
				if (!flag)
				{
					return;
				}
				for (int j = 0; j < clips.Count; j++)
				{
					AnimatorClipInfo val2 = clips[j];
					if (((AnimatorClipInfo)(ref val2)).weight > 0f)
					{
						val2 = clips[j];
						if (((Il2CppArrayBase<AnimationEvent>)(object)((AnimatorClipInfo)(ref val2)).clip.events).Length != 0)
						{
							return;
						}
					}
				}
				animator.Play(0, 0, ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime % 1f);
				if (reported.Add(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash))
				{
					ManualLogSource modLog = P