Decompiled source of Eggstended Play v0.1.2

BepInEx/plugins/CrackEggstendedPlay/CrackEggstendedPlay.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CrackEggstendedPlay
{
	internal sealed class CreditsWatcher : MonoBehaviour
	{
		private GameEndUI _ui;

		private float _startedAt;

		private float _held;

		private bool _done;

		private bool _loggedVisible;

		private float _waitingSince;

		internal void Init(GameEndUI ui)
		{
			_ui = ui;
			_startedAt = Time.unscaledTime;
			_held = 0f;
			_done = false;
			_loggedVisible = false;
			_waitingSince = 0f;
		}

		private void Update()
		{
			if (_done || (Object)(object)_ui == (Object)null || Time.unscaledTime < _startedAt + 0.75f)
			{
				return;
			}
			if (!EndUi.ContentActive(_ui))
			{
				if (_waitingSince <= 0f)
				{
					_waitingSince = Time.unscaledTime;
				}
				else if (Time.unscaledTime - _waitingSince > 10f)
				{
					ManualLogSource log = EggstendedPlayPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)"[Overtime] still waiting for the credits content to become active.");
					}
					_waitingSince = Time.unscaledTime;
				}
				_held = 0f;
				return;
			}
			if (!_loggedVisible)
			{
				_loggedVisible = true;
				EndUi.SetSkipPromptActive(_ui, active: true);
				ManualLogSource log2 = EggstendedPlayPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)"[Overtime] credits content is visible; skip is armed.");
				}
			}
			CanvasGroup val = EndUi.Menu(_ui);
			if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy && (val.blocksRaycasts || val.alpha > 0.99f))
			{
				Finish("ending menu");
				return;
			}
			bool flag = false;
			Keyboard current = Keyboard.current;
			if (current != null && ((ButtonControl)current.spaceKey).isPressed)
			{
				flag = true;
			}
			Gamepad current2 = Gamepad.current;
			if (current2 != null && current2.buttonSouth.isPressed)
			{
				flag = true;
			}
			if (flag)
			{
				_held += Time.unscaledDeltaTime;
				if (_held >= 1.2f)
				{
					Skip();
				}
			}
			else
			{
				_held = 0f;
			}
		}

		private void Skip()
		{
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[Overtime] credits skipped by the local player.");
			}
			EndUi.StopCinematics();
			EndUi.HideCompletely(_ui);
			Finish("skipped");
		}

		private void Finish(string why)
		{
			if (!_done)
			{
				_done = true;
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("[Overtime] credits finished (" + why + ")."));
				}
				EndUi.DisableMenu(_ui);
				EndUi.ShowBlackout();
				EndUi.CloseEyes();
				if (NetworkServer.active)
				{
					OvertimeFlow.ServerCreditsDone();
				}
				Object.Destroy((Object)(object)this);
			}
		}
	}
	internal static class DebugControl
	{
		private static bool _unlocked;

		private static readonly MethodInfo LiteralMethod = AccessTools.Method(typeof(ConsoleApp), "Literal", new Type[1] { typeof(string) }, (Type[])null);

		internal static bool Unlocked => _unlocked;

		internal static void Init()
		{
		}

		internal static bool TryRun(ConsoleApp app, string command)
		{
			if ((Object)(object)app == (Object)null || string.IsNullOrWhiteSpace(command))
			{
				return true;
			}
			string text = command.Trim();
			string text2 = text.ToUpperInvariant();
			if (text2 == "DOUBLESHIFT")
			{
				_unlocked = true;
				Print(app, "FACS> " + text);
				Print(app, "-- EGG MAINTENANCE --");
				Print(app, "DOUBLESHIFT accepted. Type EGG HELP.");
				Print(app, "");
				return false;
			}
			if (!text2.StartsWith("EGG", StringComparison.Ordinal) || !_unlocked)
			{
				return true;
			}
			string[] array = text2.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			string text3 = ((array.Length > 1) ? array[1] : "HELP");
			Print(app, "FACS> " + text);
			switch (text3)
			{
			case "HELP":
				Print(app, "EGG STATUS          shell, decal and agitation state");
				Print(app, "EGG SHELL [NAME]    set palette: robin, phoenix, alien, random");
				Print(app, "EGG DECAL [1-4]     force an alien/phoenix decal sheet");
				Print(app, "EGG AGITATE [PCT]   raise egg agitation (default 20)");
				Print(app, "EGG TOSS            replace the egg now (no ending, no credits)");
				break;
			case "STATUS":
				Print(app, "palette:    " + (EggstendedPlayPlugin.ShellPalette?.Value ?? "robin"));
				Print(app, "active:     " + EggPalette.ActivePaletteName);
				Print(app, "decal:      " + EggDecals.LastApplied);
				Print(app, "agitation:  " + (((Object)(object)AgitationManager.instance != (Object)null) ? ((AgitationManager.instance.Agitation01 * 100f).ToString("0") + "%") : "not in scene"));
				break;
			case "SHELL":
			{
				if (!ServerCheck(app))
				{
					break;
				}
				if (array.Length < 3)
				{
					Print(app, "palettes: " + string.Join(", ", EggPalette.Presets));
					break;
				}
				string text4 = array[2].ToLowerInvariant();
				if (Array.IndexOf(EggPalette.Presets, text4) < 0 && text4 != "random")
				{
					Print(app, "unknown palette. palettes: " + string.Join(", ", EggPalette.Presets));
					break;
				}
				EggstendedPlayPlugin.ShellPalette.Value = text4;
				Print(app, EggPalette.ForceReapply(out var message) ? message : message);
				break;
			}
			case "DECAL":
				if (ServerCheck(app))
				{
					if (array.Length > 2 && int.TryParse(array[2], out var result2))
					{
						EggDecals.Force(result2 - 1);
						Print(app, "decal forced: " + EggDecals.LastApplied);
					}
					else
					{
						Print(app, "usage: EGG DECAL 1-4");
					}
				}
				break;
			case "TOSS":
				if (ServerCheck(app))
				{
					Print(app, OvertimeFlow.ServerTossEgg(out var message2) ? message2 : message2);
				}
				break;
			case "AGITATE":
				if (ServerCheck(app))
				{
					float num = 20f;
					if (array.Length > 2 && float.TryParse(array[2], out var result))
					{
						num = Mathf.Clamp(result, 1f, 100f);
					}
					AgitationManager instance = AgitationManager.instance;
					if ((Object)(object)instance == (Object)null)
					{
						Print(app, "No AgitationManager in this scene.");
						break;
					}
					float num2 = Mathf.Min(instance.MaxAgitation, instance.Agitation + instance.MaxAgitation * (num / 100f));
					instance.SetAgitation(num2);
					Print(app, "Agitation -> " + (num2 / instance.MaxAgitation * 100f).ToString("0") + "%.");
				}
				break;
			default:
				Print(app, "Unknown EGG command: " + text3);
				break;
			}
			Print(app, "");
			return false;
		}

		private static bool ServerCheck(ConsoleApp app)
		{
			if (!NetworkServer.active)
			{
				Print(app, "Not the host.");
				return false;
			}
			return true;
		}

		private static void Print(ConsoleApp app, string text)
		{
			try
			{
				LiteralMethod?.Invoke(app, new object[1] { text });
			}
			catch (Exception ex)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Egg] console print failed: " + ex.Message));
				}
			}
		}
	}
	[HarmonyPatch(typeof(ConsoleApp), "ServerRun", new Type[] { typeof(string) })]
	internal static class ConsoleAppServerRunPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ConsoleApp __instance, string command)
		{
			return DebugControl.TryRun(__instance, command);
		}
	}
	internal static class DecalTests
	{
		internal static readonly string[] Names = new string[4] { "full-uv", "ref-bbox", "ref-plus-digit", "quad-grid" };

		private const string TextureId = "_EggTexture";

		private const string AmountId = "_EggTextureAmount";

		private const int Width = 2048;

		private const int Height = 1024;

		private static int _index = -1;

		private static readonly Texture2D[] Cache = (Texture2D[])(object)new Texture2D[4];

		private static readonly string[] Glyphs = new string[4] { "00100011000010000100001000010001110", "01110100010000100110010001000011111", "11111000100010000010000011000101110", "00010001100101010010111110001000010" };

		internal static string Current
		{
			get
			{
				if (_index < 0 || _index >= Names.Length)
				{
					return "none";
				}
				return Names[_index];
			}
		}

		internal static void Cycle()
		{
			_index = (_index + 1) % Names.Length;
			Apply(_index);
		}

		internal static void Apply(int mode)
		{
			ref Texture2D reference = ref Cache[mode];
			Texture2D val = reference ?? (reference = Build(mode));
			if ((Object)(object)val == (Object)null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)$"[Decal] method {mode + 1} ({Names[mode]}) could not be built.");
				}
				return;
			}
			Shader.SetGlobalTexture("_EggTexture", (Texture)(object)val);
			Shader.SetGlobalFloat("_EggTextureAmount", 1f);
			ManualLogSource log2 = EggstendedPlayPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)$"[Decal] method {mode + 1}/4 '{Names[mode]}' applied ({((Texture)val).width}x{((Texture)val).height}).");
			}
		}

		internal static void Clear()
		{
			Shader.SetGlobalFloat("_EggTextureAmount", 0f);
		}

		private static Texture2D Build(int mode)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: 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_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = FindReferenceSkin();
			RectInt val2 = (RectInt)(((Object)(object)val != (Object)null) ? OpaqueBox(val) : new RectInt(0, 0, 2048, 1024));
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)(((Object)(object)val != (Object)null) ? $"[Decal] reference skin '{((Object)val).name}' {((Texture)val).width}x{((Texture)val).height}, opaque box {val2}." : "[Decal] no reference skin found; using the full square."));
			}
			Texture2D val3 = new Texture2D(2048, 1024, (TextureFormat)4, true)
			{
				name = "TEX_Decal_" + Names[mode],
				wrapMode = (TextureWrapMode)1,
				filterMode = (FilterMode)1
			};
			Color32[] array = (Color32[])(object)new Color32[2097152];
			Color32 val4 = default(Color32);
			((Color32)(ref val4))..ctor(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)0);
			if (mode == 2 && (Object)(object)val != (Object)null)
			{
				array = ReferencePixels(val);
			}
			else if (mode == 3 && (Object)(object)val != (Object)null)
			{
				array = ReferencePixels(val);
			}
			else
			{
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = val4;
				}
			}
			Color ink = (new Color[4]
			{
				new Color(0.91f, 0.08f, 0.24f),
				new Color(0.09f, 0.78f, 0.52f),
				new Color(0.18f, 0.49f, 1f),
				new Color(1f, 0.83f, 0f)
			})[mode];
			float num = 0.35f;
			if (mode == 3)
			{
				int num2 = Mathf.Max(8, Mathf.RoundToInt((float)((RectInt)(ref val2)).width / 3f));
				int num3 = Mathf.Max(8, Mathf.RoundToInt((float)((RectInt)(ref val2)).height / 3f));
				RectInt rect = default(RectInt);
				for (int j = 0; j < 3; j++)
				{
					for (int k = 0; k < 3; k++)
					{
						((RectInt)(ref rect))..ctor(((RectInt)(ref val2)).x + k * num2, ((RectInt)(ref val2)).y + j * num3, num2, num3);
						DrawDigit(array, Inset(rect, 0.18f), 4, ink);
					}
				}
			}
			else
			{
				RectInt rect2 = (RectInt)((mode == 0) ? new RectInt(0, 0, 2048, 1024) : val2);
				DrawDigit(array, Inset(rect2, (1f - num) / 2f), mode + 1, ink);
			}
			val3.SetPixels32(array);
			val3.Apply(true, false);
			return val3;
		}

		private static RectInt Inset(RectInt rect, float margin)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.RoundToInt((float)((RectInt)(ref rect)).width * margin);
			int num2 = Mathf.RoundToInt((float)((RectInt)(ref rect)).height * margin);
			return new RectInt(((RectInt)(ref rect)).x + num, ((RectInt)(ref rect)).y + num2, Mathf.Max(8, ((RectInt)(ref rect)).width - num * 2), Mathf.Max(8, ((RectInt)(ref rect)).height - num2 * 2));
		}

		private static Texture2D FindReferenceSkin()
		{
			try
			{
				EggSequence recipes = IncrementalEgg.Recipes;
				if ((Object)(object)recipes == (Object)null || recipes.eggs == null)
				{
					return null;
				}
				EggRecipe[] eggs = recipes.eggs;
				foreach (EggRecipe val in eggs)
				{
					if ((Object)(object)val != (Object)null && (Object)(object)val.skin != (Object)null && ((Texture)val.skin).isReadable)
					{
						return val.skin;
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Decal] reference skin lookup failed: " + ex.Message));
				}
			}
			return null;
		}

		private static RectInt OpaqueBox(Texture2D tex)
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			int num = ((Texture)tex).width;
			int num2 = ((Texture)tex).height;
			int num3 = -1;
			int num4 = -1;
			Color32[] pixels = tex.GetPixels32();
			for (int i = 0; i < ((Texture)tex).height; i++)
			{
				for (int j = 0; j < ((Texture)tex).width; j++)
				{
					if (pixels[i * ((Texture)tex).width + j].a > 8)
					{
						if (j < num)
						{
							num = j;
						}
						if (j > num3)
						{
							num3 = j;
						}
						if (i < num2)
						{
							num2 = i;
						}
						if (i > num4)
						{
							num4 = i;
						}
					}
				}
			}
			if (num3 < 0)
			{
				return new RectInt(0, 0, ((Texture)tex).width, ((Texture)tex).height);
			}
			float num5 = 2048f / (float)((Texture)tex).width;
			float num6 = 1024f / (float)((Texture)tex).height;
			return new RectInt(Mathf.FloorToInt((float)num * num5), Mathf.FloorToInt((float)num2 * num6), Mathf.Max(8, Mathf.CeilToInt((float)(num3 - num + 1) * num5)), Mathf.Max(8, Mathf.CeilToInt((float)(num4 - num2 + 1) * num6)));
		}

		private static Color32[] ReferencePixels(Texture2D tex)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			Color32[] pixels = tex.GetPixels32();
			Color32[] array = (Color32[])(object)new Color32[2097152];
			for (int i = 0; i < 1024; i++)
			{
				int num = Mathf.Clamp(i * ((Texture)tex).height / 1024, 0, ((Texture)tex).height - 1);
				for (int j = 0; j < 2048; j++)
				{
					int num2 = Mathf.Clamp(j * ((Texture)tex).width / 2048, 0, ((Texture)tex).width - 1);
					array[i * 2048 + j] = pixels[num * ((Texture)tex).width + num2];
				}
			}
			return array;
		}

		private static void DrawDigit(Color32[] pixels, RectInt rect, int digit, Color ink)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			string text = Glyphs[Mathf.Clamp(digit, 1, 4) - 1];
			int num = 5;
			int num2 = 7;
			int num3 = Mathf.Max(1, Mathf.Min(((RectInt)(ref rect)).width / num, ((RectInt)(ref rect)).height / num2));
			int num4 = num3 * num;
			int num5 = num3 * num2;
			int num6 = ((RectInt)(ref rect)).x + (((RectInt)(ref rect)).width - num4) / 2;
			int num7 = ((RectInt)(ref rect)).y + (((RectInt)(ref rect)).height - num5) / 2;
			Color32 val = Color32.op_Implicit(ink);
			for (int i = 0; i < num2; i++)
			{
				for (int j = 0; j < num; j++)
				{
					if (text[(num2 - 1 - i) * num + j] != '1')
					{
						continue;
					}
					for (int k = 0; k < num3; k++)
					{
						int num8 = num7 + i * num3 + k;
						if (num8 < 0 || num8 >= 1024)
						{
							continue;
						}
						for (int l = 0; l < num3; l++)
						{
							int num9 = num6 + j * num3 + l;
							if (num9 >= 0 && num9 < 2048)
							{
								pixels[num8 * 2048 + num9] = val;
							}
						}
					}
				}
			}
		}
	}
	internal static class EggDecals
	{
		private sealed class Group
		{
			internal readonly string[] Names;

			internal readonly Texture2D[] Cache;

			internal int LastPick = -1;

			internal Group(string[] names)
			{
				Names = names;
				Cache = (Texture2D[])(object)new Texture2D[names.Length];
			}
		}

		private const string TextureId = "_EggTexture";

		private const string AmountId = "_EggTextureAmount";

		private static readonly Group Alien = new Group(new string[4] { "alien_script_1.png", "alien_script_2.png", "alien_script_3.png", "alien_script_4.png" });

		private static readonly Group Phoenix = new Group(new string[2] { "phoenix_1.png", "phoenix_2.png" });

		private static Group _active;

		internal static string LastApplied { get; private set; } = "none";

		private static string Folder => Path.GetDirectoryName(typeof(EggDecals).Assembly.Location) ?? string.Empty;

		internal static void ApplyForPalette(string palette)
		{
			if (EggstendedPlayPlugin.DecalsEnabled != null && !EggstendedPlayPlugin.DecalsEnabled.Value)
			{
				Clear();
				return;
			}
			Group obj = (string.Equals(palette, "alien", StringComparison.OrdinalIgnoreCase) ? Alien : (string.Equals(palette, "phoenix", StringComparison.OrdinalIgnoreCase) ? Phoenix : null));
			if (obj == null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("[Decal] palette " + palette + " -> none (this palette ships without a decal)."));
				}
				Clear();
				return;
			}
			_active = obj;
			int num = ((EggstendedPlayPlugin.DecalsRandom == null || EggstendedPlayPlugin.DecalsRandom.Value) ? Random.Range(0, obj.Names.Length) : 0);
			if (num == obj.LastPick && obj.Names.Length > 1)
			{
				num = (num + 1) % obj.Names.Length;
			}
			ManualLogSource log2 = EggstendedPlayPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)$"[Decal] palette {palette} -> set of {obj.Names.Length}; picking one at random.");
			}
			Apply(obj, num);
		}

		internal static void Force(int index)
		{
			if (_active != null)
			{
				Apply(_active, index);
			}
		}

		private static void Apply(Group group, int index)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			index = (index % group.Names.Length + group.Names.Length) % group.Names.Length;
			Texture2D val = group.Cache[index];
			if ((Object)(object)val == (Object)null)
			{
				string text = Path.Combine(Folder, group.Names[index]);
				if (!File.Exists(text))
				{
					ManualLogSource log = EggstendedPlayPlugin.Log;
					if (log != null)
					{
						log.LogError((object)("[Decal] missing decal file: " + text));
					}
					return;
				}
				val = new Texture2D(2, 2, (TextureFormat)4, true)
				{
					name = group.Names[index],
					wrapMode = (TextureWrapMode)0,
					filterMode = (FilterMode)1
				};
				if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text), false))
				{
					ManualLogSource log2 = EggstendedPlayPlugin.Log;
					if (log2 != null)
					{
						log2.LogError((object)("[Decal] could not decode " + text));
					}
					return;
				}
				group.Cache[index] = val;
			}
			group.LastPick = index;
			_active = group;
			LastApplied = group.Names[index];
			Shader.SetGlobalTexture("_EggTexture", (Texture)(object)val);
			Shader.SetGlobalFloat("_EggTextureAmount", 1f);
			ManualLogSource log3 = EggstendedPlayPlugin.Log;
			if (log3 != null)
			{
				log3.LogInfo((object)$"[Decal] sheet {index + 1}/{group.Names.Length} '{group.Names[index]}' applied.");
			}
		}

		internal static void Clear()
		{
			if (LastApplied != "none")
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"[Decal] overlay cleared.");
				}
			}
			Shader.SetGlobalFloat("_EggTextureAmount", 0f);
			LastApplied = "none";
			_active = null;
		}

		internal static void Audit()
		{
			(string, Group)[] array = new(string, Group)[2]
			{
				("alien", Alien),
				("phoenix", Phoenix)
			};
			for (int i = 0; i < array.Length; i++)
			{
				(string, Group) tuple = array[i];
				string[] names = tuple.Item2.Names;
				foreach (string text in names)
				{
					string path = Path.Combine(Folder, text);
					ManualLogSource log = EggstendedPlayPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)("[Decal] audit " + tuple.Item1 + ": " + text + " " + (File.Exists(path) ? "present" : "MISSING")));
					}
				}
			}
		}
	}
	internal static class EggEnlargement
	{
		internal static float AppliedHeight;

		internal static int AppliedSeed;

		internal static float TargetRootY;

		internal static bool HasTargetRoot;

		private static float _baseRootY;

		private static float _baseHalf;

		private static bool _baseCaptured;

		private static bool _releaseHeightApplied;

		private static bool _standAdjusted;

		internal static int EggSeed;

		internal static bool EggSeedActive;

		internal static void ResetForScene()
		{
			AppliedHeight = 0f;
			AppliedSeed = 0;
			EggSeed = 0;
			EggSeedActive = false;
			_releaseHeightApplied = false;
			_standAdjusted = false;
			_baseCaptured = false;
			HasTargetRoot = false;
			TargetRootY = 0f;
		}

		internal static void SetSeed(int seed)
		{
			EggSeed = seed;
			EggSeedActive = true;
		}

		internal static IEnumerator ResizeAndRebuild(float totalHeight, bool forceRebuild)
		{
			if (!GameMode.IsStory || totalHeight <= 0f)
			{
				yield break;
			}
			if (forceRebuild && AppliedSeed == EggSeed && Mathf.Abs(AppliedHeight - totalHeight) < 0.01f)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"[Egg] already rebuilt at {totalHeight:0.###} m with seed {EggSeed}; skipping duplicate message.");
				}
				yield break;
			}
			float num = totalHeight * 0.5f;
			EggMeshGenerator val = Object.FindAnyObjectByType<EggMeshGenerator>();
			EggTerrain val2 = Object.FindAnyObjectByType<EggTerrain>();
			EggShellManager shell = Object.FindAnyObjectByType<EggShellManager>();
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)shell == (Object)null)
			{
				ManualLogSource log2 = EggstendedPlayPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)"[Egg] missing mesh/terrain/shell; overtime egg stays at its current size.");
				}
				yield break;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(EggMeshGenerator), "_height");
			if (fieldInfo == null)
			{
				ManualLogSource log3 = EggstendedPlayPlugin.Log;
				if (log3 != null)
				{
					log3.LogError((object)"[Egg] EggMeshGenerator._height is missing; enlargement skipped.");
				}
				yield break;
			}
			float num2 = (float)fieldInfo.GetValue(val);
			bool flag = num > num2 + 0.01f;
			if (!flag && !forceRebuild)
			{
				AppliedHeight = totalHeight;
				AppliedSeed = EggSeed;
				ManualLogSource log4 = EggstendedPlayPlugin.Log;
				if (log4 != null)
				{
					log4.LogInfo((object)$"[Egg] already at {num2 * 2f:0.###} m; no rebuild needed.");
				}
				yield break;
			}
			if (flag)
			{
				fieldInfo.SetValue(val, num);
				Transform val3 = (((Object)(object)((Component)val).transform.parent != (Object)null) ? ((Component)val).transform.parent : ((Component)val).transform);
				if (!_baseCaptured)
				{
					_baseCaptured = true;
					_baseRootY = val3.position.y;
					_baseHalf = num2;
				}
				Vector3 position = val3.position;
				val3.position = position + Vector3.up * (num - num2);
				TargetRootY = _baseRootY + (num - _baseHalf);
				HasTargetRoot = true;
				ManualLogSource log5 = EggstendedPlayPlugin.Log;
				if (log5 != null)
				{
					log5.LogInfo((object)($"[Egg] growing to {totalHeight:0.###} m tall, radius {val.Radius:0.###} m, " + $"root Y {position.y:0.###} -> {val3.position.y:0.###}."));
				}
			}
			Vector3Int val4 = default(Vector3Int);
			((Vector3Int)(ref val4))..ctor(7, 12, 7);
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(EggTerrain), "numChunks");
			if (fieldInfo2 != null)
			{
				Vector3Int val5 = (Vector3Int)fieldInfo2.GetValue(val2);
				int num3 = (flag ? Mathf.Max(((Vector3Int)(ref val5)).y, Mathf.CeilToInt((float)((Vector3Int)(ref val5)).y * num / num2)) : ((Vector3Int)(ref val5)).y);
				((Vector3Int)(ref val4))..ctor(((Vector3Int)(ref val5)).x, num3, ((Vector3Int)(ref val5)).z);
			}
			ManualLogSource log6 = EggstendedPlayPlugin.Log;
			if (log6 != null)
			{
				log6.LogInfo((object)$"[Egg] rebuilding overtime egg: grid {val4}, seed {EggSeed}.");
			}
			EggPalette.ResetForScene();
			EggPalette.ApplyOvertimeShell(shell);
			shell.RebuildForRecipe(shell.InitialChunkCount, 1f);
			yield return val2.RebuildForRecipe(val4);
			EggPalette.RefreshRenderers(shell);
			EggClawIntro val6 = Object.FindAnyObjectByType<EggClawIntro>();
			if ((Object)(object)val6 != (Object)null)
			{
				val6.RecaptureEggRest();
				if (!_releaseHeightApplied)
				{
					FieldInfo fieldInfo3 = AccessTools.Field(typeof(EggClawIntro), "_releaseHeight");
					if (fieldInfo3 != null)
					{
						float num4 = (float)fieldInfo3.GetValue(val6);
						float num5 = 1f;
						fieldInfo3.SetValue(val6, num4 + num5);
						_releaseHeightApplied = true;
						ManualLogSource log7 = EggstendedPlayPlugin.Log;
						if (log7 != null)
						{
							log7.LogInfo((object)$"[Egg] claw release height {num4:0.###} -> {num4 + num5:0.###} m.");
						}
					}
				}
			}
			EggVitals val7 = Object.FindAnyObjectByType<EggVitals>();
			if ((Object)(object)val7 != (Object)null)
			{
				val7.RecaptureEggCentre();
			}
			AdjustStand();
			AppliedHeight = totalHeight;
			AppliedSeed = EggSeed;
			ManualLogSource log8 = EggstendedPlayPlugin.Log;
			if (log8 != null)
			{
				log8.LogInfo((object)$"[Egg] overtime egg ready at {totalHeight:0.###} m, seed {EggSeed}.");
			}
		}

		private static void AdjustStand()
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if (_standAdjusted)
			{
				return;
			}
			_standAdjusted = true;
			EggStand val = Object.FindAnyObjectByType<EggStand>();
			if ((Object)(object)val == (Object)null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[Egg] no EggStand found; pedestal not rescaled.");
				}
				return;
			}
			float num = 0.92f;
			float num2 = 1f;
			Transform parent = ((Component)val).transform.parent;
			Transform val2 = (((Object)(object)parent != (Object)null) ? parent.Find("SM_EggStand") : null);
			if ((Object)(object)val2 == (Object)null)
			{
				MeshRenderer[] array = Object.FindObjectsByType<MeshRenderer>((FindObjectsSortMode)0);
				foreach (MeshRenderer val3 in array)
				{
					if ((Object)(object)val3 != (Object)null && ((Object)val3).name.IndexOf("SM_EggStand", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						val2 = ((Component)val3).transform;
						break;
					}
				}
			}
			if ((Object)(object)val2 != (Object)null)
			{
				Vector3 localScale = val2.localScale;
				Vector3 val4 = default(Vector3);
				((Vector3)(ref val4))..ctor(localScale.x * num, localScale.y * num2, localScale.z * num);
				val2.localScale = val4;
				ManualLogSource log2 = EggstendedPlayPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"[Egg] pedestal visual SM_EggStand scale {localScale} -> {val4} (radius {num:0.###}, height {num2:0.###}).");
				}
			}
			else
			{
				ManualLogSource log3 = EggstendedPlayPlugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)"[Egg] SM_EggStand visual not found; pedestal not rescaled.");
				}
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(EggStand), "radius");
			if (fieldInfo != null && fieldInfo.GetValue(val) is float num3)
			{
				fieldInfo.SetValue(val, num3 * num);
			}
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(EggStand), "height");
			if (fieldInfo2 != null && fieldInfo2.GetValue(val) is float num4)
			{
				fieldInfo2.SetValue(val, num4 * num2);
			}
		}

		private static string MarkerPath()
		{
			return SaveSlots.WorldPath(SaveSlots.SelectedSlot) + ".overtime";
		}

		internal static void WriteMarker(float height, int seed)
		{
			try
			{
				string text = RunRecord.RunId ?? "";
				File.WriteAllText(MarkerPath(), text + "\n" + height.ToString("R") + "\n" + seed);
				EggstendedPlayPlugin.Verbose("[Egg] overtime marker written.");
			}
			catch (Exception ex)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Egg] couldn't write the overtime marker: " + ex.Message));
				}
			}
		}

		internal static bool ReadMarker(out float height, out int seed)
		{
			height = 0f;
			seed = 0;
			try
			{
				string path = MarkerPath();
				if (!File.Exists(path))
				{
					return false;
				}
				string[] array = File.ReadAllLines(path);
				if (array.Length < 3)
				{
					return false;
				}
				string text = RunRecord.RunId ?? "";
				if (array[0] != text)
				{
					EggstendedPlayPlugin.Verbose("[Egg] overtime marker belongs to a different run; ignored.");
					return false;
				}
				height = float.Parse(array[1], CultureInfo.InvariantCulture);
				seed = int.Parse(array[2], CultureInfo.InvariantCulture);
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Egg] couldn't read the overtime marker: " + ex.Message));
				}
				return false;
			}
		}

		internal static void ApplyMarkerAfterLoad()
		{
			if ((Object)(object)EggstendedPlayPlugin.Instance != (Object)null)
			{
				((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(ApplyMarkerWhenReady());
			}
		}

		private static IEnumerator ApplyMarkerWhenReady()
		{
			for (int i = 0; i < 600; i++)
			{
				if (!SaveManager.LoadInProgress && (Object)(object)SaveManager.Instance != (Object)null && (Object)(object)Object.FindAnyObjectByType<EggTerrain>() != (Object)null)
				{
					break;
				}
				yield return null;
			}
			yield return null;
			if (ReadMarker(out var height, out var seed))
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"[Egg] overtime marker found ({height:0.###} m, seed {seed}); rebuilding after load.");
				}
				SetSeed(seed);
				yield return ResizeAndRebuild(height, forceRebuild: true);
			}
		}
	}
	[HarmonyPatch(typeof(EggClawIntro), "Play")]
	internal static class EggClawIntroPlayPatch
	{
		[HarmonyPrefix]
		private static void Prefix(EggClawIntro __instance)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			if (EggEnlargement.HasTargetRoot)
			{
				object? obj = AccessTools.Field(typeof(EggClawIntro), "_eggRoot")?.GetValue(__instance);
				Transform val = (Transform)((obj is Transform) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					Vector3 position = val.position;
					if (Mathf.Abs(position.y - EggEnlargement.TargetRootY) > 0.01f)
					{
						ManualLogSource log = EggstendedPlayPlugin.Log;
						if (log != null)
						{
							log.LogInfo((object)$"[Egg] claw play: correcting egg root Y {position.y:0.###} -> {EggEnlargement.TargetRootY:0.###}.");
						}
						val.position = new Vector3(position.x, EggEnlargement.TargetRootY, position.z);
					}
				}
			}
			__instance.RecaptureEggRest();
			FieldInfo fieldInfo = AccessTools.Field(typeof(EggClawIntro), "_eggRestY");
			if (fieldInfo != null)
			{
				ManualLogSource log2 = EggstendedPlayPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"[Egg] claw play: recaptured rest Y {fieldInfo.GetValue(__instance)}.");
				}
			}
		}
	}
	[HarmonyPatch(typeof(WorldSeed), "EggSalt")]
	internal static class WorldSeedEggSaltPatch
	{
		[HarmonyPostfix]
		private static void Postfix(string salt, ref string __result)
		{
			if (EggEnlargement.EggSeedActive && GameMode.IsStory)
			{
				__result = salt + "#overtime" + EggEnlargement.EggSeed;
			}
		}
	}
	[HarmonyPatch(typeof(BreakManager), "ResetToStartOfDay")]
	internal static class BreakManagerResetToStartOfDayPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (!OvertimeFlow.SuppressMarker)
			{
				EggEnlargement.ApplyMarkerAfterLoad();
			}
		}
	}
	internal static class EggPalette
	{
		private struct Look
		{
			public string BaseHex;

			public string Surface1Hex;

			public string DarkHex;

			public string LightHex;

			public string SpeckleHex;

			public float SpeckleScale;

			public float Strength;

			public float Mottle;

			public float Normal;

			public Color Base => Parse(BaseHex, Color.white);

			public Color Dark => Parse(DarkHex, Color.white);

			public Color Light => Parse(LightHex, Color.white);

			public Color Speckle => Parse(SpeckleHex, Color.white);

			public Color Surface1 => Parse(string.IsNullOrEmpty(Surface1Hex) ? BaseHex : Surface1Hex, Color.white);
		}

		private static readonly List<Material> Made = new List<Material>();

		private static EggShellManager _appliedTo;

		private static Material _shellMat;

		private static Material _peelMat;

		internal static readonly string[] Presets = new string[6] { "robin", "redbird", "phoenix", "jade", "alien", "custom" };

		private static readonly Dictionary<string, Look> Looks = new Dictionary<string, Look>
		{
			["robin"] = new Look
			{
				BaseHex = "#BFE9EC",
				DarkHex = "#A8DDE2",
				LightHex = "#DDF6F7",
				SpeckleHex = "#A24E2E",
				SpeckleScale = 60f,
				Strength = 1f,
				Mottle = 0.35f,
				Normal = 0.2f
			},
			["redbird"] = new Look
			{
				BaseHex = "#F6F2F2",
				DarkHex = "#EAE3E4",
				LightHex = "#FFFFFF",
				SpeckleHex = "#FF5A5A",
				SpeckleScale = 30f,
				Strength = 1.15f,
				Mottle = 0.06f,
				Normal = 0.08f
			},
			["phoenix"] = new Look
			{
				BaseHex = "#FFFFFF",
				Surface1Hex = "#FFE84A",
				DarkHex = "#EFEDE8",
				LightHex = "#FFFFFF",
				SpeckleHex = "#FF7A1A",
				SpeckleScale = 42f,
				Strength = 1.1f,
				Mottle = 0.45f,
				Normal = 0.12f
			},
			["jade"] = new Look
			{
				BaseHex = "#A9DFB8",
				DarkHex = "#8AC79B",
				LightHex = "#CFF0D6",
				SpeckleHex = "#EAF6EA",
				SpeckleScale = 22f,
				Strength = 0.3f,
				Mottle = 0.1f,
				Normal = 0.15f
			},
			["alien"] = new Look
			{
				BaseHex = "#7FD8E8",
				DarkHex = "#57B7C9",
				LightHex = "#BCEFF8",
				SpeckleHex = "#E8FDFF",
				SpeckleScale = 16f,
				Strength = 0.45f,
				Mottle = 0.12f,
				Normal = 0.18f
			}
		};

		private static string _lastResolved;

		private static Look _resolvedLook;

		private static readonly string[] RandomPresets = new string[3] { "robin", "phoenix", "alien" };

		private static bool _logged;

		internal static string ActivePaletteName { get; private set; } = "robin";

		internal static void Init()
		{
		}

		internal static void ResetForScene()
		{
			_appliedTo = null;
			_shellMat = null;
			_peelMat = null;
			for (int i = 0; i < Made.Count; i++)
			{
				if ((Object)(object)Made[i] != (Object)null)
				{
					Object.Destroy((Object)(object)Made[i]);
				}
			}
			Made.Clear();
		}

		internal static void ApplyOvertimeShell(EggShellManager shell)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)shell == (Object)null || (Object)(object)_appliedTo == (Object)(object)shell || EggstendedPlayPlugin.RobinEggShell == null || !EggstendedPlayPlugin.RobinEggShell.Value)
			{
				return;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(EggShellManager), "_shellMaterial");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(EggShellManager), "_peelableMaterial");
			object? obj = fieldInfo?.GetValue(shell);
			Material val = (Material)((obj is Material) ? obj : null);
			if ((Object)(object)val == (Object)null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[Shell] no shell material to recolour.");
				}
				return;
			}
			_resolvedLook = ResolveLook(out var chosen);
			ActivePaletteName = chosen;
			ManualLogSource log2 = EggstendedPlayPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)("[Shell] palette chosen: " + chosen + "."));
			}
			Material val2 = Recolour(val, "MAT_EggShell_Overtime");
			object? obj2 = fieldInfo2?.GetValue(shell);
			Material val3 = (Material)((obj2 is Material) ? obj2 : null);
			Material val4 = (((Object)(object)val3 != (Object)null) ? Recolour(val3, "MAT_EggShell_Peelable_Overtime") : val2);
			fieldInfo.SetValue(shell, val2);
			if (fieldInfo2 != null)
			{
				fieldInfo2.SetValue(shell, val4);
			}
			_shellMat = val2;
			_peelMat = val4;
			_appliedTo = shell;
			RefreshRenderers(shell);
			EggDecals.ApplyForPalette(chosen);
			FleshTint.ApplyForPalette(chosen);
			LogMaterialOnce(val2);
			ManualLogSource log3 = EggstendedPlayPlugin.Log;
			if (log3 != null)
			{
				log3.LogInfo((object)(string.Format("[Shell] palette applied: source={0}, hasBase={1}, ", ((Object)val).name, val2.HasProperty("_BaseColor")) + string.Format("base={0}, speckle={1}, ", val2.GetColor("_BaseColor"), val2.GetColor("_SurfaceColor1")) + $"scale {EggstendedPlayPlugin.EggSpeckleScale2.Value:0.#}."));
			}
		}

		internal static void RefreshRenderers(EggShellManager shell)
		{
			if ((Object)(object)shell == (Object)null)
			{
				return;
			}
			Material val = (Material)(((object)_shellMat) ?? ((object)/*isinst with value type is only supported in some contexts*/));
			Material val2 = (Material)(((object)_peelMat) ?? ((object)/*isinst with value type is only supported in some contexts*/));
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Transform val3 = (((Object)(object)((Component)shell).transform.parent != (Object)null) ? ((Component)shell).transform.parent : ((Component)shell).transform);
			MeshRenderer[] componentsInChildren = ((Component)val3).GetComponentsInChildren<MeshRenderer>(true);
			int num = 0;
			string text = null;
			MeshRenderer[] array = componentsInChildren;
			foreach (MeshRenderer val4 in array)
			{
				if ((Object)(object)val4 == (Object)null)
				{
					continue;
				}
				Material sharedMaterial = ((Renderer)val4).sharedMaterial;
				if ((Object)(object)sharedMaterial == (Object)null)
				{
					continue;
				}
				if (((Object)sharedMaterial).name.IndexOf("EggShell_Peelable", StringComparison.Ordinal) >= 0)
				{
					if ((Object)(object)val2 != (Object)null && (Object)(object)sharedMaterial != (Object)(object)val2)
					{
						((Renderer)val4).sharedMaterial = val2;
						num++;
						if (text == null)
						{
							text = ((Object)val4).name + "->" + ((Object)val2).name;
						}
					}
				}
				else if (((Object)sharedMaterial).name.IndexOf("EggShell", StringComparison.Ordinal) >= 0 && (Object)(object)sharedMaterial != (Object)(object)val)
				{
					((Renderer)val4).sharedMaterial = val;
					num++;
					if (text == null)
					{
						text = ((Object)val4).name + "->" + ((Object)val).name;
					}
				}
			}
			for (int j = 0; j < 14; j++)
			{
				MeshRenderer bucketRenderer = shell.GetBucketRenderer(j);
				if ((Object)(object)bucketRenderer != (Object)null && (Object)(object)((Renderer)bucketRenderer).sharedMaterial != (Object)(object)val)
				{
					((Renderer)bucketRenderer).sharedMaterial = val;
					num++;
				}
			}
			if (num == 0)
			{
				array = Object.FindObjectsByType<MeshRenderer>((FindObjectsSortMode)0);
				foreach (MeshRenderer val5 in array)
				{
					Material val6 = (((Object)(object)val5 != (Object)null) ? ((Renderer)val5).sharedMaterial : null);
					if (!((Object)(object)val6 == (Object)null))
					{
						string name = ((Object)val6).name;
						if (name.IndexOf("EggShell_Peelable", StringComparison.Ordinal) >= 0 && (Object)(object)val2 != (Object)null)
						{
							((Renderer)val5).sharedMaterial = val2;
							num++;
						}
						else if (name.IndexOf("EggShell", StringComparison.Ordinal) >= 0)
						{
							((Renderer)val5).sharedMaterial = val;
							num++;
						}
					}
				}
			}
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)($"[Shell] refreshed {num} renderer(s) under {((Object)val3).name}" + ((text != null) ? ("; first " + text) : "") + "."));
			}
		}

		private static Material Recolour(Material source, string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			Material val = new Material(source)
			{
				name = name
			};
			Made.Add(val);
			Look resolvedLook = _resolvedLook;
			SetColor(val, "_BaseColor", resolvedLook.Base);
			SetColor(val, "_Color", resolvedLook.Base);
			SetColor(val, "_BaseColorDark", resolvedLook.Dark);
			SetColor(val, "_BaseColorLight", resolvedLook.Light);
			SetColor(val, "_SurfaceColor1", resolvedLook.Surface1);
			SetColor(val, "_SurfaceColor2", resolvedLook.Speckle);
			SetFloat(val, "_SurfaceScale1", 8f);
			SetFloat(val, "_SurfaceScale2", resolvedLook.SpeckleScale);
			SetFloat(val, "_SurfaceIntensity1", resolvedLook.Mottle);
			SetFloat(val, "_SurfaceIntensity2", resolvedLook.Strength);
			SetFloat(val, "_SurfaceBlend", resolvedLook.Mottle);
			SetFloat(val, "_PatternIntensity", 1.5f * resolvedLook.Strength);
			SetFloat(val, "_NoiseScale", 20f);
			SetFloat(val, "_NormalStrength", resolvedLook.Normal);
			return val;
		}

		private static Look ResolveLook(out string chosen)
		{
			string text = (EggstendedPlayPlugin.ShellPalette?.Value ?? "robin").Trim().ToLowerInvariant();
			if (text == "random")
			{
				text = RandomPresets[Random.Range(0, RandomPresets.Length)];
			}
			if (text == "jade")
			{
				text = "phoenix";
			}
			chosen = text;
			if (text == "custom")
			{
				Look result = new Look
				{
					BaseHex = EggstendedPlayPlugin.EggBaseColor.Value,
					DarkHex = EggstendedPlayPlugin.EggBaseDark.Value,
					LightHex = EggstendedPlayPlugin.EggBaseLight.Value,
					SpeckleHex = EggstendedPlayPlugin.EggSpeckleColor.Value,
					SpeckleScale = Mathf.Max(1f, EggstendedPlayPlugin.EggSpeckleScale2.Value),
					Strength = Mathf.Max(0f, EggstendedPlayPlugin.EggSpeckleStrength.Value),
					Mottle = Mathf.Clamp01(EggstendedPlayPlugin.EggMottle.Value),
					Normal = EggstendedPlayPlugin.EggNormalStrength.Value
				};
				if (_lastResolved != "custom")
				{
					ManualLogSource log = EggstendedPlayPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)"[Shell] palette custom: using the per-colour config keys.");
					}
					_lastResolved = "custom";
				}
				return result;
			}
			if (!Looks.TryGetValue(text, out var value))
			{
				ManualLogSource log2 = EggstendedPlayPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("[Shell] unknown palette '" + text + "'; using robin. Known: " + string.Join(", ", Presets) + "."));
				}
				text = "robin";
				value = Looks["robin"];
			}
			if (_lastResolved != text)
			{
				ManualLogSource log3 = EggstendedPlayPlugin.Log;
				if (log3 != null)
				{
					log3.LogInfo((object)("[Shell] palette " + text + ": base=" + value.BaseHex + ", speckle=" + value.SpeckleHex + ", " + $"scale={value.SpeckleScale:0.#}, strength={value.Strength:0.##}."));
				}
				_lastResolved = text;
			}
			return value;
		}

		private static void LogMaterialOnce(Material mat)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			if (_logged || (Object)(object)mat == (Object)null || (Object)(object)mat.shader == (Object)null)
			{
				return;
			}
			_logged = true;
			Shader shader = mat.shader;
			int propertyCount = shader.GetPropertyCount();
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append($"[Shell] shader={((Object)shader).name} properties={propertyCount}");
			for (int i = 0; i < propertyCount; i++)
			{
				string propertyName = shader.GetPropertyName(i);
				ShaderPropertyType propertyType = shader.GetPropertyType(i);
				string value = string.Empty;
				if ((int)propertyType == 4)
				{
					Texture texture = mat.GetTexture(propertyName);
					value = " (" + (((Object)(object)texture != (Object)null) ? ((Object)texture).name : "null") + ")";
				}
				stringBuilder.Append("\n  ").Append(propertyName).Append(" : ")
					.Append(propertyType)
					.Append(value);
			}
			stringBuilder.Append("\n  keywords: ").Append(string.Join(",", mat.shaderKeywords));
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)stringBuilder.ToString());
			}
		}

		internal static bool ForceReapply(out string message)
		{
			EggShellManager val = Object.FindAnyObjectByType<EggShellManager>();
			if ((Object)(object)val == (Object)null)
			{
				message = "No EggShellManager in this scene (overtime egg is not built yet).";
				return false;
			}
			if (EggstendedPlayPlugin.RobinEggShell == null || !EggstendedPlayPlugin.RobinEggShell.Value)
			{
				message = "Shell recolour is off ([Shell] RobinEgg = false).";
				return false;
			}
			ResetForScene();
			ApplyOvertimeShell(val);
			message = "Shell re-coloured with palette '" + (EggstendedPlayPlugin.ShellPalette?.Value ?? "robin") + "'.";
			return true;
		}

		private static Color Parse(string hex, Color fallback)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			//IL_001e: 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)
			Color result = default(Color);
			if (!string.IsNullOrEmpty(hex) && ColorUtility.TryParseHtmlString(hex, ref result))
			{
				if ((int)QualitySettings.activeColorSpace != 1)
				{
					return result;
				}
				return ((Color)(ref result)).linear;
			}
			return fallback;
		}

		private static void SetColor(Material mat, string property, Color color)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (mat.HasProperty(property))
			{
				mat.SetColor(property, color);
			}
		}

		private static void SetFloat(Material mat, string property, float value)
		{
			if (mat.HasProperty(property))
			{
				mat.SetFloat(property, value);
			}
		}
	}
	[BepInPlugin("Grokent.CrackEggstendedPlay", "Eggstended Play", "0.1.2")]
	public sealed class EggstendedPlayPlugin : BaseUnityPlugin
	{
		public const string Guid = "Grokent.CrackEggstendedPlay";

		public const string Version = "0.1.2";

		internal const float EggHeight = 24f;

		internal const float CreditsSkipHoldSeconds = 1.2f;

		internal const float CreditsFallbackSeconds = 600f;

		internal const bool FastCredits = false;

		internal const bool VerboseLogging = false;

		internal const float ReleaseHeightExtra = 1f;

		internal const float StandRadiusScale = 0.92f;

		internal const float StandHeightScale = 1f;

		internal const bool BypassEnabled = true;

		internal const float BypassHeight = 0f;

		internal const float BypassRight = 0.08f;

		internal const float BypassForward = 0.03f;

		internal static EggstendedPlayPlugin Instance;

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> RobinEggShell;

		internal static ConfigEntry<string> ShellPalette;

		internal static ConfigEntry<string> EggBaseColor;

		internal static ConfigEntry<string> EggBaseDark;

		internal static ConfigEntry<string> EggBaseLight;

		internal static ConfigEntry<string> EggSpeckleColor;

		internal static ConfigEntry<float> EggSpeckleScale2;

		internal static ConfigEntry<float> EggSpeckleStrength;

		internal static ConfigEntry<float> EggMottle;

		internal static ConfigEntry<float> EggNormalStrength;

		internal static ConfigEntry<bool> DecalsEnabled;

		internal static ConfigEntry<bool> DecalsRandom;

		private void Awake()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Config.Remove(new ConfigDefinition("Egg", "RestLift"));
			((BaseUnityPlugin)this).Config.Remove(new ConfigDefinition("Shell", "SpeckleScale"));
			((BaseUnityPlugin)this).Config.Remove(new ConfigDefinition("Shell", "SpeckleColor2"));
			ConfigDefinition[] array = (ConfigDefinition[])(object)new ConfigDefinition[12]
			{
				new ConfigDefinition("Egg", "TotalHeight"),
				new ConfigDefinition("Egg", "ReleaseHeightExtra"),
				new ConfigDefinition("Stand", "RadiusScale"),
				new ConfigDefinition("Stand", "HeightScale"),
				new ConfigDefinition("Bypass", "Enabled"),
				new ConfigDefinition("Bypass", "Right"),
				new ConfigDefinition("Bypass", "Forward"),
				new ConfigDefinition("Bypass", "Height"),
				new ConfigDefinition("Debug", "VerboseLogging"),
				new ConfigDefinition("Debug", "FastCredits"),
				new ConfigDefinition("Credits", "SkipHoldSeconds"),
				new ConfigDefinition("Credits", "FallbackSeconds")
			};
			foreach (ConfigDefinition val in array)
			{
				((BaseUnityPlugin)this).Config.Remove(val);
			}
			((BaseUnityPlugin)this).Config.Save();
			RobinEggShell = ((BaseUnityPlugin)this).Config.Bind<bool>("Shell", "RobinEgg", true, "Recolour the overtime egg shell. Off leaves the vanilla shell. When on, the Palette key chooses the look.");
			ShellPalette = ((BaseUnityPlugin)this).Config.Bind<string>("Shell", "Palette", "random", "Shell look: robin (pale blue, rust speckles), redbird (white, bright red speckles), phoenix (white with yellow mottling and orange speckles), alien (cyan shell), custom (uses the BaseColor/SpeckleColor/Mottle keys below), or random (robin, redbird, phoenix or alien chosen per egg).");
			EggBaseColor = ((BaseUnityPlugin)this).Config.Bind<string>("Shell", "BaseColor", "#BFE9EC", "Robin egg base colour (HTML hex).");
			EggBaseDark = ((BaseUnityPlugin)this).Config.Bind<string>("Shell", "BaseColorDark", "#A8DDE2", "Robin egg shadow colour (HTML hex).");
			EggBaseLight = ((BaseUnityPlugin)this).Config.Bind<string>("Shell", "BaseColorLight", "#DDF6F7", "Robin egg highlight colour (HTML hex).");
			EggSpeckleColor = ((BaseUnityPlugin)this).Config.Bind<string>("Shell", "SpeckleColor", "#A24E2E", "Speckle colour (HTML hex).");
			EggSpeckleScale2 = ((BaseUnityPlugin)this).Config.Bind<float>("Shell", "SpeckleScale2", 60f, "Secondary speckle frequency. Higher is finer/denser.");
			EggSpeckleStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Shell", "SpeckleStrength", 1f, "Speckle contrast multiplier.");
			EggMottle = ((BaseUnityPlugin)this).Config.Bind<float>("Shell", "Mottle", 0.35f, "Strength of the dark shell mottling. Lower is cleaner blue.");
			EggNormalStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Shell", "NormalStrength", 0.2f, "Surface normal strength. Lower flattens the black mottled shading.");
			DecalsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Decal", "Enabled", true, "Apply a decal matching the palette (alien glyphs, phoenix embers).");
			DecalsRandom = ((BaseUnityPlugin)this).Config.Bind<bool>("Decal", "Random", true, "Pick a sheet at random for each new egg.");
			new Harmony("Grokent.CrackEggstendedPlay").PatchAll();
			OvertimeFlow.Init();
			SelfCheck.Run();
			EggDecals.Audit();
			EggPalette.Init();
			SceneManager.sceneLoaded += OnSceneLoaded;
			Log.LogInfo((object)"Eggstended Play loaded.");
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			OvertimeFlow.ResetForNewScene();
			EggEnlargement.ResetForScene();
			EggPalette.ResetForScene();
			EndUi.ResetBlackout();
			PuzzleBypassFlow.ResetForScene();
			((MonoBehaviour)this).StartCoroutine(PuzzleBypassFlow.SpawnWhenReady());
			((MonoBehaviour)this).StartCoroutine(SelfCheck.LogEggFacts());
		}

		private void Update()
		{
			OvertimeFlow.EnsureHandlers();
			PuzzleBypassFlow.Update();
		}

		internal static void Verbose(string message)
		{
		}
	}
	internal static class EndingProps
	{
		internal static bool ToolboxHintSuppressed { get; private set; }

		internal static void ResetServer()
		{
			ExitDoor[] array = Object.FindObjectsByType<ExitDoor>((FindObjectsSortMode)0);
			foreach (ExitDoor val in array)
			{
				if (!((Object)(object)val == (Object)null))
				{
					Set(val, "_taken", false);
					val.Network_open = false;
					ResetDoorVisuals(val);
				}
			}
			CoopOven val2 = Object.FindAnyObjectByType<CoopOven>();
			if ((Object)(object)val2 != (Object)null)
			{
				ResetOven(val2);
			}
			ChickenBox val3 = Object.FindAnyObjectByType<ChickenBox>();
			if ((Object)(object)val3 != (Object)null)
			{
				ResetBox(val3);
			}
		}

		internal static void ResetClients()
		{
			ExitDoor[] array = Object.FindObjectsByType<ExitDoor>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				ResetDoorVisuals(array[i]);
			}
			ChickenBox val = Object.FindAnyObjectByType<ChickenBox>();
			if ((Object)(object)val != (Object)null)
			{
				ResetBoxVisuals(val);
			}
			ClearToolboxHint();
		}

		private static void ClearToolboxHint()
		{
			ToolboxHintSuppressed = true;
			HudWaypoints.Clear("toolbox");
			Tips.MarkSeenQuietly("Hint_ToolboxRefill");
			ToolboxHintWaypoint[] array = Object.FindObjectsByType<ToolboxHintWaypoint>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			ToolboxHintWaypoint[] array2 = array;
			foreach (ToolboxHintWaypoint val in array2)
			{
				if (!((Object)(object)val == (Object)null))
				{
					Set(val, "_hinted", true);
					((Behaviour)val).enabled = false;
				}
			}
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"[Overtime] toolbox hint suppressed ({array.Length} instance(s) found).");
			}
		}

		private static void ResetDoorVisuals(ExitDoor door)
		{
			Transform val = Get<Transform>(door, "gate");
			if ((Object)(object)val != (Object)null)
			{
				((Component)val).gameObject.SetActive(true);
			}
			Animation val2 = Get<Animation>(door, "shatteredGate");
			if ((Object)(object)val2 != (Object)null)
			{
				val2.Stop();
				val2.Rewind();
				((Component)val2).gameObject.SetActive(false);
			}
			GameObject val3 = Get<GameObject>(door, "explosion");
			if ((Object)(object)val3 != (Object)null)
			{
				val3.SetActive(false);
			}
			Light val4 = Get<Light>(door, "glowLight");
			if ((Object)(object)val4 != (Object)null)
			{
				val4.intensity = 0f;
			}
			Light val5 = Get<Light>(door, "impactFlash");
			if ((Object)(object)val5 != (Object)null)
			{
				val5.intensity = 0f;
			}
		}

		private static void ResetOven(CoopOven oven)
		{
			((MonoBehaviour)oven).StopAllCoroutines();
			Set(oven, "_sequence", null);
			Set(oven, "_cookingForReal", false);
			Set(oven, "_piecesRevealed", false);
			Set(oven, "_power", 0f);
			Set(oven, "_steamPower", 0f);
			Set(oven, "_firePower", 0f);
			CookedChicken val = Get<CookedChicken>(oven, "_spawnedChicken");
			if ((Object)(object)val != (Object)null)
			{
				Set(oven, "_spawnedChicken", null);
				if ((Object)(object)((Component)val).gameObject != (Object)null)
				{
					NetworkServer.Destroy(((Component)val).gameObject);
				}
			}
			GameObject val2 = Get<GameObject>(oven, "_liveChicken");
			if ((Object)(object)val2 != (Object)null)
			{
				val2.SetActive(true);
			}
			GameObject val3 = Get<GameObject>(oven, "_cookedChicken");
			if ((Object)(object)val3 != (Object)null)
			{
				val3.SetActive(false);
			}
			List<ParticleSystem> list = Get<List<ParticleSystem>>(oven, "_steamSystems");
			if (list != null)
			{
				foreach (ParticleSystem item in list)
				{
					if ((Object)(object)item != (Object)null)
					{
						item.Stop(true, (ParticleSystemStopBehavior)0);
					}
				}
			}
			List<ParticleSystem> list2 = Get<List<ParticleSystem>>(oven, "_particlesToStop");
			if (list2 != null)
			{
				foreach (ParticleSystem item2 in list2)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						item2.Stop(true, (ParticleSystemStopBehavior)0);
					}
				}
			}
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[Props] oven reset; accepts a chicken again.");
			}
		}

		private static void ResetBox(ChickenBox box)
		{
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ChickenBox), "Network_state");
			if (propertyInfo != null)
			{
				propertyInfo.SetValue(box, Enum.ToObject(propertyInfo.PropertyType, 0));
			}
			ResetBoxVisuals(box);
		}

		private static void ResetBoxVisuals(ChickenBox box)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			Transform val = Get<Transform>(box, "_movingBox");
			Vector3 vector = GetVector(box, "_restPos");
			if ((Object)(object)val != (Object)null)
			{
				LeanTween.cancel(((Component)val).gameObject);
				val.position = vector;
				val.rotation = Quaternion.identity;
				val.localScale = Vector3.one;
			}
			Set(box, "_shown", false);
			GameObject val2 = Get<GameObject>(box, "_boxedChicken");
			if ((Object)(object)val2 != (Object)null)
			{
				val2.SetActive(false);
			}
			Animator val3 = Get<Animator>(box, "_lidAnimator");
			if ((Object)(object)val3 != (Object)null)
			{
				val3.Rebind();
				val3.Update(0f);
			}
			object obj = AccessTools.Field(typeof(ChickenBox), "_roll")?.GetValue(box);
			if (obj != null)
			{
				AccessTools.Method(obj.GetType(), "Stop", new Type[1] { typeof(float) }, (Type[])null)?.Invoke(obj, new object[1] { 0.2f });
			}
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ChickenBox), "Network_boxedPos");
			PropertyInfo propertyInfo2 = AccessTools.Property(typeof(ChickenBox), "Network_boxedRot");
			PropertyInfo propertyInfo3 = AccessTools.Property(typeof(ChickenBox), "Network_boxedScale");
			propertyInfo?.SetValue(box, vector);
			propertyInfo2?.SetValue(box, Quaternion.identity);
			propertyInfo3?.SetValue(box, Vector3.one);
		}

		private static T Get<T>(object target, string field) where T : class
		{
			return AccessTools.Field(target.GetType(), field)?.GetValue(target) as T;
		}

		private static Vector3 GetVector(object target, string field)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			FieldInfo fieldInfo = AccessTools.Field(target.GetType(), field);
			if (!(fieldInfo != null))
			{
				return Vector3.zero;
			}
			return (Vector3)fieldInfo.GetValue(target);
		}

		private static void Set(object target, string field, object value)
		{
			AccessTools.Field(target.GetType(), field)?.SetValue(target, value);
		}
	}
	internal static class EndUi
	{
		private static readonly Dictionary<GameEndUI, Vector2> RollRest = new Dictionary<GameEndUI, Vector2>();

		private static readonly HashSet<GameEndUI> Captured = new HashSet<GameEndUI>();

		private static GameObject _blackout;

		internal static CanvasGroup Menu(GameEndUI ui)
		{
			return Field<CanvasGroup>(ui, "menu");
		}

		internal static bool ContentActive(GameEndUI ui)
		{
			GameObject val = Field<GameObject>(ui, "content");
			if ((Object)(object)val != (Object)null)
			{
				return val.activeInHierarchy;
			}
			return false;
		}

		internal static void EnsureSkipPrompt(GameEndUI ui)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00ac: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ui == (Object)null))
			{
				Transform val = FindSkipPrompt(ui);
				if ((Object)(object)val != (Object)null)
				{
					((Object)val).name = "EggstendedSkipPrompt_Old";
					Object.Destroy((Object)(object)((Component)val).gameObject);
				}
				TMP_Text val2 = Field<TMP_Text>(ui, "speedrunText") ?? Field<TMP_Text>(ui, "endingLabel");
				GameObject val3 = new GameObject("EggstendedSkipPrompt", new Type[4]
				{
					typeof(RectTransform),
					typeof(CanvasRenderer),
					typeof(TextMeshProUGUI),
					typeof(Canvas)
				});
				RectTransform val4 = (RectTransform)val3.transform;
				((Transform)val4).SetParent(((Component)ui).transform, false);
				PlacePrompt(val4);
				Canvas component = val3.GetComponent<Canvas>();
				component.overrideSorting = true;
				component.sortingOrder = 30000;
				val3.transform.SetAsLastSibling();
				TextMeshProUGUI component2 = val3.GetComponent<TextMeshProUGUI>();
				if ((Object)(object)val2 != (Object)null)
				{
					((TMP_Text)component2).font = val2.font;
				}
				((TMP_Text)component2).text = "HOLD SPACE TO SKIP";
				((TMP_Text)component2).fontSize = 20f;
				((Graphic)component2).color = new Color(1f, 1f, 1f, 0.72f);
				((TMP_Text)component2).alignment = (TextAlignmentOptions)514;
				((Graphic)component2).raycastTarget = false;
				val3.SetActive(false);
				EggstendedPlayPlugin.Verbose("[Overtime] skip prompt added to the credits.");
			}
		}

		internal static void SetSkipPromptActive(GameEndUI ui, bool active)
		{
			Transform val = FindSkipPrompt(ui);
			if ((Object)(object)val != (Object)null)
			{
				((Component)val).gameObject.SetActive(active);
				if (active)
				{
					val.SetAsLastSibling();
				}
			}
		}

		private static Transform FindSkipPrompt(GameEndUI ui)
		{
			if ((Object)(object)ui == (Object)null)
			{
				return null;
			}
			Transform[] componentsInChildren = ((Component)ui).GetComponentsInChildren<Transform>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null && ((Object)componentsInChildren[i]).name == "EggstendedSkipPrompt")
				{
					return componentsInChildren[i];
				}
			}
			return null;
		}

		private static void PlacePrompt(RectTransform rect)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			rect.anchorMin = new Vector2(0.5f, 0f);
			rect.anchorMax = new Vector2(0.5f, 0f);
			rect.pivot = new Vector2(0.5f, 0f);
			rect.anchoredPosition = new Vector2(0f, 36f);
			rect.sizeDelta = new Vector2(700f, 40f);
		}

		internal static void CaptureRoll(GameEndUI ui)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ui == (Object)null) && !Captured.Contains(ui))
			{
				RectTransform val = Field<RectTransform>(ui, "roll");
				if ((Object)(object)val != (Object)null)
				{
					RollRest[ui] = val.anchoredPosition;
				}
				Captured.Add(ui);
			}
		}

		internal static void DisableMenu(GameEndUI ui)
		{
			CanvasGroup val = Menu(ui);
			if ((Object)(object)val != (Object)null)
			{
				val.blocksRaycasts = false;
				val.interactable = false;
			}
		}

		internal static void HideCompletely(GameEndUI ui)
		{
			if (!((Object)(object)ui == (Object)null))
			{
				((MonoBehaviour)ui).StopAllCoroutines();
				SetSkipPromptActive(ui, active: false);
				GameObject val = Field<GameObject>(ui, "content");
				if ((Object)(object)val != (Object)null)
				{
					val.SetActive(false);
				}
				CanvasGroup val2 = Field<CanvasGroup>(ui, "group");
				if ((Object)(object)val2 != (Object)null)
				{
					val2.alpha = 0f;
					val2.blocksRaycasts = false;
					val2.interactable = false;
				}
				CanvasGroup val3 = Field<CanvasGroup>(ui, "menu");
				if ((Object)(object)val3 != (Object)null)
				{
					val3.alpha = 0f;
					val3.blocksRaycasts = false;
					val3.interactable = false;
					((Component)val3).gameObject.SetActive(false);
				}
				RectTransform val4 = Field<RectTransform>(ui, "roll");
				if ((Object)(object)val4 != (Object)null)
				{
					((Component)val4).gameObject.SetActive(false);
				}
				CanvasGroup val5 = Field<CanvasGroup>(ui, "timelapsePanel");
				if ((Object)(object)val5 != (Object)null)
				{
					val5.alpha = 0f;
					val5.blocksRaycasts = false;
					((Component)val5).gameObject.SetActive(false);
				}
			}
		}

		internal static void ResetForNextRun(GameEndUI ui)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ui == (Object)null)
			{
				return;
			}
			HideCompletely(ui);
			Transform val = Field<Transform>(ui, "statsParent");
			if ((Object)(object)val != (Object)null)
			{
				for (int num = val.childCount - 1; num >= 0; num--)
				{
					Object.Destroy((Object)(object)((Component)val.GetChild(num)).gameObject);
				}
			}
			RectTransform val2 = Field<RectTransform>(ui, "roll");
			if ((Object)(object)val2 != (Object)null && RollRest.TryGetValue(ui, out var value))
			{
				val2.anchoredPosition = value;
			}
			CanvasGroup val3 = Field<CanvasGroup>(ui, "_rollGroup");
			if ((Object)(object)val3 != (Object)null)
			{
				val3.alpha = 0f;
			}
			SetField(ui, "_playing", false);
			SetField(ui, "_timelapseStarted", false);
			SetField(ui, "_timelapseDone", false);
			SetField(ui, "_newBest", false);
			SetField(ui, "_rank", 0);
			SetField(ui, "_names", null);
			SetField(ui, "_values", null);
			FieldInfo fieldInfo = AccessTools.Field(typeof(GameEndUI), "_rankState");
			if (fieldInfo != null)
			{
				fieldInfo.SetValue(ui, Enum.ToObject(fieldInfo.FieldType, 0));
			}
		}

		internal static void Wake()
		{
			GameEndUI val = Object.FindAnyObjectByType<GameEndUI>();
			if ((Object)(object)val != (Object)null)
			{
				ResetForNextRun(val);
			}
			GameMenu val2 = Object.FindAnyObjectByType<GameMenu>();
			if ((Object)(object)val2 != (Object)null && val2.IsOpen)
			{
				val2.Close();
			}
			Player local = Player.Local;
			if ((Object)(object)local != (Object)null)
			{
				((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(EnsureAwakeFallback(local));
			}
			else if ((Object)(object)EggstendedPlayPlugin.Instance != (Object)null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[Overtime] no local Player yet; retrying wake.");
				}
				((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(WakeWhenPlayerExists());
			}
			StopCinematics();
			StopEndingMusic();
			BreakManager instance = BreakManager.instance;
			if (instance != null)
			{
				instance.EndGasVisual();
			}
			ReopenLabGateways();
			EndingProps.ResetClients();
			Cursor.lockState = (CursorLockMode)1;
			Cursor.visible = false;
			EyelidUI instance2 = EyelidUI.Instance;
			if ((Object)(object)instance2 != (Object)null)
			{
				instance2.Open(1.5f);
			}
			if ((Object)(object)EggstendedPlayPlugin.Instance != (Object)null)
			{
				((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(HideBlackoutAfter(1.2f));
			}
		}

		private static IEnumerator EnsureAwakeFallback(Player local)
		{
			FieldInfo asleep = AccessTools.Field(typeof(Player), "_asleepStanding");
			for (int i = 0; i < 180; i++)
			{
				yield return null;
				Player val = Player.Local ?? local;
				if (!((Object)(object)val == (Object)null))
				{
					bool flag = asleep != null && (bool)asleep.GetValue(val);
					if (!val.IsAsleep && !flag && !val.IsRagdolled)
					{
						val.RestoreGameplayInput();
						yield break;
					}
				}
			}
			Player val2 = Player.Local ?? local;
			if (!((Object)(object)val2 == (Object)null))
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[Overtime] wake routine did not clear; forcing the local player awake.");
				}
				asleep?.SetValue(val2, false);
				if (val2.IsRagdolled)
				{
					val2.RecoverFromLocalRagdoll();
				}
				val2.RestoreGameplayInput();
			}
		}

		private static void StopEndingMusic()
		{
			MusicDirector instance = MusicDirector.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(MusicDirector), "EnterSleep", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					methodInfo.Invoke(instance, null);
					EggstendedPlayPlugin.Verbose("[Overtime] ending music faded out.");
				}
			}
		}

		private static IEnumerator WakeWhenPlayerExists()
		{
			for (int i = 0; i < 300; i++)
			{
				yield return null;
				Player local = Player.Local;
				if ((Object)(object)local != (Object)null)
				{
					((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(EnsureAwakeFallback(local));
					yield break;
				}
			}
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogError((object)"[Overtime] local Player never appeared; input may still be disabled.");
			}
		}

		internal static void CloseEyes()
		{
			EyelidUI instance = EyelidUI.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.Close(1f);
			}
		}

		internal static void ShowBlackout()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_blackout == (Object)null)
			{
				_blackout = new GameObject("EggstendedBlackout", new Type[3]
				{
					typeof(Canvas),
					typeof(CanvasScaler),
					typeof(GraphicRaycaster)
				});
				Object.DontDestroyOnLoad((Object)(object)_blackout);
				Canvas component = _blackout.GetComponent<Canvas>();
				component.renderMode = (RenderMode)0;
				component.sortingOrder = 30000;
				GameObject val = new GameObject("Black", new Type[3]
				{
					typeof(RectTransform),
					typeof(CanvasRenderer),
					typeof(Image)
				});
				val.transform.SetParent(_blackout.transform, false);
				RectTransform val2 = (RectTransform)val.transform;
				val2.anchorMin = Vector2.zero;
				val2.anchorMax = Vector2.one;
				val2.offsetMin = Vector2.zero;
				val2.offsetMax = Vector2.zero;
				Image component2 = val.GetComponent<Image>();
				((Graphic)component2).color = Color.black;
				((Graphic)component2).raycastTarget = true;
			}
			_blackout.SetActive(true);
			Player local = Player.Local;
			if ((Object)(object)local != (Object)null && local.IsInputReady)
			{
				GameplayActions gameplayInput = local.GameplayInput;
				((GameplayActions)(ref gameplayInput)).Disable();
			}
		}

		internal static void HideBlackout()
		{
			if ((Object)(object)_blackout != (Object)null)
			{
				_blackout.SetActive(false);
			}
		}

		internal static void ResetBlackout()
		{
			if ((Object)(object)_blackout != (Object)null)
			{
				Object.Destroy((Object)(object)_blackout);
				_blackout = null;
			}
		}

		private static IEnumerator HideBlackoutAfter(float seconds)
		{
			yield return (object)new WaitForSecondsRealtime(seconds);
			HideBlackout();
		}

		internal static void ReopenLabGateways()
		{
			LabGateway[] array = Object.FindObjectsByType<LabGateway>((FindObjectsSortMode)0);
			foreach (LabGateway val in array)
			{
				if ((Object)(object)val != (Object)null && val.HasOpened)
				{
					val.Open();
				}
			}
		}

		internal static void StopCinematics()
		{
			CinematicSequence[] array = Object.FindObjectsByType<CinematicSequence>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				if ((Object)(object)array[i] != (Object)null && array[i].IsPlaying)
				{
					array[i].Stop();
				}
			}
		}

		private static T Field<T>(GameEndUI ui, string name) where T : class
		{
			if ((Object)(object)ui == (Object)null)
			{
				return null;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(GameEndUI), name);
			if (fieldInfo == null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Overtime] GameEndUI field '" + name + "' not found."));
				}
				return null;
			}
			return fieldInfo.GetValue(ui) as T;
		}

		private static void SetField(object target, string name, object value)
		{
			FieldInfo fieldInfo = AccessTools.Field(target.GetType(), name);
			if (fieldInfo == null)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Overtime] field '" + name + "' not found on " + target.GetType().Name + "."));
				}
			}
			else
			{
				fieldInfo.SetValue(target, value);
			}
		}
	}
	internal static class FleshTint
	{
		private const float TissueOffset = 0f;

		private const float BlightOffset = -85f;

		private static readonly Dictionary<string, (string tissue, string blight)> Palette = new Dictionary<string, (string, string)>
		{
			["robin"] = ("#ecec8c", "#c692fe"),
			["phoenix"] = ("#00BECD", "#0F00CD"),
			["alien"] = ("#CD32CD", "#3CEAEA")
		};

		private static readonly int HueShiftId = Shader.PropertyToID("_HueShift");

		private static HashSet<Material> _blightMaterials;

		internal static void ApplyForPalette(string palette)
		{
			if (palette != null && Palette.TryGetValue(palette, out (string, string) value))
			{
				Apply(value.Item1, value.Item2, palette);
			}
		}

		private static void Apply(string tissueHex, string blightHex, string palette)
		{
			float num = Encode(tissueHex, 0f);
			float num2 = Encode(blightHex, -85f);
			Dictionary<Material, float> dictionary = new Dictionary<Material, float>();
			HashSet<Material> hashSet = ResolveBlightMaterials();
			int num3 = 0;
			int num4 = 0;
			EggTerrain[] array = Object.FindObjectsByType<EggTerrain>((FindObjectsSortMode)0);
			foreach (EggTerrain val in array)
			{
				Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>(true);
				for (int j = 0; j < componentsInChildren.Length; j++)
				{
					Material[] sharedMaterials = componentsInChildren[j].sharedMaterials;
					foreach (Material val2 in sharedMaterials)
					{
						if (!((Object)(object)val2 == (Object)null) && val2.HasProperty(HueShiftId) && !dictionary.ContainsKey(val2))
						{
							bool flag = hashSet.Contains(val2);
							dictionary[val2] = (flag ? num2 : num);
							if (flag)
							{
								num4++;
							}
							else
							{
								num3++;
							}
						}
					}
				}
				TerrainTypeRegistry typeRegistry = val.TypeRegistry;
				if (typeRegistry != null)
				{
					typeRegistry.ApplyRecipeHue(dictionary);
				}
			}
			foreach (KeyValuePair<Material, float> item in dictionary)
			{
				item.Key.SetFloat(HueShiftId, item.Value);
			}
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)($"[Flesh] palette {palette}: tissue {tissueHex} (encoded {num:0}), " + $"blight {blightHex} (encoded {num2:0}); {num3} tissue, {num4} blight materials."));
			}
		}

		private static float Encode(string hex, float offset)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Color val = default(Color);
			if (!ColorUtility.TryParseHtmlString(hex, ref val))
			{
				return 0f;
			}
			float num = default(float);
			float num2 = default(float);
			float num3 = default(float);
			Color.RGBToHSV(val, ref num, ref num2, ref num3);
			float hue = num * 360f + offset;
			float multiplier = Mathf.Clamp(0.75f + num2 * 0.5f, 0.5f, 1.5f);
			float multiplier2 = Mathf.Clamp(0.85f + num3 * 0.35f, 0.6f, 1.4f);
			return Wrap(hue) + 360f * (float)WrapStep(multiplier) + 14760f * (float)WrapStep(multiplier2);
		}

		private static float Wrap(float hue)
		{
			return (Mathf.RoundToInt(hue) % 360 + 360) % 360;
		}

		private static int WrapStep(float multiplier)
		{
			return (Mathf.Clamp(Mathf.RoundToInt((multiplier - 1f) / 0.05f), -20, 20) + 41) % 41;
		}

		private static HashSet<Material> ResolveBlightMaterials()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Invalid comparison between Unknown and I4
			if (_blightMaterials != null)
			{
				return _blightMaterials;
			}
			_blightMaterials = new HashSet<Material>();
			TerrainType[] array = Resources.LoadAll<TerrainType>("Terrain Types");
			foreach (TerrainType val in array)
			{
				if ((Object)(object)val != (Object)null && (int)val.resourceType == 11 && (Object)(object)val.material != (Object)null)
				{
					_blightMaterials.Add(val.material);
				}
			}
			return _blightMaterials;
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct OvertimeWakeMessage : NetworkMessage
	{
	}
	public struct OvertimeEggResizeMessage : NetworkMessage
	{
		public float totalHeight;

		public int eggSeed;
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct OvertimeBlackoutMessage : NetworkMessage
	{
	}
	internal static class OvertimeFlow
	{
		internal static bool Pending;

		internal static bool SuppressMarker;

		private static bool _resetting;

		private static bool _endingSeen;

		private static bool _handlersRegistered;

		internal static void Init()
		{
			Writer<OvertimeWakeMessage>.write = WriteWake;
			Reader<OvertimeWakeMessage>.read = ReadWake;
			Writer<OvertimeEggResizeMessage>.write = WriteEggResize;
			Reader<OvertimeEggResizeMessage>.read = ReadEggResize;
			Writer<OvertimeBlackoutMessage>.write = WriteBlackout;
			Reader<OvertimeBlackoutMessage>.read = ReadBlackout;
			EnsureHandlers();
			EnsureOvertimeAnnouncement();
		}

		internal static void SendEggCatchUp(NetworkConnectionToClient conn)
		{
			if (NetworkServer.active && conn != null && EggEnlargement.EggSeedActive)
			{
				float totalHeight = ((EggEnlargement.AppliedHeight > 0f) ? EggEnlargement.AppliedHeight : 24f);
				((NetworkConnection)conn).Send<OvertimeEggResizeMessage>(new OvertimeEggResizeMessage
				{
					totalHeight = totalHeight,
					eggSeed = EggEnlargement.EggSeed
				}, 0);
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"[Egg] sent overtime resize catch-up to connection {conn.connectionId}.");
				}
			}
		}

		internal static void ResetForNewScene()
		{
			Pending = false;
			_endingSeen = false;
			_resetting = false;
		}

		internal static void EnsureHandlers()
		{
			if (!NetworkClient.active)
			{
				_handlersRegistered = false;
			}
			else if (!_handlersRegistered)
			{
				NetworkClient.RegisterHandler<OvertimeWakeMessage>((Action<OvertimeWakeMessage>)OnWake, false);
				NetworkClient.RegisterHandler<OvertimeEggResizeMessage>((Action<OvertimeEggResizeMessage>)OnEggResize, false);
				NetworkClient.RegisterHandler<OvertimeBlackoutMessage>((Action<OvertimeBlackoutMessage>)OnBlackout, false);
				_handlersRegistered = true;
				EggstendedPlayPlugin.Verbose("[Overtime] network handlers registered.");
			}
		}

		private static void WriteWake(NetworkWriter writer, OvertimeWakeMessage message)
		{
		}

		private static OvertimeWakeMessage ReadWake(NetworkReader reader)
		{
			return default(OvertimeWakeMessage);
		}

		private static void WriteEggResize(NetworkWriter writer, OvertimeEggResizeMessage message)
		{
			NetworkWriterExtensions.WriteFloat(writer, message.totalHeight);
			NetworkWriterExtensions.WriteInt(writer, message.eggSeed);
		}

		private static OvertimeEggResizeMessage ReadEggResize(NetworkReader reader)
		{
			return new OvertimeEggResizeMessage
			{
				totalHeight = NetworkReaderExtensions.ReadFloat(reader),
				eggSeed = NetworkReaderExtensions.ReadInt(reader)
			};
		}

		private static void WriteBlackout(NetworkWriter writer, OvertimeBlackoutMessage message)
		{
		}

		private static OvertimeBlackoutMessage ReadBlackout(NetworkReader reader)
		{
			return default(OvertimeBlackoutMessage);
		}

		private static void OnBlackout(OvertimeBlackoutMessage message)
		{
			EndUi.ShowBlackout();
		}

		private static void OnEggResize(OvertimeEggResizeMessage message)
		{
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"[Egg] resize message: {message.totalHeight:0.###} m, seed {message.eggSeed}.");
			}
			EggEnlargement.SetSeed(message.eggSeed);
			((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(EggEnlargement.ResizeAndRebuild(message.totalHeight, forceRebuild: true));
		}

		private static void OnWake(OvertimeWakeMessage message)
		{
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[Overtime] wake received.");
			}
			EnsureOvertimeAnnouncement();
			EndUi.Wake();
		}

		internal static void OnServerEndGame(GameEnding ending)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkServer.active && (int)ending != 0 && !_endingSeen && !_resetting)
			{
				_endingSeen = true;
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"[Overtime] ending {ending} seen; overtime is queued.");
				}
				((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(FallbackTimer());
			}
		}

		private static IEnumerator FallbackTimer()
		{
			float fallback = 600f;
			if (fallback <= 0f)
			{
				yield break;
			}
			float started = Time.realtimeSinceStartup;
			while (_endingSeen && !_resetting && Time.realtimeSinceStartup - started < fallback)
			{
				yield return null;
			}
			if (_endingSeen && !_resetting)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[Overtime] credits never finished; starting the reset on the fallback timer.");
				}
				ServerCreditsDone();
			}
		}

		internal static void ServerExitToMenuPressed()
		{
			if (NetworkServer.active)
			{
				ManualLogSource log = EggstendedPlayPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"[Overtime] exit-to-menu intercepted; starting overtime.");
				}
				_endingSeen = true;
				ServerCreditsDone();
			}
		}

		internal static bool ServerTossEgg(out string message)
		{
			if (!NetworkServer.active)
			{
				message = "EGG TOSS is host-side.";
				return false;
			}
			if (_resetting)
			{
				message = "A reset is already running.";
				return false;
			}
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[Overtime] EGG TOSS: rebuilding the egg without an ending.");
			}
			_endingSeen = true;
			ServerCreditsDone();
			message = "Egg tossed: resetting the world and rebuilding the egg.";
			return true;
		}

		internal static void ServerCreditsDone()
		{
			if (NetworkServer.active && !_resetting && _endingSeen)
			{
				_endingSeen = false;
				((MonoBehaviour)EggstendedPlayPlugin.Instance).StartCoroutine(ServerResetRoutine());
			}
		}

		private static IEnumerator ServerResetRoutine()
		{
			_resetting = true;
			ManualLogSource log = EggstendedPlayPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[Overtime] starting world reset.");
			}
			if (NetworkServer.active)
			{
				NetworkServer.SendToReady<OvertimeBlackoutMessage>(default(OvertimeBlackoutMessage), 0);
			}
			if (NetworkClient.active)
			{
				EndUi.ShowBlackout();
			}
			SaveManager save = SaveManager.Instance;
			if ((Object)(object)save == (Object)null)
			{
				ManualLogSource log2 = EggstendedPlayPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)"[Overtime] no SaveManager; reset aborted.");
				}
				_resetting = false;
				yield break;
			}
			float waitUntil = Time.realtimeSinceStartup + 60f;
			while ((save.IsLoading || save.AsyncSaveRunning) && Time.realtimeSinceStartup < waitUntil)
			{
				yield return null;
			}
			float cinemaUntil = Time.realtimeSinceStartup + 45f;
			while (CinematicSequence.AnyPlaying && Time.realtimeSinceStartup < cinemaUntil)
			{
				yield return null;
			}
			if (CinematicSequence.AnyPlaying)
			{
				ManualLogSource log3 = EggstendedPlayPlugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)"[Overtime] cinematic never ended; stopping it before the reset.");
				}
				EndUi.StopCinematics();
			}
			int num = RackTools.ServerDropAllRackTools();
			int num2 = EjectSupportSpikes();
			if (num > 0 || num2 > 0)
			{
				yield return (object)new WaitForSecondsRealtime(3f);
			}
			if (save.SaveBlockedReason != null)
			{
				ManualLogSource log4 = EggstendedPlayPlugin.Log;
				if (log4 != null)
				{
					log4.LogError((object)("[Overtime] saving is blocked: " + save.SaveBlockedReason + "; reset aborted."));
				}
				_resetting = false;
				yield break;
			}
			save.Save();
			yield return null;
			string text = SaveSlots.WorldPath(SaveSlots.SelectedSlot);
			ReadResult val = SaveFile.Read(text, SaveFile.LocalHostId);
			if (!val.ok)
			{
				ManualLogSource log5 = EggstendedPlayPlugin.Log;
				if (log5 != null)
				{
					log5.LogError((object)("[Overtime] couldn't read the ending save: " + val.error + "; reset aborted."));
				}
				_resetting = false;
				yield break;
			}
			WorldSaveData val2;
			try
			{
				val2 = JsonUtility.FromJson<WorldSaveData>(val.json);
			}
			catch (Exception ex)
			{
				ManualLogSource log6 = EggstendedPlayPlugin.Log;
				if (log6 != null)
				{
					log6.LogError((object)("[Overtime] ending save is unreadable: " + ex.Message + "; reset aborted."));
				}
				_resetting = false;
				yield break;
			}
			if (val2 == null)
			{
				ManualLogSource log7 = EggstendedPlayPlugin.Log;
				if (log7 != null)
				{
					log7.LogError((object)"[Overtime] ending save decoded to nothing; reset aborted.");
				}
				_resetting = false;
				yield break;
			}
			val2.egg = null;
			val2.scaffold = null;
			val2.pickups = null;
			val2.removedDepositIndices = null;
			ReadResult val3 = SaveFile.Read(SaveSlots.BaselinePath(SaveSlots.SelectedSlot), SaveFile.LocalHostId);
			if (val3.ok)
			{
				try
				{
					WorldSaveData val4 = JsonUtility.FromJson<WorldSaveData>(val3.json);
					if (val4 != null)
					{
						val2.vehicles = val4.vehicles;
						val2.pushableScaffolds = val4.pushableScaffolds;
					}
				}
				catch (Exception ex2)
				{
					ManualLogSource log8 = EggstendedPlayPlugin.Log;
					if (log8 != null)
					{
						log8.LogWarning((object)("[Overtime] baseline is unreadable, leaving vehicle positions alone: " + ex2.Message));
					}
				}
			}
			try
			{
				SaveFile.Write(text, JsonUtility.ToJson((object)val2), SaveFile.LocalHostId);
			}
			catch (Exception ex3)
			{
				ManualLogSource log9 = EggstendedPlayPlugin.Log;
				if (log9 != null)
				{
					log9.LogError((object)("[Overtime] couldn't write the overtime save: " + ex3.Message + "; reset aborted."));
				}
				_resetting = false;
				yield break;
			}
			ManualLogSource log10 = EggstendedPlayPlugin.Log;
			if (log10 != null)
			{
				log10.LogInfo((object)"[Overtime] overtime save written; loading checkpoint.");
			}
			RecoverAllPlayersToSpawns();
			SuppressMarker = true;
			save.LoadCheckpoint();
			yield return null;
			yield return null;
			float loadUntil = Time.realtimeSinceStartup + 300f;
			while (save.IsLoading && Time.realtimeSinceStartup < loadUntil)
			{
				yield return null;
			}
			SuppressMarker = false;
			if (save.IsLoading)
			{
				ManualLogSource log11 = EggstendedPlayPlugin.Log;
				if (log11 != null)
				{
					log11.LogError((object)"[Overtime] checkpoint load did not finish; overtime remains armed but clients may desync.");
				}
			}
			float eggHeight = 24f;
			int eggSeed = Random.Range(int.MinValue, int.MaxValue);
			EggEnlargement.SetSeed(eggSeed);
			yield return EggEnlargement.ResizeAndRebuild(eggHeight, forceRebuild: true);
			EggEnlargement.WriteMarker(eggHeight, eggSeed);
			if (NetworkServer.active)
			{
				NetworkServer.SendToReady<OvertimeEggResizeMessage>(new OvertimeEggResizeMessage
				{
					totalHeight = eggHeight,
					eggSeed = eggSeed
				}, 0);
			}
			ReArmEnding();
			RecoverAllPlayersToSpawns();
			SleepAllPlayersInBeds();
			yield return (object)new WaitForSecondsRealtime(1.5f);
			WakeAllPlayersOnly();
			RecoverAllPlayersToSpawns();
			Pending = true;
			NetworkServer.SendToReady<OvertimeWakeMessage>(default(OvertimeWakeMessage), 0);
			if (NetworkClient.active)
			{
				EndUi.Wake();
			}
			ManualLogSource log12 = EggstendedPlayPlugin.Log;
			if (log12 != null)
			{
				log12.LogInfo((object)"[Overtime] world reset complete; waiting for the hatch.");
			}
			_resetting = false;
		}

		private static void RecoverAllPlayersToSpawns()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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)
			if ((Object)(object)GameManager.instance == (Object)null)
			{
				return;
			}
			foreach (PlayerController allPlayerController in GameManager.instance.GetAllPlayerControllers())
			{
				if (!((Object)(object)allPlayerController == (Object)null) && !((Object)(object)allPlayerController.player == (Object)null))
				{
					var (val, val2) = GameManager.instance.GetSpawnPoint(allPlayerController.index);
					allPlayerController.player.ServerRecoverTo(val, val2);
					allPlayerController.player.ServerWakeUp();
				}
			}
		}

		private static void SleepAllPlayersInBeds()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)GameManager.instance == (Object)null)
			{
				return;
			}
			foreach (PlayerController allPlayerController in GameManager.instance.GetAllPlayerControllers())
			{
				if (!((Object)(object)allPlayerController == (Object)null) && !((Object)(object)allPlayerController.player == (Object)null))
				{
					Bed forPlayer = Bed.GetForPlayer(allPlayerController.index);
					Vector3 val;
					Quaternion val2;
					if (!((Object)(object)forPlayer != (Object)null) || !((Object)(object)forPlayer.SleepPoint != (Object)null))
					{
						(val, val2) = GameManager.instance.GetSpawnPoint(allPlayerController.index);
					}
					else
					{
						val = forPlayer.SleepPoint.position;
						val2 = forPlayer.SleepPoint.rotation;
					}
					allPlayerController.player.ServerRecoverTo(val, val2);
					allPlayerController.player.ServerSleepInBed(val, 0f, false);
				}
			}
		}

		private static void WakeAllPlayersOnly()
		{
			if ((Object)(object)GameManager.instance == (Object)null)
			{
				return;
			}
			foreach (PlayerController allPlayerController in GameManager.instance.GetAllPlayerControllers())
			{
				if ((Object)(object)allPlayerController != (Object)null && (Object)(object)allPlayerController.player != (Object)null)
				{
					allPlayerController.player.ServerWakeUp();
				}
			}
		}

		private static int EjectSupportSpikes()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be