Decompiled source of MoonRotation v1.3.1

MoonRotation.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dawn;
using HarmonyLib;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MoonRotation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.1.0")]
[assembly: AssemblyInformationalVersion("1.3.1")]
[assembly: AssemblyProduct("MoonRotation")]
[assembly: AssemblyTitle("MoonRotation")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.3.1.0")]
namespace MoonRotation;

internal class FloorMoon
{
	public int Id;

	public string Name;

	public string Weather;

	public bool Clear;

	public bool CanBeClear = true;

	public bool Forced;

	public bool Locked;
}
internal class FloorPlan
{
	public int Counted;

	public int ClearBefore;

	public int Needed;

	public List<FloorMoon> ToClear = new List<FloorMoon>();

	public bool Acts => Needed > 0;

	public bool Short => ToClear.Count < Needed;
}
internal static class ClearFloor
{
	internal const int NoneWeather = -1;

	internal static bool IsClear(int weatherType)
	{
		return weatherType == -1;
	}

	internal static FloorPlan Plan(IEnumerable<FloorMoon> moons, int minClear, int seed)
	{
		FloorPlan floorPlan = new FloorPlan();
		List<FloorMoon> list = (from m in moons ?? Enumerable.Empty<FloorMoon>()
			where m?.CanBeClear ?? false
			orderby m.Id
			select m).ToList();
		floorPlan.Counted = list.Count;
		floorPlan.ClearBefore = list.Count((FloorMoon m) => m.Clear);
		if (minClear <= 0)
		{
			return floorPlan;
		}
		floorPlan.Needed = Math.Max(0, minClear - floorPlan.ClearBefore);
		if (floorPlan.Needed == 0)
		{
			return floorPlan;
		}
		Random rng = new Random(seed);
		List<FloorMoon> list2 = list.Where((FloorMoon m) => !m.Clear && !m.Locked && !m.Forced).ToList();
		List<FloorMoon> list3 = list.Where((FloorMoon m) => !m.Clear && !m.Locked && m.Forced).ToList();
		Shuffle(list2, rng);
		Shuffle(list3, rng);
		foreach (FloorMoon item in list2.Concat(list3))
		{
			if (floorPlan.ToClear.Count >= floorPlan.Needed)
			{
				break;
			}
			floorPlan.ToClear.Add(item);
		}
		return floorPlan;
	}

	private static void Shuffle<T>(List<T> list, Random rng)
	{
		for (int num = list.Count - 1; num > 0; num--)
		{
			int index = rng.Next(num + 1);
			T value = list[num];
			list[num] = list[index];
			list[index] = value;
		}
	}

	internal static string Describe(FloorPlan plan, int minClear)
	{
		StringBuilder stringBuilder = new StringBuilder("MoonRotation: only ");
		stringBuilder.Append(plan.ClearBefore).Append((plan.ClearBefore == 1) ? " clear moon in range, " : " clear moons in range, ");
		if (plan.ToClear.Count == 0)
		{
			stringBuilder.Append("but no moon could be cleared");
		}
		else
		{
			stringBuilder.Append("cleared ").Append(string.Join(", ", plan.ToClear.Select((FloorMoon m) => m.Name + " (was " + m.Weather + ")").ToArray()));
		}
		if (plan.Short)
		{
			stringBuilder.Append(" (").Append(plan.ClearBefore + plan.ToClear.Count).Append(" of ")
				.Append(minClear)
				.Append(" clear; the other weathered moons are the ship's moon or can't be clear)");
		}
		return stringBuilder.ToString();
	}

	internal static string Numberless(string planetName)
	{
		if (string.IsNullOrEmpty(planetName))
		{
			return planetName ?? "";
		}
		int i;
		for (i = 0; i < planetName.Length && char.IsDigit(planetName[i]); i++)
		{
		}
		if (i == 0 || i >= planetName.Length || planetName[i] != ' ')
		{
			return planetName;
		}
		string text = planetName.Substring(i).TrimStart();
		if (text.Length <= 0)
		{
			return planetName;
		}
		return text;
	}
}
public enum RotateMode
{
	Day,
	Quota,
	Game
}
[BepInPlugin("jacob.moonrotation", "MoonRotation", "1.3.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "jacob.moonrotation";

	public const string Name = "MoonRotation";

	public const string Version = "1.3.1";

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<RotateMode> RotateEvery;

	internal static ConfigEntry<int> PercentShown;

	internal static ConfigEntry<bool> ShowRangeLine;

	internal static ConfigEntry<string> InRangeInfo;

	internal static ConfigEntry<int> MinClearMoons;

	private void Awake()
	{
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Expected O, but got Unknown
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Expected O, but got Unknown
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_0218: Unknown result type (might be due to invalid IL or missing references)
		//IL_021e: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Only a share of the moons are available at a time.");
		RotateEvery = ((BaseUnityPlugin)this).Config.Bind<RotateMode>("General", "RotateEvery", RotateMode.Day, "When the available moons change: Day, Quota, or Game (once per save/run). Host's setting is used.");
		PercentShown = ((BaseUnityPlugin)this).Config.Bind<int>("General", "PercentShown", 40, new ConfigDescription("Percent of moons available at a time (the Company is always extra). At least one free and one paid moon are always included. Host's setting is used.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 100), Array.Empty<object>()));
		ShowRangeLine = ((BaseUnityPlugin)this).Config.Bind<bool>("Terminal", "ShowRangeLine", true, "Add a line to the moons list saying how many moons are in range.");
		InRangeInfo = ((BaseUnityPlugin)this).Config.Bind<string>("Info", "MoonsInRange", "(updates once you're in a game)", "Read-only, written by the mod: how many moons there are and how many the current percentage makes available, by price bracket. Editing it does nothing.");
		MinClearMoons = ((BaseUnityPlugin)this).Config.Bind<int>("Weather", "MinClearMoons", 2, new ConfigDescription("At least this many of the moons in range have clear weather (None) each day. If fewer rolled None, randomly chosen weathered moons in range are set to None (never the moon the ship is on or routed to). 0 = off. Host's setting is used. Needs WeatherRegistry.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
		Harmony h = new Harmony("jacob.moonrotation");
		Patch(h, AccessTools.Method(typeof(VisibleFilterStep), "Filter", (Type[])null, (Type[])null), null, "AfterVisibleFilter");
		Patch(h, AccessTools.Method(typeof(Terminal), "LoadNewNode", (Type[])null, (Type[])null), "BeforeLoadNewNode");
		Patch(h, AccessTools.Method(typeof(Terminal), "LoadNewNodeIfAffordable", (Type[])null, (Type[])null), "BeforeLoadNewNode");
		Patch(h, AccessTools.Method(typeof(Terminal), "TextPostProcess", (Type[])null, (Type[])null), null, "AfterTextPostProcess");
		Patch(h, AccessTools.Method(typeof(StartOfRound), "Start", (Type[])null, (Type[])null), null, "AfterStartOfRoundStart");
		Patch(h, AccessTools.Method(typeof(StartOfRound), "FirePlayersAfterDeadlineClientRpc", (Type[])null, (Type[])null), null, "AfterFired");
		Type type = QuietTypes.Find("RouteRandom.Helpers.TerminalHelper");
		if (type != null)
		{
			Patch(h, AccessTools.Method(type, "ResultIsRealMoon", (Type[])null, (Type[])null), null, "AfterRouteRandomCheck");
		}
		PatchWeatherFloor(h);
		GameObject val = new GameObject("MoonRotationRunner")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)val);
		val.AddComponent<Runner>();
		((BaseUnityPlugin)this).Logger.LogInfo((object)("MoonRotation 1.3.1 loaded. RotateEvery=" + RotateEvery.Value.ToString() + ", PercentShown=" + PercentShown.Value + ", MinClearMoons=" + MinClearMoons.Value));
	}

	private void PatchWeatherFloor(Harmony h)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Expected O, but got Unknown
		MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "SetPlanetsWeather", (Type[])null, (Type[])null);
		if (methodInfo == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Hook target missing (BeforeSetPlanetsWeather)");
			return;
		}
		try
		{
			HarmonyMethod val = new HarmonyMethod(typeof(Hooks), "BeforeSetPlanetsWeather", (Type[])null);
			val.after = new string[1] { "mrov.WeatherRegistry" };
			val.before = new string[1] { "WeatherTweaks" };
			HarmonyMethod val2 = val;
			h.Patch((MethodBase)methodInfo, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Couldn't hook SetPlanetsWeather (MinClearMoons is off): " + ex.Message));
		}
	}

	private void Patch(Harmony h, MethodInfo target, string prefix = null, string postfix = null)
	{
		//IL_003d: 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)
		if (target == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Hook target missing (" + (prefix ?? postfix) + ")"));
			return;
		}
		try
		{
			h.Patch((MethodBase)target, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Hooks), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Hooks), postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Couldn't hook " + target.Name + ": " + ex.Message));
		}
	}
}
internal static class Rotation
{
	internal class Moon
	{
		public int Id;

		public int Price;

		public string Name;
	}

	internal class Selection
	{
		public List<int> Picked = new List<int>();

		public string Breakdown = "";

		public int[] Quota;

		public int[] Sizes;
	}

	internal const string SeedKey = "jacob.MoonRotation.Seed";

	internal static int Key = -1;

	internal static int Percent = 40;

	internal static RotateMode Mode = RotateMode.Day;

	internal static int HostSeed;

	internal static bool HostSeedLoaded;

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

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

	private static int _computedKey = int.MinValue;

	private static int _computedSig;

	internal static int EligibleCount;

	internal static int PickedCount;

	private static bool _inCompute;

	internal static bool Active
	{
		get
		{
			if (Plugin.Enabled.Value)
			{
				return Key >= 0;
			}
			return false;
		}
	}

	internal static bool IsCompany(SelectableLevel l)
	{
		if ((Object)(object)l != (Object)null)
		{
			if (!(l.sceneName == "CompanyBuilding"))
			{
				return (l.PlanetName ?? "").IndexOf("Gordion", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return true;
		}
		return false;
	}

	internal static bool IsAvailable(int levelID)
	{
		if (!Active || levelID < 0)
		{
			return true;
		}
		EnsureComputed();
		StartOfRound instance = StartOfRound.Instance;
		if ((Object)(object)instance != (Object)null && instance.levels != null)
		{
			SelectableLevel[] levels = instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if ((Object)(object)val != (Object)null && val.levelID == levelID && IsCompany(val))
				{
					return true;
				}
			}
		}
		return Picked.Contains(levelID);
	}

	internal static HashSet<int> InRangeIds()
	{
		return new HashSet<int>(Plugin.Enabled.Value ? Picked : Eligible);
	}

	internal static IEnumerable<DawnMoonInfo> Filter(IEnumerable<DawnMoonInfo> visible)
	{
		if (_inCompute || !Active || visible == null)
		{
			return visible;
		}
		EnsureComputed();
		return visible.Where((DawnMoonInfo m) => m == null || (Object)(object)m.Level == (Object)null || IsAvailable(m.Level.levelID));
	}

	internal static void EnsureComputed()
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		if (_inCompute)
		{
			return;
		}
		_inCompute = true;
		List<DawnMoonInfo> list;
		try
		{
			IEnumerable<DawnMoonInfo> enumerable = ((IEnumerable<DawnMoonInfo>)LethalContent.Moons).Where((DawnMoonInfo m) => m != null && (Object)(object)m.Level != (Object)null && !((DawnBaseInfo<DawnMoonInfo>)(object)m).HasTag(Tags.Unimplemented));
			list = new VisibleFilterStep().Filter(enumerable).ToList();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Couldn't read DawnLib's moons: " + ex.Message));
			return;
		}
		finally
		{
			_inCompute = false;
		}
		int num = 17;
		foreach (DawnMoonInfo item in list.OrderBy((DawnMoonInfo m) => m.Level.levelID))
		{
			num = num * 31 + item.Level.levelID;
		}
		num = num * 31 + Percent;
		if (Key != _computedKey || num != _computedSig)
		{
			_computedKey = Key;
			_computedSig = num;
			Compute(list);
		}
	}

	private static int Price(DawnMoonInfo m)
	{
		try
		{
			return m.DawnPurchaseInfo.Cost.Provide();
		}
		catch
		{
			return 0;
		}
	}

	private static void Compute(List<DawnMoonInfo> eligible)
	{
		List<Moon> list = (from m in eligible
			where !IsCompany(m.Level)
			select new Moon
			{
				Id = m.Level.levelID,
				Price = Price(m),
				Name = m.Level.PlanetName
			}).ToList();
		Selection selection = Select(list, Percent, Key);
		Picked.Clear();
		foreach (int item in selection.Picked)
		{
			Picked.Add(item);
		}
		Eligible.Clear();
		foreach (Moon item2 in list)
		{
			Eligible.Add(item2.Id);
		}
		EligibleCount = list.Count;
		PickedCount = Picked.Count;
		try
		{
			Plugin.InRangeInfo.Value = PickedCount + " of " + EligibleCount + " moons in range at " + Percent + "% (" + selection.Breakdown + "), plus the Company. Changes " + PeriodWord(every: true) + ".";
		}
		catch
		{
		}
		IEnumerable<string> values = from x in list
			where Picked.Contains(x.Id)
			orderby x.Price
			select x.Name + " ($" + x.Price + ")";
		Plugin.Log.LogInfo((object)("Moons in range (key " + Key + "): " + PickedCount + " of " + EligibleCount + " plus the Company: " + string.Join(", ", values)));
	}

	internal static Selection Select(List<Moon> pool, int percent, int key)
	{
		Selection selection = new Selection();
		pool = (from x in pool
			orderby x.Price, x.Id
			select x).ToList();
		if (pool.Count == 0)
		{
			selection.Quota = new int[4];
			selection.Sizes = new int[4];
			return selection;
		}
		List<Moon> list = pool.Where((Moon x) => x.Price <= 0).ToList();
		List<Moon> list2 = pool.Where((Moon x) => x.Price > 0).ToList();
		List<List<int>> brackets = new List<List<int>> { list.Select((Moon x) => x.Id).ToList() };
		int num = list2.Count / 3;
		int num2 = list2.Count % 3;
		int num3 = 0;
		for (int num4 = 0; num4 < 3; num4++)
		{
			int num5 = num + ((num4 < num2) ? 1 : 0);
			brackets.Add((from x in list2.Skip(num3).Take(num5)
				select x.Id).ToList());
			num3 += num5;
		}
		int num6 = Math.Max(((list.Count > 0) ? 1 : 0) + ((list2.Count > 0) ? 1 : 0), Math.Min(val2: (int)Math.Round((double)(pool.Count * Math.Max(1, Math.Min(100, percent))) / 100.0, MidpointRounding.AwayFromZero), val1: pool.Count));
		int[] quota = new int[brackets.Count];
		double[] rem = new double[brackets.Count];
		int num7 = 0;
		for (int num8 = 0; num8 < brackets.Count; num8++)
		{
			double num9 = (double)num6 * (double)brackets[num8].Count / (double)pool.Count;
			quota[num8] = (int)Math.Floor(num9);
			rem[num8] = num9 - (double)quota[num8];
			num7 += quota[num8];
		}
		foreach (int item in from i in Enumerable.Range(0, brackets.Count)
			orderby rem[i] descending, i
			select i)
		{
			if (num7 >= num6)
			{
				break;
			}
			if (quota[item] < brackets[item].Count)
			{
				quota[item]++;
				num7++;
			}
		}
		if (list.Count > 0 && quota[0] == 0)
		{
			Move(quota, brackets, 0);
		}
		if (list2.Count > 0 && quota[1] + quota[2] + quota[3] == 0)
		{
			int toIndex = (from i in Enumerable.Range(1, 3)
				orderby brackets[i].Count descending
				select i).First();
			Move(quota, brackets, toIndex);
		}
		Random random = new Random(key);
		for (int num10 = 0; num10 < brackets.Count; num10++)
		{
			List<int> list3 = brackets[num10].OrderBy((int id) => id).ToList();
			for (int num11 = 0; num11 < quota[num10]; num11++)
			{
				if (list3.Count <= 0)
				{
					break;
				}
				int index = random.Next(list3.Count);
				selection.Picked.Add(list3[index]);
				list3.RemoveAt(index);
			}
		}
		string[] bn = new string[4] { "free", "cheap", "mid", "expensive" };
		selection.Breakdown = string.Join(", ", from i in Enumerable.Range(0, brackets.Count)
			where brackets[i].Count > 0
			select bn[i] + " " + quota[i] + "/" + brackets[i].Count);
		selection.Quota = quota;
		selection.Sizes = brackets.Select((List<int> b) => b.Count).ToArray();
		return selection;
	}

	private static void Move(int[] quota, List<List<int>> brackets, int toIndex)
	{
		int num = -1;
		for (int i = 0; i < quota.Length; i++)
		{
			if (i != toIndex && quota[i] > 0 && (num < 0 || quota[i] > quota[num]))
			{
				num = i;
			}
		}
		if (num >= 0)
		{
			quota[num]--;
		}
		if (quota[toIndex] < brackets[toIndex].Count)
		{
			quota[toIndex]++;
		}
	}

	internal static int MakeKey(int seed, RotateMode mode, int index)
	{
		int num = (int)(seed * 486187739 + mode + 1) * 486187739 + index;
		int num2 = (num ^ (num >> 15)) * 739982445;
		return (num2 ^ (num2 >> 12)) & 0x7FFFFFFF;
	}

	internal static string PeriodWord(bool every = false)
	{
		switch (Mode)
		{
		case RotateMode.Quota:
			if (!every)
			{
				return "this quota";
			}
			return "every quota";
		case RotateMode.Game:
			if (!every)
			{
				return "this run";
			}
			return "once per run";
		default:
			if (!every)
			{
				return "today";
			}
			return "every day";
		}
	}
}
internal static class Net
{
	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static HandleNamedMessageDelegate <>9__3_0;

		public static HandleNamedMessageDelegate <>9__3_1;

		internal void <EnsureRegistered>b__3_0(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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)
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			int num2 = 40;
			int num3 = 0;
			try
			{
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num3, default(ForPrimitives));
			}
			catch
			{
			}
			if (!NetworkManager.Singleton.IsServer && (num != Rotation.Key || num2 != Rotation.Percent || num3 != (int)Rotation.Mode))
			{
				Rotation.Key = num;
				Rotation.Percent = num2;
				Rotation.Mode = (RotateMode)num3;
				Plugin.Log.LogInfo((object)("Received moon rotation from host (key " + num + ", " + num2 + "%, " + Rotation.Mode.ToString() + ")"));
			}
		}

		internal void <EnsureRegistered>b__3_1(ulong sender, FastBufferReader reader)
		{
			if (NetworkManager.Singleton.IsServer)
			{
				SendKey(sender);
			}
		}
	}

	internal const string KeyMsg = "jacob.moonrotation.key";

	internal const string RequestMsg = "jacob.moonrotation.request";

	private static CustomMessagingManager _registeredOn;

	internal static void EnsureRegistered()
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Expected O, but got Unknown
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Expected O, but got Unknown
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null || _registeredOn == singleton.CustomMessagingManager)
		{
			return;
		}
		_registeredOn = singleton.CustomMessagingManager;
		CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
		object obj = <>c.<>9__3_0;
		if (obj == null)
		{
			HandleNamedMessageDelegate val = delegate(ulong sender, FastBufferReader reader)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: 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)
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				int num2 = 40;
				int num3 = 0;
				try
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num3, default(ForPrimitives));
				}
				catch
				{
				}
				if (!NetworkManager.Singleton.IsServer && (num != Rotation.Key || num2 != Rotation.Percent || num3 != (int)Rotation.Mode))
				{
					Rotation.Key = num;
					Rotation.Percent = num2;
					Rotation.Mode = (RotateMode)num3;
					Plugin.Log.LogInfo((object)("Received moon rotation from host (key " + num + ", " + num2 + "%, " + Rotation.Mode.ToString() + ")"));
				}
			};
			<>c.<>9__3_0 = val;
			obj = (object)val;
		}
		customMessagingManager.RegisterNamedMessageHandler("jacob.moonrotation.key", (HandleNamedMessageDelegate)obj);
		CustomMessagingManager customMessagingManager2 = singleton.CustomMessagingManager;
		object obj2 = <>c.<>9__3_1;
		if (obj2 == null)
		{
			HandleNamedMessageDelegate val2 = delegate(ulong sender, FastBufferReader reader)
			{
				if (NetworkManager.Singleton.IsServer)
				{
					SendKey(sender);
				}
			};
			<>c.<>9__3_1 = val2;
			obj2 = (object)val2;
		}
		customMessagingManager2.RegisterNamedMessageHandler("jacob.moonrotation.request", (HandleNamedMessageDelegate)obj2);
		if (!singleton.IsServer)
		{
			Request();
		}
	}

	internal unsafe static void Request()
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || singleton.IsServer || !singleton.IsConnectedClient)
		{
			return;
		}
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
		try
		{
			int num = 0;
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			singleton.CustomMessagingManager.SendNamedMessage("jacob.moonrotation.request", 0uL, val, (NetworkDelivery)2);
		}
		finally
		{
			((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
		}
	}

	internal unsafe static void SendKey(ulong clientId)
	{
		//IL_002f: 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_0044: 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_005c: 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_0074: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsServer || clientId == 0L)
		{
			return;
		}
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1);
		try
		{
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref Rotation.Key, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref Rotation.Percent, default(ForPrimitives));
			int mode = (int)Rotation.Mode;
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref mode, default(ForPrimitives));
			singleton.CustomMessagingManager.SendNamedMessage("jacob.moonrotation.key", clientId, val, (NetworkDelivery)2);
		}
		finally
		{
			((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
		}
	}

	internal static void Broadcast()
	{
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
		{
			return;
		}
		foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
		{
			SendKey(connectedClientsId);
		}
	}
}
internal class Runner : MonoBehaviour
{
	private float _next;

	private float _nextRequest;

	private int _errors;

	private void Update()
	{
		if (_errors >= 10 || Time.unscaledTime < _next)
		{
			return;
		}
		_next = Time.unscaledTime + 0.5f;
		try
		{
			Tick();
		}
		catch (Exception ex)
		{
			_errors++;
			Plugin.Log.LogWarning((object)("Runner error " + _errors + "/10: " + ex.Message));
		}
	}

	private void Tick()
	{
		StartOfRound instance = StartOfRound.Instance;
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)instance == (Object)null || (Object)(object)singleton == (Object)null || !singleton.IsListening)
		{
			Rotation.Key = -1;
			Rotation.HostSeedLoaded = false;
			return;
		}
		Net.EnsureRegistered();
		if (!singleton.IsServer)
		{
			if (Rotation.Key < 0 && Time.unscaledTime > _nextRequest)
			{
				_nextRequest = Time.unscaledTime + 5f;
				Net.Request();
			}
		}
		else
		{
			UpdateHostKey(instance);
		}
	}

	internal static void UpdateHostKey(StartOfRound sor)
	{
		if (!Rotation.HostSeedLoaded)
		{
			LoadSeed();
		}
		int index = 0;
		switch (Plugin.RotateEvery.Value)
		{
		case RotateMode.Day:
			index = ((sor.gameStats != null) ? sor.gameStats.daysSpent : 0);
			break;
		case RotateMode.Quota:
			index = (((Object)(object)TimeOfDay.Instance != (Object)null) ? TimeOfDay.Instance.timesFulfilledQuota : 0);
			break;
		}
		int num = Rotation.MakeKey(Rotation.HostSeed, Plugin.RotateEvery.Value, index);
		int num2 = Mathf.Clamp(Plugin.PercentShown.Value, 1, 100);
		if (num != Rotation.Key || num2 != Rotation.Percent || Plugin.RotateEvery.Value != Rotation.Mode)
		{
			Rotation.Key = num;
			Rotation.Percent = num2;
			Rotation.Mode = Plugin.RotateEvery.Value;
			Plugin.Log.LogInfo((object)("Moon rotation key " + num + " (" + Rotation.Mode.ToString() + " " + index + ", " + num2 + "%)"));
			Net.Broadcast();
			Rotation.EnsureComputed();
		}
	}

	internal static void LoadSeed()
	{
		string text = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.currentSaveFileName : null);
		int seed = 0;
		try
		{
			if (!string.IsNullOrEmpty(text) && ES3.KeyExists("jacob.MoonRotation.Seed", text))
			{
				seed = ES3.Load<int>("jacob.MoonRotation.Seed", text);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Couldn't read the rotation seed: " + ex.Message));
		}
		if (seed == 0)
		{
			NewSeed(text, out seed);
		}
		Rotation.HostSeed = seed;
		Rotation.HostSeedLoaded = true;
	}

	internal static void NewSeed(string file, out int seed)
	{
		seed = new Random(Guid.NewGuid().GetHashCode()).Next(1, int.MaxValue);
		try
		{
			if (!string.IsNullOrEmpty(file))
			{
				ES3.Save<int>("jacob.MoonRotation.Seed", seed, file);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Couldn't save the rotation seed: " + ex.Message));
		}
		Plugin.Log.LogInfo((object)("New moon rotation seed for " + file));
	}
}
internal static class Hooks
{
	private static TerminalNode _blocked;

	internal static void AfterVisibleFilter(ref IEnumerable<DawnMoonInfo> __result)
	{
		try
		{
			__result = Rotation.Filter(__result);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Filter: " + ex.Message));
		}
	}

	internal static void BeforeLoadNewNode(ref TerminalNode node)
	{
		try
		{
			if (!((Object)(object)node == (Object)null) && Rotation.Active)
			{
				int num = ((node.buyRerouteToMoon >= 0) ? node.buyRerouteToMoon : node.displayPlanetInfo);
				if (num >= 0 && !Rotation.IsAvailable(num))
				{
					node = Blocked();
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Route check: " + ex.Message));
		}
	}

	private static TerminalNode Blocked()
	{
		if ((Object)(object)_blocked == (Object)null)
		{
			_blocked = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)_blocked).name = "MoonRotationOutOfRange";
			_blocked.clearPreviousText = true;
			_blocked.buyRerouteToMoon = -1;
			_blocked.displayPlanetInfo = -1;
			_blocked.buyItemIndex = -1;
			_blocked.shipUnlockableID = -1;
			_blocked.maxCharactersToType = 25;
			_blocked.terminalEvent = "";
		}
		_blocked.displayText = "\n\nThat moon is out of autopilot range " + Rotation.PeriodWord() + ".\nType MOONS to see the moons in range.\n\n";
		return _blocked;
	}

	internal static void AfterTextPostProcess(ref string __result)
	{
		try
		{
			if (!Rotation.Active || !Plugin.ShowRangeLine.Value || string.IsNullOrEmpty(__result) || __result.IndexOf("exomoons catalogue", StringComparison.OrdinalIgnoreCase) < 0 || __result.Contains("moons in autopilot range"))
			{
				return;
			}
			Rotation.EnsureComputed();
			int num = __result.IndexOf("____");
			if (num >= 0)
			{
				int num2 = __result.IndexOf('\n', num);
				if (num2 >= 0)
				{
					string value = "\n" + Rotation.PickedCount + " of " + Rotation.EligibleCount + " moons in autopilot range " + Rotation.PeriodWord() + ".\n";
					__result = __result.Insert(num2 + 1, value);
				}
			}
		}
		catch
		{
		}
	}

	internal static void AfterStartOfRoundStart()
	{
		try
		{
			Net.EnsureRegistered();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Network setup: " + ex.Message));
		}
	}

	internal static void AfterFired()
	{
		try
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.IsServer)
			{
				Runner.NewSeed(((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.currentSaveFileName : null, out var seed);
				Rotation.HostSeed = seed;
				Rotation.HostSeedLoaded = true;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Reseed: " + ex.Message));
		}
	}

	internal static void BeforeSetPlanetsWeather(StartOfRound __instance)
	{
		try
		{
			WeatherFloor.Run(__instance);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Clear-weather floor: " + ex.Message));
		}
	}

	internal static void AfterRouteRandomCheck(CompatibleNoun __0, ref bool __result)
	{
		try
		{
			if (!__result || !Rotation.Active || (Object)(object)__0?.result == (Object)null)
			{
				return;
			}
			int num = __0.result.displayPlanetInfo;
			if (num < 0 && __0.result.terminalOptions != null)
			{
				CompatibleNoun[] terminalOptions = __0.result.terminalOptions;
				foreach (CompatibleNoun val in terminalOptions)
				{
					if ((Object)(object)val?.result != (Object)null && val.result.buyRerouteToMoon >= 0)
					{
						num = val.result.buyRerouteToMoon;
						break;
					}
				}
			}
			if (num >= 0 && !Rotation.IsAvailable(num))
			{
				__result = false;
			}
		}
		catch
		{
		}
	}
}
internal static class QuietTypes
{
	private static readonly Dictionary<string, Type> _hits;

	private static readonly Dictionary<string, int> _misses;

	private static readonly object _lock;

	private static int _generation;

	static QuietTypes()
	{
		_hits = new Dictionary<string, Type>(StringComparer.Ordinal);
		_misses = new Dictionary<string, int>(StringComparer.Ordinal);
		_lock = new object();
		try
		{
			AppDomain.CurrentDomain.AssemblyLoad += delegate
			{
				lock (_lock)
				{
					_generation++;
				}
			};
		}
		catch
		{
		}
	}

	internal static Type Find(string fullName)
	{
		if (string.IsNullOrEmpty(fullName))
		{
			return null;
		}
		int generation;
		lock (_lock)
		{
			if (_hits.TryGetValue(fullName, out var value))
			{
				return value;
			}
			if (_misses.TryGetValue(fullName, out var value2) && value2 == _generation)
			{
				return null;
			}
			generation = _generation;
		}
		Type type = Scan(fullName);
		lock (_lock)
		{
			if (type != null)
			{
				_hits[fullName] = type;
				_misses.Remove(fullName);
			}
			else
			{
				_misses[fullName] = generation;
			}
		}
		return type;
	}

	private static Type Scan(string fullName)
	{
		Assembly[] assemblies;
		try
		{
			assemblies = AppDomain.CurrentDomain.GetAssemblies();
		}
		catch
		{
			return null;
		}
		Assembly[] array = assemblies;
		foreach (Assembly assembly in array)
		{
			Type type = null;
			try
			{
				type = assembly.GetType(fullName, throwOnError: false);
			}
			catch
			{
			}
			if (type != null)
			{
				return type;
			}
		}
		return null;
	}
}
internal static class WeatherFloor
{
	internal const string WeatherRegistryId = "mrov.WeatherRegistry";

	internal const string WeatherTweaksId = "WeatherTweaks";

	private const int Salt = 1129075538;

	private static bool _resolved;

	private static bool _ok;

	private static int _errors;

	private static bool _saveWarned;

	private static MethodInfo _changeWeather;

	private static PropertyInfo _setupFinished;

	private static PropertyInfo _selectWeathers;

	private static FieldInfo _currentWeathers;

	private static MethodInfo _cwContains;

	private static MethodInfo _cwGetType;

	private static PropertyInfo _cwNames;

	private static MethodInfo _getWeather;

	private static PropertyInfo _noneWeather;

	private static PropertyInfo _weathers;

	private static PropertyInfo _wName;

	private static PropertyInfo _wDefaultWeight;

	private static PropertyInfo _wLevelWeights;

	private static PropertyInfo _wWeatherWeights;

	private static FieldInfo _saveKey;

	private static MethodInfo _jsonSerialize;

	private static bool Resolve()
	{
		if (_resolved)
		{
			return _ok;
		}
		_resolved = true;
		Type type = QuietTypes.Find("WeatherRegistry.WeatherController");
		if (type == null)
		{
			Plugin.Log.LogInfo((object)"WeatherRegistry not found; MinClearMoons does nothing.");
			return false;
		}
		try
		{
			Type type2 = QuietTypes.Find("WeatherRegistry.WeatherManager");
			Type type3 = QuietTypes.Find("WeatherRegistry.Settings");
			Type type4 = QuietTypes.Find("WeatherRegistry.Modules.CurrentWeathers");
			Type type5 = QuietTypes.Find("WeatherRegistry.Weather");
			Type type6 = QuietTypes.Find("WeatherRegistry.Defaults");
			_changeWeather = AccessTools.Method(type, "ChangeWeather", new Type[2]
			{
				typeof(SelectableLevel),
				typeof(LevelWeatherType)
			}, (Type[])null);
			_setupFinished = AccessTools.Property(type2, "IsSetupFinished");
			_selectWeathers = AccessTools.Property(type3, "SelectWeathers");
			_currentWeathers = AccessTools.Field(type2, "CurrentWeathers");
			_cwContains = AccessTools.Method(type4, "Contains", new Type[1] { typeof(SelectableLevel) }, (Type[])null);
			_cwGetType = AccessTools.Method(type4, "GetWeatherType", new Type[1] { typeof(SelectableLevel) }, (Type[])null);
			_cwNames = AccessTools.Property(type4, "GetWeatherNames");
			_getWeather = AccessTools.Method(type2, "GetWeather", new Type[1] { typeof(LevelWeatherType) }, (Type[])null);
			_noneWeather = AccessTools.Property(type2, "NoneWeather");
			_weathers = AccessTools.Property(type2, "Weathers");
			_wName = AccessTools.Property(type5, "Name");
			_wDefaultWeight = AccessTools.Property(type5, "DefaultWeight");
			_wLevelWeights = AccessTools.Property(type5, "LevelWeights");
			_wWeatherWeights = AccessTools.Property(type5, "WeatherWeights");
			_saveKey = ((type6 == null) ? null : AccessTools.Field(type6, "WeatherSaveKey"));
			Type type7 = QuietTypes.Find("Newtonsoft.Json.JsonConvert");
			_jsonSerialize = ((type7 == null) ? null : AccessTools.Method(type7, "SerializeObject", new Type[1] { typeof(object) }, (Type[])null));
			List<string> list = new List<string>();
			if (_changeWeather == null)
			{
				list.Add("WeatherController.ChangeWeather(level, type)");
			}
			if (_setupFinished == null)
			{
				list.Add("WeatherManager.IsSetupFinished");
			}
			if (_selectWeathers == null)
			{
				list.Add("Settings.SelectWeathers");
			}
			if (_currentWeathers == null || _cwContains == null || _cwGetType == null)
			{
				list.Add("WeatherManager.CurrentWeathers");
			}
			if (list.Count > 0)
			{
				Plugin.Log.LogWarning((object)("WeatherRegistry is missing " + string.Join(", ", list.ToArray()) + "; MinClearMoons is off."));
				return false;
			}
			if (_cwNames == null || _saveKey == null || _jsonSerialize == null)
			{
				Plugin.Log.LogWarning((object)"Can't write WeatherRegistry's save entry; cleared moons are re-cleared on reload instead.");
			}
			_ok = true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("WeatherRegistry lookup failed, MinClearMoons is off: " + ex.Message));
		}
		return _ok;
	}

	internal static void Run(StartOfRound sor)
	{
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Invalid comparison between Unknown and I4
		if (_errors >= 3 || (Object)(object)sor == (Object)null || Plugin.MinClearMoons.Value <= 0)
		{
			return;
		}
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
		{
			return;
		}
		try
		{
			if (!Resolve() || !(bool)_setupFinished.GetValue(null, null) || !(bool)_selectWeathers.GetValue(null, null))
			{
				return;
			}
			Runner.UpdateHostKey(sor);
			Rotation.EnsureComputed();
			HashSet<int> hashSet = Rotation.InRangeIds();
			if (hashSet.Count == 0 || sor.levels == null)
			{
				return;
			}
			int num = ((sor.gameStats != null) ? sor.gameStats.daysSpent : 0);
			object value = _currentWeathers.GetValue(null);
			List<FloorMoon> list = new List<FloorMoon>();
			Dictionary<int, SelectableLevel> dictionary = new Dictionary<int, SelectableLevel>();
			SelectableLevel[] levels = sor.levels;
			foreach (SelectableLevel val in levels)
			{
				if (!((Object)(object)val == (Object)null) && hashSet.Contains(val.levelID) && !Rotation.IsCompany(val) && !dictionary.ContainsKey(val.levelID))
				{
					int num2 = WeatherOf(value, val);
					dictionary[val.levelID] = val;
					list.Add(new FloorMoon
					{
						Id = val.levelID,
						Name = ClearFloor.Numberless(val.PlanetName),
						Weather = WeatherName(num2),
						Clear = ClearFloor.IsClear(num2),
						CanBeClear = CanBeNone(val),
						Forced = (val.overrideWeather && (int)val.overrideWeatherType != -1),
						Locked = ((Object)(object)val == (Object)(object)sor.currentLevel || val.levelID == sor.currentLevelID)
					});
				}
			}
			int value2 = Plugin.MinClearMoons.Value;
			FloorPlan floorPlan = ClearFloor.Plan(list, value2, Rotation.MakeKey(Rotation.HostSeed ^ 0x434C5352, RotateMode.Day, num));
			if (!floorPlan.Acts)
			{
				_errors = 0;
				return;
			}
			List<FloorMoon> list2 = new List<FloorMoon>();
			foreach (FloorMoon item in floorPlan.ToClear)
			{
				SelectableLevel val2 = dictionary[item.Id];
				_changeWeather.Invoke(null, new object[2]
				{
					val2,
					(object)(LevelWeatherType)(-1)
				});
				if (ClearFloor.IsClear(WeatherOf(_currentWeathers.GetValue(null), val2)))
				{
					list2.Add(item);
					continue;
				}
				Plugin.Log.LogWarning((object)("WeatherRegistry didn't change " + item.Name + " to None (still " + WeatherName(WeatherOf(_currentWeathers.GetValue(null), val2)) + ")."));
			}
			floorPlan.ToClear = list2;
			Plugin.Log.LogInfo((object)ClearFloor.Describe(floorPlan, value2));
			if (list2.Count > 0)
			{
				SaveDay(num);
			}
			_errors = 0;
		}
		catch (Exception ex)
		{
			_errors++;
			Exception ex2 = ((ex is TargetInvocationException && ex.InnerException != null) ? ex.InnerException : ex);
			Plugin.Log.LogWarning((object)("Clear-weather floor error " + _errors + "/3" + ((_errors >= 3) ? " (now off until restart)" : "") + ": " + ex2.Message));
		}
	}

	private static int WeatherOf(object cw, SelectableLevel level)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected I4, but got Unknown
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected I4, but got Unknown
		if (cw != null && (bool)_cwContains.Invoke(cw, new object[1] { level }))
		{
			return (int)(LevelWeatherType)_cwGetType.Invoke(cw, new object[1] { level });
		}
		return (int)level.currentWeather;
	}

	private static string WeatherName(int type)
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (type == -1)
			{
				return "None";
			}
			object obj = ((_getWeather != null) ? _getWeather.Invoke(null, new object[1] { (object)(LevelWeatherType)type }) : null);
			string text = ((obj != null && _wName != null) ? (_wName.GetValue(obj, null) as string) : null);
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
		}
		catch
		{
		}
		return ((object)(LevelWeatherType)type/*cast due to .constrained prefix*/).ToString();
	}

	private static bool CanBeNone(SelectableLevel level)
	{
		try
		{
			object obj = ((_noneWeather != null) ? _noneWeather.GetValue(null, null) : null);
			if (obj == null)
			{
				return true;
			}
			IDictionary dictionary = ((_wLevelWeights != null) ? (_wLevelWeights.GetValue(obj, null) as IDictionary) : null);
			if (dictionary != null && dictionary.Contains(level))
			{
				return (int)dictionary[level] > 0;
			}
			if (_wDefaultWeight != null && (int)_wDefaultWeight.GetValue(obj, null) > 0)
			{
				return true;
			}
			IEnumerable enumerable = ((_weathers != null) ? (_weathers.GetValue(null, null) as IEnumerable) : null);
			if (enumerable == null || _wWeatherWeights == null)
			{
				return true;
			}
			foreach (object item in enumerable)
			{
				IDictionary dictionary2 = ((item == null) ? null : (_wWeatherWeights.GetValue(item, null) as IDictionary));
				if (dictionary2 != null && dictionary2.Contains((object)(LevelWeatherType)(-1)) && (int)dictionary2[(object)(LevelWeatherType)(-1)] > 0)
				{
					return true;
				}
			}
			return false;
		}
		catch
		{
			return true;
		}
	}

	private static void SaveDay(int day)
	{
		try
		{
			if (_cwNames == null || _saveKey == null || _jsonSerialize == null)
			{
				return;
			}
			string text = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.currentSaveFileName : null);
			string text2 = _saveKey.GetValue(null) as string;
			if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(text2))
			{
				return;
			}
			string text3 = text2 + "-" + day;
			if (ES3.KeyExists(text3, text))
			{
				object value = _cwNames.GetValue(_currentWeathers.GetValue(null), null);
				string text4 = ((value == null) ? null : (_jsonSerialize.Invoke(null, new object[1] { value }) as string));
				if (!string.IsNullOrEmpty(text4))
				{
					ES3.Save<string>(text3, text4, text);
				}
			}
		}
		catch (Exception ex)
		{
			if (!_saveWarned)
			{
				_saveWarned = true;
				Plugin.Log.LogWarning((object)("Couldn't update WeatherRegistry's saved weathers (cleared moons are re-cleared on reload instead): " + ex.Message));
			}
		}
	}
}