Decompiled source of Riverheim Config v3.1.1

BepInEx\plugins\RiverheimConfigTest.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	public class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase()
	{
		public readonly ConfigEntry<T> SourceConfig = sourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	public abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	public sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	public class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName);
							}).ToList();
							SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false);
							SendAdmin(list, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_004c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0052: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend != 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> list = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							list.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						list.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)methodInfo == null) ? ((object)val.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2]
							{
								val,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section;

			public string key;

			public Type type;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected;

			public string received;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0051;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag == true;
				}
				if (num)
				{
					return !lockExempt;
				}
				goto IL_0051;
				IL_0051:
				return false;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin
		{
			get
			{
				if (!lockExempt)
				{
					return isSourceOfTruth;
				}
				return true;
			}
		}

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; }

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(0L, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(0L, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					MemoryStream stream = new MemoryStream(package.ReadByteArray());
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
					val2.Save();
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null)
			{
				if (!configSync.IsLocked)
				{
					if (config == configSync.lockedConfig)
					{
						return lockExempt;
					}
					return true;
				}
				return false;
			}
			return true;
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage val = new ZPackage();
						val.Write((byte)2);
						val.Write(packageIdentifier);
						val.Write(fragment);
						val.Write(fragments);
						val.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(val);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != 0L)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] array = package.GetArray();
			if (array != null && array.LongLength > 10000)
			{
				ZPackage val = new ZPackage();
				val.Write((byte)4);
				MemoryStream memoryStream = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
				{
					deflateStream.Write(array, 0, array.Length);
				}
				val.Write(memoryStream.ToArray());
				package = val;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			if (!type.IsEnum)
			{
				return type;
			}
			return Enum.GetUnderlyingType(type);
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write(partial ? ((byte)1) : ((byte)0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	public class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				string text = minimumRequiredVersion;
				if (text == null)
				{
					if (!ModRequired)
					{
						return "0.0.0";
					}
					text = CurrentVersion;
				}
				return text;
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return num && flag;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return DisplayName + " is not installed on the server.";
			}
			if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)))
			{
				return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + ".";
			}
			return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".";
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			if (rpc != null)
			{
				return ErrorServer(rpc);
			}
			return ErrorClient();
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				Debug.LogWarning((object)array2[i].Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					TMP_Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed.";
					flag = true;
				}
			}
			if (flag)
			{
				RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>();
				Vector2 sizeDelta = component.sizeDelta;
				sizeDelta.x = 675f;
				component.sizeDelta = sizeDelta;
				__instance.m_connectionFailedError.ForceMeshUpdate(false, false);
				float num = __instance.m_connectionFailedError.renderedHeight + 105f;
				RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>();
				component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f);
				sizeDelta = component.sizeDelta;
				sizeDelta.y = num;
				component.sizeDelta = sizeDelta;
			}
		}
	}
}
namespace RiverheimConfig
{
	[BepInPlugin("com.valheim.riverheim.config", "Riverheim Config", "3.1.1")]
	public sealed class RiverheimConfigPlugin : BaseUnityPlugin
	{
		private const string PluginGuid = "com.valheim.riverheim.config";

		private const string PluginName = "Riverheim Config";

		private const string PluginVersion = "3.1.1";

		private const string MinimumCompatibleVersion = "3.0.0";

		private const string RiverheimConfigMethod = "Riverheim.Configuration.ConfigManager:GetConfig";

		private static ManualLogSource log;

		private static ConfigSync configSync;

		private static bool patchApplied;

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

		private FileSystemWatcher watcher;

		private void Awake()
		{
			log = ((BaseUnityPlugin)this).Logger;
			configSync = new ConfigSync("com.valheim.riverheim.config")
			{
				DisplayName = "Riverheim Config",
				CurrentVersion = "3.1.1",
				MinimumRequiredVersion = "3.0.0"
			};
			BindConfiguration();
			WatchConfigFile();
		}

		private void WatchConfigFile()
		{
			try
			{
				watcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath));
				watcher.Changed += OnConfigFileChanged;
				watcher.Created += OnConfigFileChanged;
				watcher.Renamed += OnConfigFileChanged;
				watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
				watcher.EnableRaisingEvents = true;
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Could not watch the config file for changes; restart the game after editing it. " + ex.Message));
			}
		}

		private void OnConfigFileChanged(object sender, FileSystemEventArgs args)
		{
			if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
			{
				return;
			}
			try
			{
				((BaseUnityPlugin)this).Config.Reload();
				log.LogInfo((object)"Config file reloaded. The new values apply to the next world you create or load.");
			}
			catch (Exception ex)
			{
				log.LogError((object)("Could not reload the config file: " + ex.Message));
			}
		}

		private IEnumerator Start()
		{
			yield return null;
			ApplyPatch();
		}

		private void BindConfiguration()
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			RiverheimSettings.Setting[] all = RiverheimSettings.All;
			foreach (RiverheimSettings.Setting setting in all)
			{
				string text = setting.Description + " Riverheim default: " + setting.DefaultText + " (leave it there to keep Riverheim's own value).";
				if (setting.PreviewNote != null)
				{
					text = text + " " + setting.PreviewNote;
				}
				if (setting.IsInteger)
				{
					ConfigDescription val = new ConfigDescription(text, (AcceptableValueBase)(object)new AcceptableValueRange<int>((int)setting.Min, (int)setting.Max), Array.Empty<object>());
					ConfigEntry<int> val2 = ((BaseUnityPlugin)this).Config.Bind<int>(setting.Section, setting.Key, (int)setting.Default, val);
					configSync.AddConfigEntry<int>(val2).SynchronizedConfig = true;
					entries[setting.Id] = (ConfigEntryBase)(object)val2;
				}
				else
				{
					ConfigDescription val3 = new ConfigDescription(text, (AcceptableValueBase)(object)new AcceptableValueRange<double>(setting.Min, setting.Max), Array.Empty<object>());
					ConfigEntry<double> val4 = ((BaseUnityPlugin)this).Config.Bind<double>(setting.Section, setting.Key, setting.Default, val3);
					configSync.AddConfigEntry<double>(val4).SynchronizedConfig = true;
					entries[setting.Id] = (ConfigEntryBase)(object)val4;
				}
			}
		}

		private static void ApplyPatch()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method("Riverheim.Configuration.ConfigManager:GetConfig", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				log.LogError((object)"Riverheim's ConfigManager.GetConfig was not found. Riverheim Config 3.1.1 is disabled; install Gurebu-Riverheim 1.2.x or 1.3.x.");
				return;
			}
			Harmony val = new Harmony("com.valheim.riverheim.config");
			val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(RiverheimConfigPlugin), "PatchGenerationConfig", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			patchApplied = true;
			log.LogInfo((object)"Riverheim configuration patch applied. Server configuration is synchronized to clients.");
			try
			{
				ExpandWorldSizeCompatibility.Apply(val, log);
			}
			catch (Exception ex)
			{
				log.LogError((object)("Could not apply the Expand World Size stretch fix: " + ex));
			}
		}

		private static void PatchGenerationConfig(ref object __result)
		{
			if (__result == null)
			{
				log.LogError((object)"Riverheim returned a null world generation configuration.");
				return;
			}
			Dictionary<string, double> dictionary = new Dictionary<string, double>();
			foreach (KeyValuePair<string, ConfigEntryBase> entry in entries)
			{
				dictionary[entry.Key] = Convert.ToDouble(entry.Value.BoxedValue, CultureInfo.InvariantCulture);
			}
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			RiverheimSettings.Apply(__result, dictionary, force: false, list, list2);
			if (list2.Count > 0)
			{
				log.LogWarning((object)("This Riverheim build has no field for: " + string.Join(", ", list2.ToArray()) + ". Those settings were left out."));
			}
			if (list.Count > 0)
			{
				log.LogError((object)("Riverheim's configuration layout changed or a value is invalid; these settings were not applied: " + string.Join(", ", list.ToArray())));
			}
			else
			{
				log.LogInfo((object)("Applied Riverheim config: " + RiverheimSettings.Summary(dictionary) + "."));
			}
		}

		private void OnDestroy()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (watcher != null)
			{
				watcher.Dispose();
				watcher = null;
			}
			if (patchApplied)
			{
				new Harmony("com.valheim.riverheim.config").UnpatchSelf();
				patchApplied = false;
			}
		}
	}
	public static class RiverheimSettings
	{
		public sealed class Section
		{
			public string Name;

			public string Title;
		}

		public sealed class Setting
		{
			public string Section;

			public string Key;

			public string Label;

			public double Default;

			public bool IsInteger;

			public double Min;

			public double Max;

			public double Step;

			public int Decimals;

			public string Path;

			public string Description;

			public bool Optional;

			public string PreviewNote;

			public string Id => Section + "|" + Key;

			public string DefaultText => Default.ToString(CultureInfo.InvariantCulture);
		}

		public const string World = "1. World";

		public const string Rivers = "2. Rivers";

		public const string Lakes = "3. Lakes";

		public const string Biomes = "4. Biomes";

		public const string Amounts = "5. Biome Amounts";

		public const string Bands = "6. Biome Bands";

		public const string Landmass = "7. Landmass";

		public const string Mountains = "8. Mountains";

		public const string RiverFeatures = "9. River Features";

		public const string SubBiomes = "10. Sub-biomes";

		public const string Terrain = "11. Terrain";

		public const string Patches = "12. Biome Patches";

		public const string Forests = "13. Forests";

		public static readonly Section[] Sections = new Section[13]
		{
			new Section
			{
				Name = "1. World",
				Title = "World (to change the world size, use World size at the bottom)"
			},
			new Section
			{
				Name = "2. Rivers",
				Title = "Rivers"
			},
			new Section
			{
				Name = "3. Lakes",
				Title = "Lakes"
			},
			new Section
			{
				Name = "4. Biomes",
				Title = "Biome placement bias"
			},
			new Section
			{
				Name = "5. Biome Amounts",
				Title = "Biome amounts (share of contested land)"
			},
			new Section
			{
				Name = "6. Biome Bands",
				Title = "Biome bands (% of the way from spawn to the world edge)"
			},
			new Section
			{
				Name = "7. Landmass",
				Title = "Landmass"
			},
			new Section
			{
				Name = "8. Mountains",
				Title = "Mountains"
			},
			new Section
			{
				Name = "9. River Features",
				Title = "River features"
			},
			new Section
			{
				Name = "10. Sub-biomes",
				Title = "Sub-biomes"
			},
			new Section
			{
				Name = "11. Terrain",
				Title = "Terrain feel"
			},
			new Section
			{
				Name = "12. Biome Patches",
				Title = "Biome patch sizes"
			},
			new Section
			{
				Name = "13. Forests",
				Title = "Forests"
			}
		};

		private const string Affinity = "world.biomes.affinity.main.";

		private const int UnsafeRadiusMin = 7800;

		private const int UnsafeRadiusMax = 9000;

		private const string Placement = "world.biomes.competitivePlacement.main.biomes.";

		private const string Plateaus = "world.splats.plateaus.main.";

		private const string SourceSplats = "world.splats.riverSourceSplats.main.";

		public static readonly Setting[] All = new Setting[101]
		{
			Number("1. World", "WorldRadius", "World radius (m)", 10500.0, 4000.0, 100000.0, 500.0, 0, "common.worldSize", "Radius of the world Riverheim generates, in metres. Keep 10500 and use Expand World Size stretching for a bigger or smaller world: biome bands scale with this value, but the Ashlands and Deep North (which always begin 8000 m from the centre, where the game itself puts them), the landmass swirl and the rainfall pattern do not, so changing it distorts the layout. Values from 7800 to 9000 are refused and Riverheim's own radius is kept: there the world edge runs into the Ashlands and Deep North belts and Riverheim cannot generate the world. Below 4000 Riverheim cannot generate the world either."),
			Number("1. World", "TileSpacing", "Tile spacing (m)", 60.0, 10.0, 150.0, 5.0, 0, "common.tileSpacing", "Distance between generation points in metres. Lower values add detail but take much longer (10: about 30 times longer), and river and lake counts grow with the number of points. Any change gives a different world for the same seed. Above 150 Riverheim can fail to generate the world."),
			Number("1. World", "SeaFloorDepth", "Sea floor depth", -40.0, -1000.0, 0.0, 1.0, 1, "common.oceanDepth", "Height the sea floor settles to at the world edge and in the polar trenches, also used as the floor when shaping terrain. More negative values mean deeper edges and trenches. Above 0 Riverheim cannot generate the world."),
			Number("1. World", "OceanBiomeDepth", "Ocean biome depth", -20.0, -1000.0, 1000.0, 1.0, 1, "world.biomes.conditionalPlacement.main.oceanDepth", "Water must be deeper than this, and far enough from the coast, to count as the Ocean biome. More negative values mean fewer waters count as Ocean."),
			Number("1. World", "MountainHeight", "Mountain height", 50.0, 0.0, 200.0, 1.0, 1, "common.mountainHeight", "Height Riverheim treats as mountain level when shaping terrain and scoring which high ground becomes the Mountain biome. Lower values make more mountains. Below 0 or above about 200 Riverheim cannot generate the world."),
			Number("1. World", "StartingAreaRadius", "Starting area (m)", 870.0, 0.0, 10000.0, 50.0, 0, "common.startingAreaRadius", "Size of the gentle area around spawn in metres, where hills are shaped like flatland. Larger values make a bigger gentle start; below about 400 there is no gentle area, the same as 0."),
			Number("2. Rivers", "OriginDensity", "River origin density", 0.25, 0.0, 1.0, 0.05, 2, "world.rivers.origins.main.density", "Share of suitable coastline tiles that become river mouths. Higher values make more rivers, up to about 0.5, where every suitable spot is used; 0 turns rivers off."),
			Whole("2. Rivers", "MinLandNeighbors", "Min land neighbours", 2, 0, 8, "world.rivers.origins.main.minLandNeighbors", "Land tiles a coastline tile needs next to it to start a river. Higher values keep river mouths off thin peninsulas and small islands."),
			Number("2. Rivers", "WidthScale", "Width scale", 140.0, 0.0, 10000.0, 10.0, 1, "world.rivers.width.main.scale", "River width = WidthScale x flow ^ WidthPower + WidthOffset, never below zero. Scales every river's width."),
			Number("2. Rivers", "WidthPower", "Width power", 0.4, 0.0, 10.0, 0.05, 2, "world.rivers.width.main.power", "How strongly river width grows with water flow. Higher values make big rivers much wider than small streams."),
			Number("2. Rivers", "WidthOffset", "Width offset", -6.0, -1000.0, 1000.0, 1.0, 1, "world.rivers.width.main.offset", "Added to every river width. Negative values thin out small streams."),
			Whole("2. Rivers", "MinStrahler", "Min Strahler order", 2, 1, 20, "world.rivers.prune.main.minStrahler", "River branches below this Strahler order are removed. Higher values keep only the bigger branches; with the default Min river width, 1 removes nothing more than 2 does."),
			Number("2. Rivers", "MinWidth", "Min river width (m)", 14.5, 3.0, 1000.0, 0.5, 1, "world.rivers.prune.main.minWidth", "River segments narrower than this are removed. Higher values drop thin streams. The lowest allowed value is 3: at 1 Riverheim fails to generate the world, and at 0 it keeps every trickle and runs out of memory."),
			Number("2. Rivers", "MaxWidthDifference", "Max tributary ratio", 2.2, 0.0, 1000.0, 0.5, 1, "world.rivers.prune.main.maxWidthDiff", "Where rivers join, a side branch is removed if the widest incoming branch is more than this many times wider. Higher values keep more small tributaries; from about 5 up they are all kept, the same as 0."),
			Number("2. Rivers", "MeanderPeriod", "Meander period", 3.4, 0.5, 100.0, 0.1, 2, "world.rivers.meander.main.period", "Length of river bends, measured in river widths, so wider rivers get bigger loops. Higher values make longer, gentler bends; 0 crashes Riverheim, so the minimum is 0.5."),
			Number("2. Rivers", "MeanderAmplitude", "Meander amplitude", 1.35, 0.0, 100.0, 0.05, 2, "world.rivers.meander.main.riverAmplitude", "Strength of river bends. Higher values make rivers wind more."),
			Number("3. Lakes", "Budget", "Lake budget", 0.0055, 0.0, 1.0, 0.0005, 4, "world.height.lakes.main.budget", "Share of generation points picked as lake starting points, which then grow into lakes. Higher values make more lake area."),
			Number("3. Lakes", "NoiseScale", "Lake noise scale", 600.0, 1.0, 100000.0, 50.0, 0, "world.height.lakes.main.affinity.noiseScale", "Size of the random pattern that decides where lakes prefer to form. Larger values group lakes into bigger regions."),
			Number("3. Lakes", "LowlandContribution", "Lowland pull", 0.35, -100.0, 100.0, 0.05, 2, "world.height.lakes.main.affinity.kFlatland", "How strongly lakes prefer flat lowland. Above about 1 it makes no further difference; negative values push lakes away from lowland."),
			Number("3. Lakes", "CuriosityContribution", "Terrain interest pull", 0.8, -100.0, 100.0, 0.05, 2, "world.height.lakes.main.affinity.kCuriosity", "How strongly lakes prefer notable spots along river systems."),
			Number("3. Lakes", "LakeSize", "Lake size (m)", 50.0, 0.0, 300.0, 10.0, 0, "world.height.lakes.main.expansion", "How far lakes grow out from their starting points, in metres (varied by Lake size variability). Lower values leave fewer, smaller lakes; at 300 neighbouring lakes join into large inland waters. Much higher values flood most of the inland (1000), so the maximum is 300."),
			Number("3. Lakes", "LakeSizeVariability", "Lake size variability", 0.7, 0.0, 3.0, 0.1, 2, "world.height.lakes.main.expansionVariability", "How much Lake size varies from place to place, which changes lake shapes and how evenly sized they are. 0 grows every lake by the same distance."),
			Number("3. Lakes", "LakeMinCoastDistance", "Lake distance from sea (m)", 200.0, 0.0, 2000.0, 50.0, 0, "world.height.lakes.main.minCoastalProximity", "Lakes only form on land at least this far from the sea, in metres. 0 also allows lakes near the coast; higher values push lakes inland, where they can gather into a few large lakes (seed 400 at 1500)."),
			Number("4. Biomes", "MeadowsBias", "Meadows bias", 0.0, -1000.0, 1000.0, 1.0, 1, "world.biomes.affinity.main.meadows.bias", "Flat bonus to the Meadows score wherever biomes compete for land. Higher values let it win more land."),
			Number("4. Biomes", "ForestBias", "Black Forest bias", -10.0, -1000.0, 1000.0, 1.0, 1, "world.biomes.affinity.main.forest.bias", "Flat bonus to the Black Forest score wherever biomes compete for land. Higher values let it win more land."),
			Number("4. Biomes", "SwampBias", "Swamp bias", 8.0, -1000.0, 1000.0, 1.0, 1, "world.biomes.affinity.main.swamp.bias", "Flat bonus to the Swamp score wherever biomes compete for land. Higher values let it win more land."),
			Number("4. Biomes", "PlainsBias", "Plains bias", 5.0, -1000.0, 1000.0, 1.0, 1, "world.biomes.affinity.main.plains.bias", "Flat bonus to the Plains score wherever biomes compete for land. Higher values let it win more land."),
			Number("4. Biomes", "MistlandsBias", "Mistlands bias", 0.0, -1000.0, 1000.0, 1.0, 1, "world.biomes.affinity.main.mistlands.bias", "Flat bonus to the Mistlands score wherever biomes compete for land. Higher values let it win more land."),
			Number("5. Biome Amounts", "MeadowsWeight", "Meadows amount", 69.5, 0.0, 100000.0, 10.0, 1, "world.biomes.competitivePlacement.main.biomes.meadows.weight", "How much of the contested land Meadows takes. Biomes claim land in proportion to these amounts, so raising one gives that biome more land within its bands."),
			Number("5. Biome Amounts", "ForestWeight", "Black Forest amount", 258.5, 0.0, 100000.0, 10.0, 1, "world.biomes.competitivePlacement.main.biomes.forest.weight", "How much of the contested land Black Forest takes. Biomes claim land in proportion to these amounts, so raising one gives that biome more land within its bands. Riverheim 1.1.1 moved 2.5 of this to the lowland Black Forest variant."),
			Number("5. Biome Amounts", "SwampWeight", "Swamp amount", 76.0, 0.0, 100000.0, 10.0, 1, "world.biomes.competitivePlacement.main.biomes.swamp.weight", "How much of the contested land Swamp takes. Biomes claim land in proportion to these amounts, so raising one gives that biome more land within its bands."),
			Number("5. Biome Amounts", "PlainsWeight", "Plains amount", 283.0, 0.0, 100000.0, 10.0, 1, "world.biomes.competitivePlacement.main.biomes.plains.weight", "How much of the contested land Plains takes. Biomes claim land in proportion to these amounts, so raising one gives that biome more land within its bands."),
			Number("5. Biome Amounts", "MistlandsWeight", "Mistlands amount", 305.0, 0.0, 100000.0, 10.0, 1, "world.biomes.competitivePlacement.main.biomes.mistlands.weight", "How much of the contested land Mistlands takes. Biomes claim land in proportion to these amounts, so raising one gives that biome more land within its bands."),
			Number("5. Biome Amounts", "MarshWeight", "Marsh amount", 5.5, 0.0, 100000.0, 1.0, 1, "world.biomes.competitivePlacement.main.biomes.marsh.weight", "How much of the contested land Marsh takes. Marsh is the rare, mostly submerged sub-biome of Meadows found next to water; the game treats it as Meadows. Raising this makes more marsh patches."),
			Newer(Number("5. Biome Amounts", "ForestLowlandsWeight", "Lowland Black Forest amount", 2.5, 0.0, 100000.0, 1.0, 1, "world.biomes.competitivePlacement.main.biomes.forestLowlands.weight", "How much of the contested land the lowland Black Forest variant takes. It only appears near spawn and prefers low ground close to water, to put tin within early reach. 0 turns it off.")),
			Number("6. Biome Bands", "MeadowsFadeEnd", "Meadows fades by (%)", 50.0, 1.0, 150.0, 1.0, 1, null, "Meadows becomes less likely the further you travel from spawn and reaches its full penalty at this percentage of the world radius. Lower values keep Meadows closer to spawn."),
			Number("6. Biome Bands", "SwampStart", "Swamp starts (%)", 20.0, 3.0, 150.0, 1.0, 1, null, "Swamp can appear from this percentage of the way from spawn to the world edge (travel distance), fading in over the 2% before it."),
			Number("6. Biome Bands", "SwampEnd", "Swamp ends (%)", 58.0, 3.0, 150.0, 1.0, 1, null, "Swamp stops appearing past this percentage of the way from spawn to the world edge, fading out over the next 2%."),
			Number("6. Biome Bands", "PlainsStart", "Plains starts (%)", 29.0, 3.0, 150.0, 1.0, 1, null, "Plains can appear from this percentage of the way from spawn to the world edge (travel distance), fading in over the 2% before it."),
			Number("6. Biome Bands", "PlainsEnd", "Plains ends (%)", 66.0, 3.0, 150.0, 1.0, 1, null, "Plains stops appearing past this percentage of the way from spawn to the world edge, fading out over the next 2%."),
			Number("6. Biome Bands", "MistlandsStart", "Mistlands starts (%)", 60.0, 6.0, 150.0, 1.0, 1, null, "Mistlands can appear from this percentage of the way from spawn to the world edge (travel distance) onwards, fading in over the 5% before it."),
			Number("7. Landmass", "LandCohesion", "Land cohesion", 0.4, 0.0, 100.0, 0.1, 2, "world.landmass.painter.main.layerPainter.cohesionWeighting", "How strongly new land sticks to land already painted. Higher values gather the land into fewer, larger continents; lower values scatter it into more islands. AtlasBuilder's single-landmass Token preset uses 20."),
			Number("7. Landmass", "LandDistanceWeighting", "Land distance weighting", 0.5, 0.0, 100.0, 0.1, 2, "world.landmass.painter.main.layerPainter.distanceWeighting", "How much distance from already painted land counts when Riverheim decides where to paint more. Higher values keep landmasses more compact."),
			Whole("7. Landmass", "SwirlRays", "Swirl arms", 8, 0, 32, "world.landmass.restrictions.main.swirl.rays", "Number of arms in the spiral pattern that keeps landmasses apart and gives Riverheim worlds their swirl. 0 turns the swirl off (AtlasBuilder's Mini preset does this)."),
			Number("7. Landmass", "SwirlExponent", "Swirl twist", 1.4, 0.0, 10.0, 0.1, 2, "world.landmass.restrictions.main.swirl.exponent", "How quickly the swirl arms wind round as they go outwards. Higher values twist the arms more; 1 or less turns the swirl off, leaving land in large round masses."),
			Number("7. Landmass", "SwirlStartRadius", "Swirl start radius (m)", 5800.0, 0.0, 100000.0, 100.0, 0, "world.landmass.restrictions.main.swirl.startRadius", "Distance from the centre, in metres, where the swirl arms begin to shape the land. Smaller values bring the swirl closer to spawn; beyond the world radius there is no swirl at all."),
			Number("7. Landmass", "HarborRadius", "Harbor radius (m)", 1700.0, 0.0, 100000.0, 100.0, 0, "world.landmass.restrictions.main.harbor.radius", "Size of the sheltered water area Riverheim keeps near the centre of the world, in metres. 0 removes it (AtlasBuilder's Mini preset does this)."),
			Number("7. Landmass", "HarborCircularity", "Harbor circularity", 0.045, 0.0, 10.0, 0.005, 3, "world.landmass.restrictions.main.harbor.circularity", "How round the central harbor area is kept. Higher values make it rounder; 0 removes the harbor, like Harbor radius 0."),
			Number("7. Landmass", "SmallIslandSizeThreshold", "Remove islands below (m)", 0.0, 0.0, 4000.0, 10.0, 0, "world.landmass.postprocessing.main.smallIslandSizeThreshold", "Landmasses smaller than about this many metres across are removed after painting. 0 keeps every island; Riverheim's own Deep North region uses 220 to clear small ones. Above about 4000 it can remove every landmass and Riverheim fails."),
			Number("7. Landmass", "CoastalTrimDistance", "Coastal trim distance (m)", 85.0, 0.0, 1000.0, 5.0, 0, "world.landmass.postprocessing.main.coastalTrimDistance", "How far the coastline is trimmed back from the painted land edge, in metres. Higher values make landmasses a bit smaller with more irregular coasts; near 0 the land joins into large continents. Above about 1000 so much land is trimmed that Riverheim fails."),
			Number("7. Landmass", "IslandMergeThreshold", "Island merge threshold", 0.25, 0.0, 10.0, 0.05, 2, "world.landmass.partitionMerging.main.mergeThreshold", "How readily neighbouring land partitions merge into one landmass. Lower values merge more."),
			Number("7. Landmass", "CoastalTrimVariance", "Coastal trim variance", 0.32, 0.0, 2.0, 0.04, 2, "world.landmass.postprocessing.main.coastalTrimVariance", "How much Coastal trim distance varies along the coast. Higher values make more ragged coasts and break off more small islands; 0 trims evenly. Any change reshapes the land across the whole world for the same seed."),
			Number("7. Landmass", "SwirlWarp", "Swirl warp", 0.35, 0.0, 2.0, 0.05, 2, "world.landmass.restrictions.main.featureWarp.intensity", "How strongly noise distorts the edges of the swirl arms, the central harbor and the outer ocean. 0 gives smooth swirl arms; higher values break the land into more, smaller islands. Any change reshapes the land across the whole world for the same seed."),
			Number("8. Mountains", "MountainScoreThreshold", "Mountain biome threshold", 0.85, 0.0, 10.0, 0.05, 2, "world.biomes.conditionalPlacement.main.mountainScoreThreshold", "How well high ground must score as mountain terrain before it becomes the Mountain biome. Lower values turn more high ground into Mountain; above 1 nothing qualifies and the world has no Mountain biome."),
			Number("8. Mountains", "MountainCutdownRatio", "Mountain cut-down ratio", 0.88, 0.0, 1.0, 0.02, 2, "world.height.settlement.main.mountainCutdownRatio", "Share of height taken off the mountain candidates Riverheim does not keep as mountains when it settles the terrain. Higher values flatten rejected mountains more; values up to about 0.5 look the same as 0, which leaves them standing."),
			Number("8. Mountains", "MountainMinPatchSize", "Mountain min patch size", 180.0, 0.0, 100000.0, 10.0, 0, "world.height.settlement.main.mountainMinPatchSize", "Mountain patches smaller than this are culled after settling. Higher values leave only the big ranges."),
			Number("8. Mountains", "MountainSelectionRandomness", "Mountain selection randomness", 4.0, 0.0, 1000.0, 0.5, 1, "world.height.mountainQuality.main.temperature", "Randomness in which mountain candidates are chosen. 0 always picks the best-scoring ones; higher values pick more freely."),
			Number("8. Mountains", "MountainAreaScore", "Mountain area score", 0.02, -10.0, 10.0, 0.005, 3, "world.height.mountainQuality.main.partitionScoring.area", "How much a mountain candidate's area counts in its score. Higher values favour bigger mountain regions."),
			Number("8. Mountains", "MountainEdgeTrim", "Mountain edge trim", 20.0, 0.0, 1000.0, 5.0, 0, "world.height.mountainEdgeProximity.main.trim", "How far mountain edges are trimmed back, in metres. Higher values make mountains smaller and steeper-sided."),
			Number("8. Mountains", "MountainPeakRate", "Mountain peak rate", 0.4, 0.0, 1.0, 0.05, 2, "world.splats.plateaus.main.mountainPeaks.spawnRate", "Share of suitable mountain tops that get a peak feature: a rock spire or a raised, rounded peak. Higher values add more; 0 removes them."),
			Number("8. Mountains", "MountainSpireMinHeight", "Mountain spire min height (m)", 32.0, 0.0, 200.0, 1.0, 0, "world.splats.plateaus.main.mountainPeaks.cragHeight.min", "Lowest height of the rock spires on mountain peaks, in metres above the ground they stand on. Each spire gets a random height between this and the max height."),
			Number("8. Mountains", "MountainSpireMaxHeight", "Mountain spire max height (m)", 45.0, 0.0, 200.0, 1.0, 0, "world.splats.plateaus.main.mountainPeaks.cragHeight.max", "Highest height of the rock spires on mountain peaks, in metres above the ground they stand on. At 200 they show on the map as tall terraced cones."),
			Number("9. River Features", "ChannelWidth", "Channel width (m)", 40.0, 0.0, 500.0, 5.0, 0, "world.rivers.channels.main.width", "Width of channels, the straits Riverheim cuts through large landmasses to connect distant waters. 0 turns channels off. Wide channels need far more memory to generate (500: about 2 GB, 1500: about 15 GB), so the maximum is 500."),
			Number("9. River Features", "ChannelMeanderAmplitude", "Channel meander amplitude", 0.75, 0.0, 100.0, 0.05, 2, "world.rivers.meander.main.channelAmplitude", "Strength of bends in channels, like Meander amplitude for rivers."),
			Number("9. River Features", "RainfallScale", "Rainfall pattern size (m)", 1050.0, 1.0, 100000.0, 50.0, 0, "world.rivers.precipitation.main.noiseScale", "Size of the rainfall pattern that feeds rivers, in metres. Larger values make bigger wet and dry regions."),
			Number("9. River Features", "RainfallVariability", "Rainfall variability", 1.9, 0.0, 100.0, 0.1, 2, "world.rivers.precipitation.main.variability", "Contrast between wet and dry regions. Higher values make river sizes vary more across the world."),
			Number("9. River Features", "RainfallMinimum", "Rainfall minimum", 0.05, 0.001, 10.0, 0.01, 3, "world.rivers.precipitation.main.minimum", "Lowest rainfall any tile gets. Higher values give dry regions more water, so more small rivers survive. Must stay above 0: at exactly 0 Riverheim fails to generate the world."),
			Number("9. River Features", "RainfallBasinContribution", "Basin contribution", 0.7, 0.0, 10.0, 0.05, 2, "world.rivers.precipitation.main.basinContribution", "How much a river's drainage basin adds to its flow. Higher values make long rivers bigger."),
			Number("9. River Features", "SourceCuriosity", "River source features", 0.1, 0.0, 100.0, 0.05, 2, "world.rivers.curiosities.main.sourceMult", "How notable river sources are. Notable spots attract lakes (Terrain interest pull) and local terrain features such as crags and ponds."),
			Number("9. River Features", "ConfluenceCuriosity", "River confluence features", 1.0, 0.0, 100.0, 0.1, 2, "world.rivers.curiosities.main.proximityMult", "How notable places where rivers run close together are. Notable spots attract lakes and local terrain features."),
			Number("9. River Features", "BendCuriosity", "River bend features", 1.0, 0.0, 100.0, 0.1, 2, "world.rivers.curiosities.main.angleMult", "How notable sharp river bends are. Notable spots attract lakes and local terrain features."),
			Number("9. River Features", "SourcePondChance", "River source ponds", 0.6, 0.0, 1.0, 0.05, 2, "world.splats.riverSourceSplats.main.ponds.frequency", "Chance that the source of a long enough river gets a small pond, roughly 20 to 30 m across. 0 removes them. The ponds are small: on a 4096 px map they only show in close-ups."),
			Number("10. Sub-biomes", "MistgladeRate", "Mistglade rate", 0.03, 0.0, 1.0, 0.01, 3, "world.biomes.replacement.main.biomes.mistglade.rate", "Share of Mistlands turned into Mistglade, the rare mist-free sub-biome with mellow terrain. 0 turns Mistglade off."),
			Number("10. Sub-biomes", "MistgladePatchSize", "Mistglade patch size", 117.0, 0.0, 100000.0, 10.0, 0, "world.biomes.replacement.main.biomes.mistglade.placement.targetPatchSize", "Size Mistglade patches aim for, in generation tiles. Larger values make fewer, bigger glades."),
			Number("10. Sub-biomes", "MarshBaseHeight", "Marsh base height", -0.25, -50.0, 50.0, 0.25, 2, "world.biomes.postprocessing.main.marshBaseHeight", "Height marsh ground is pulled towards, relative to sea level. Lower values put more of the marsh under water."),
			Number("10. Sub-biomes", "SwampBaseHeight", "Swamp base height", -0.25, -50.0, 50.0, 0.25, 2, "world.biomes.postprocessing.main.swampBaseHeight", "Height swamp ground is pulled towards, relative to sea level. Lower values put more of the swamp under water."),
			Newer(Number("10. Sub-biomes", "ForestLowlandsShapingOffset", "Lowland forest shaping offset", 2.0, -100.0, 100.0, 0.5, 2, "world.biomes.postprocessing.main.forestLowlandsShapingOffset", "Height offset used when shaping the lowland Black Forest variant's terrain.")),
			Newer(Number("10. Sub-biomes", "ForestLowlandsShapingIntensity", "Lowland forest shaping intensity", 1.25, 0.0, 100.0, 0.25, 2, "world.biomes.postprocessing.main.forestLowlandsShapingIntensity", "How strongly the lowland Black Forest variant's terrain is reshaped. Higher values make it stand out more from normal Black Forest.")),
			Number("11. Terrain", "CliffIntensity", "Cliff intensity", 5.0, 0.0, 100.0, 0.5, 2, "rendering.renderer.cliffs.gradientMagnitude", "How strongly steep slopes are sharpened into cliffs. Higher values make cliffs taller and more frequent; 0 leaves slopes smooth."),
			Number("11. Terrain", "CliffTerraceHeight", "Cliff terrace height", 30.0, 0.0, 1000.0, 5.0, 1, "rendering.renderer.cliffs.terracing.height", "Height between the terraces that cliffs are broken into."),
			Number("11. Terrain", "TerracingStep", "Terracing step", 2.0, 0.0, 100.0, 0.5, 2, "rendering.renderer.shaping.terracingStep", "Height step of the gentle terracing applied to terrain. Larger values make more pronounced steps; 0 removes them."),
			Number("11. Terrain", "FlatlandThreshold", "Flatland amount", 0.275, 0.0, 1.0, 0.025, 3, "world.height.flatlands.main.noiseThreshold", "Threshold of the noise pattern that marks land as flat lowland. Higher values make more flatland; lower values make more rolling terrain. Above about 0.35 the flatland erases mountain ground: at 0.4 the Mountain biome (and its silver) is almost gone."),
			Number("11. Terrain", "LandSlope", "Land slope", 1.06, 0.2, 100.0, 0.05, 2, "world.height.incline.main.land.mult", "Overall steepness of land rising away from water. Higher values make higher, steeper terrain inland. Below 0.2 Riverheim can fail on some seeds."),
			Number("11. Terrain", "ErosionRate", "Erosion rate", 0.12, 0.0, 10.0, 0.02, 2, "world.height.settlement.main.hydraulicErosionRate", "Strength of the water erosion pass that settles the terrain. Higher values wear terrain down and smooth it more."),
			Number("11. Terrain", "MeadowsShapingIntensity", "Meadows shaping intensity", 0.75, 0.0, 100.0, 0.25, 2, "world.biomes.postprocessing.main.meadowsShapingIntensity", "How strongly Meadows terrain is reshaped after biome placement. Higher values make Meadows terrain more distinct from its surroundings."),
			Number("11. Terrain", "PlainsShapingIntensity", "Plains shaping intensity", 0.5, 0.0, 6.0, 0.25, 2, "world.biomes.postprocessing.main.plainsShapingIntensity", "How strongly Plains terrain is reshaped after biome placement. Higher values make Plains terrain more distinct from its surroundings. Above 6 Riverheim cannot generate the world."),
			Number("11. Terrain", "HillRate", "Hill rate", 0.6, 0.0, 1.0, 0.05, 2, "world.splats.plateaus.main.hills.spawnRate", "Share of suitable spots in Meadows, Black Forest and Plains that get a small rounded hill. Higher values add more; 0 removes them."),
			Number("11. Terrain", "ShorePlateauRate", "Shore plateau rate", 0.45, 0.0, 1.0, 0.05, 2, "world.splats.plateaus.main.coastalCliffs.spawnRate", "Share of suitable spots on land next to water (from Shore plateau min height up to 48 m high) that get a raised plateau with a steep side. Higher values add more; 0 removes them."),
			Number("11. Terrain", "ShorePlateauMinHeight", "Shore plateau min height (m)", 19.0, 0.0, 100.0, 1.0, 0, "world.splats.plateaus.main.coastalCliffs.minHeight", "Land next to water must be at least this high, in metres, to get a shore plateau (see Shore plateau rate). Lower values allow them on lower ground, so there are more; from 48 up there are none."),
			Number("11. Terrain", "RiverBankMaxHeight", "River bank max height", 80.0, 0.0, 200.0, 5.0, 0, "rendering.renderer.rivers.profile.maxBankHeight", "Height up to which river banks are carved into the terrain. Lower values carve rivers less deeply; at 0 most rivers are gone from the map. Higher values change little but need much more memory to generate (500: about 4 times as much as the default), so the maximum is 200."),
			Number("11. Terrain", "RiverBankSmoothness", "River bank smoothness", 3.0, 0.5, 30.0, 0.5, 2, "rendering.renderer.rivers.profile.bankSmoothness", "How softly river banks blend into the surrounding land. Higher values make wider, flatter river valleys; at 30 rivers become broad, flooded valleys. At 0 Riverheim cannot generate the world, so the minimum is 0.5."),
			Number("11. Terrain", "MistlandsRoughness", "Mistlands roughness", 130.0, 0.0, 400.0, 10.0, 0, "rendering.renderer.biomes.mistlands.coarseMagnitude", "Height of the Mistlands' jagged hills and gullies. Lower values make smoother Mistlands, and at 0 their edges sink into shallow water; higher values make them rougher and higher."),
			Number("11. Terrain", "SwampPathDepth", "Swamp path depth", -14.75, -40.0, 20.0, 1.0, 2, "rendering.renderer.biomes.swamp.pathBandDepth", "Height of the winding raised paths through swamps. Higher values lift the paths and the swamp ground with them: at 20 the swamp is almost dry. Lower values put more of it under water."),
			Number("12. Biome Patches", "MeadowsPatchSize", "Meadows patch size", 200.0, 50.0, 1000.0, 10.0, 0, "world.biomes.competitivePlacement.main.biomes.meadows.scoring.targetPatchSize", "Size Meadows patches aim for while biomes compete for land. Lower values split Meadows into many small patches and give it more land overall (50: about 70% more land in about 12 times as many patches, seeds 400 and 1337); higher values make fewer, larger patches."),
			Number("12. Biome Patches", "ForestPatchSize", "Black Forest patch size", 230.0, 50.0, 1000.0, 10.0, 0, "world.biomes.competitivePlacement.main.biomes.forest.scoring.targetPatchSize", "Size Black Forest patches aim for while biomes compete for land. Lower values split Black Forest into many small patches and give it more land overall (50: about 18% more land in about 4 times as many patches, seeds 400 and 1337); higher values make fewer, larger patches."),
			Number("12. Biome Patches", "SwampPatchSize", "Swamp patch size", 570.0, 100.0, 3000.0, 10.0, 0, "world.biomes.competitivePlacement.main.biomes.swamp.scoring.targetPatchSize", "Size Swamp patches aim for while biomes compete for land. Lower values split Swamp into many small patches and give it more land overall (100: about 70% more land in about 10 times as many patches, seeds 400 and 1337); higher values make fewer, larger swamps."),
			Number("12. Biome Patches", "PlainsPatchSize", "Plains patch size", 650.0, 100.0, 3000.0, 10.0, 0, "world.biomes.competitivePlacement.main.biomes.plains.scoring.targetPatchSize", "Size Plains patches aim for while biomes compete for land. Lower values split Plains into many small patches and give it more land overall (100: about 11% more land in about 3 times as many patches, seeds 400 and 1337); higher values make fewer, larger patches."),
			Number("12. Biome Patches", "MistlandsPatchSize", "Mistlands patch size", 210.0, 50.0, 1000.0, 10.0, 0, "world.biomes.competitivePlacement.main.biomes.mistlands.scoring.targetPatchSize", "Size Mistlands patches aim for while biomes compete for land. Lower values split Mistlands into many small patches and give it more land overall (50: about 10% more land in about twice as many patches, seeds 400 and 1337); higher values make fewer, larger patches."),
			Number("12. Biome Patches", "MarshPatchSize", "Marsh patch size", 65.0, 10.0, 500.0, 5.0, 0, "world.biomes.competitivePlacement.main.biomes.marsh.scoring.targetPatchSize", "Size Marsh patches aim for while biomes compete for land. Lower values make many small marsh patches; higher values make fewer, larger ones."),
			Number("13. Forests", "ForestPatternSize", "Forest pattern size (m)", 250.0, 50.0, 2000.0, 25.0, 0, "world.forestation.main.noiseScale", "Size, in metres, of the random pattern that sets how densely land is wooded. AtlasBuilder maps show it only as small changes in the dark forest patches near water."),
			Number("13. Forests", "MeadowsRiversideTrees", "Meadows riverside trees", -0.14, -1.0, 1.0, 0.02, 2, "world.forestation.main.meadowsRiverBonus", "Added to how densely Meadows is wooded within 50 m of a river, fading out with distance. Negative values keep Meadows riverbanks open; positive values put forest along them.")
		};

		private static Setting Number(string section, string key, string label, double value, double min, double max, double step, int decimals, string path, string description)
		{
			return new Setting
			{
				Section = section,
				Key = key,
				Label = label,
				Default = value,
				Min = min,
				Max = max,
				Step = step,
				Decimals = decimals,
				Path = path,
				Description = description
			};
		}

		private static Setting Whole(string section, string key, string label, int value, int min, int max, string path, string description)
		{
			return new Setting
			{
				Section = section,
				Key = key,
				Label = label,
				Default = value,
				IsInteger = true,
				Min = min,
				Max = max,
				Step = 1.0,
				Decimals = 0,
				Path = path,
				Description = description
			};
		}

		private static Setting Newer(Setting setting)
		{
			setting.Optional = true;
			return setting;
		}

		public static Setting Find(string section, string key)
		{
			Setting[] all = All;
			foreach (Setting setting in all)
			{
				if (setting.Section == section && setting.Key == key)
				{
					return setting;
				}
			}
			return null;
		}

		public static Dictionary<string, double> Parse(IEnumerable<string> lines)
		{
			Dictionary<string, double> dictionary = new Dictionary<string, double>();
			string section = "";
			foreach (string line in lines)
			{
				string text = line.Trim();
				if (text.Length == 0 || text.StartsWith("#"))
				{
					continue;
				}
				if (text.StartsWith("[") && text.EndsWith("]"))
				{
					section = text.Substring(1, text.Length - 2).Trim();
					continue;
				}
				int num = text.IndexOf('=');
				if (num >= 0)
				{
					Setting setting = Find(section, text.Substring(0, num).Trim());
					if (setting != null && double.TryParse(text.Substring(num + 1).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
					{
						dictionary[setting.Id] = result;
					}
				}
			}
			return dictionary;
		}

		public static void Apply(object config, IDictionary<string, double> values, List<string> failed)
		{
			Apply(config, values, force: true, failed, new List<string>());
		}

		public static void Apply(object config, IDictionary<string, double> values, bool force, List<string> failed, List<string> skipped)
		{
			Setting[] all = All;
			foreach (Setting setting in all)
			{
				if (setting.Path == null)
				{
					continue;
				}
				double value = Value(values, setting.Section, setting.Key);
				if (!force && value == setting.Default)
				{
					continue;
				}
				if (setting.Optional && !Exists(config, setting.Path))
				{
					skipped.Add(setting.Key);
				}
				else if (setting.Key == "WorldRadius" && value >= 7800.0 && value <= 9000.0)
				{
					failed.Add("WorldRadius " + value.ToString(CultureInfo.InvariantCulture) + " (between " + 7800 + " and " + 9000 + " m the world edge runs into the Ashlands and Deep North belts and Riverheim cannot generate the world; Riverheim's own radius was kept)");
				}
				else
				{
					Assign(config, setting.Path, failed, (Type fieldType) => ConvertValue(value, fieldType));
				}
			}
			double num = Value(values, "6. Biome Bands", "MeadowsFadeEnd") / 100.0;
			if (force || Changed(values, "MeadowsFadeEnd"))
			{
				if (num > 0.0)
				{
					SetCurve(config, "world.biomes.affinity.main.meadows.relativeTravelDistance", failed, 0.0, 0.0, num, -40.0);
				}
				else
				{
					failed.Add("MeadowsFadeEnd (must be above 0)");
				}
			}
			double num2 = Value(values, "6. Biome Bands", "SwampStart") / 100.0;
			double num3 = Value(values, "6. Biome Bands", "SwampEnd") / 100.0;
			if (force || Changed(values, "SwampStart") || Changed(values, "SwampEnd"))
			{
				if (num2 - 0.02 > 0.0 && num3 > num2)
				{
					double[] obj = new double[10] { 0.0, -1000.0, 0.0, -100.0, 0.0, 0.0, 0.0, 0.0, 0.0, -100.0 };
					obj[2] = Round(num2 - 0.02);
					obj[4] = num2;
					obj[6] = num3;
					obj[8] = Round(num3 + 0.02);
					SetCurve(config, "world.biomes.affinity.main.swamp.relativeTravelDistance", failed, obj);
				}
				else
				{
					failed.Add("SwampStart/SwampEnd (start must be above 2% and below the end)");
				}
			}
			double num4 = Value(values, "6. Biome Bands", "PlainsStart") / 100.0;
			double num5 = Value(values, "6. Biome Bands", "PlainsEnd") / 100.0;
			if (force || Changed(values, "PlainsStart") || Changed(values, "PlainsEnd"))
			{
				if (num4 - 0.02 > 0.0 && num5 > num4)
				{
					double[] obj2 = new double[10] { 0.0, -1000.0, 0.0, -100.0, 0.0, 0.0, 0.0, 0.0, 0.0, -40.0 };
					obj2[2] = Round(num4 - 0.02);
					obj2[4] = num4;
					obj2[6] = num5;
					obj2[8] = Round(num5 + 0.02);
					SetCurve(config, "world.biomes.affinity.main.plains.relativeTravelDistance", failed, obj2);
				}
				else
				{
					failed.Add("PlainsStart/PlainsEnd (start must be above 2% and below the end)");
				}
			}
			double num6 = Value(values, "6. Biome Bands", "MistlandsStart") / 100.0;
			if (force || Changed(values, "MistlandsStart"))
			{
				if (num6 - 0.05 > 0.0)
				{
					SetCurve(config, "world.biomes.affinity.main.mistlands.relativeTravelDistance", failed, 0.0, -1000.0, Round(num6 - 0.05), -100.0, num6, 0.0);
				}
				else
				{
					failed.Add("MistlandsStart (must be above 5%)");
				}
			}
		}

		public static object Read(object config, string path)
		{
			object obj = config;
			string[] array = path.Split(new char[1] { '.' });
			foreach (string name in array)
			{
				if (obj == null)
				{
					return null;
				}
				FieldInfo fieldInfo = FindField(obj.GetType(), name);
				if (fieldInfo == null)
				{
					return null;
				}
				obj = fieldInfo.GetValue(obj);
			}
			return obj;
		}

		public static bool Exists(object config, string path)
		{
			object obj = config;
			string[] array = path.Split(new char[1] { '.' });
			foreach (string name in array)
			{
				if (obj == null)
				{
					return false;
				}
				FieldInfo fieldInfo = FindField(obj.GetType(), name);
				if (fieldInfo == null)
				{
					return false;
				}
				obj = fieldInfo.GetValue(obj);
			}
			return true;
		}

		public static List<string> Changes(IDictionary<string, double> values)
		{
			List<string> list = new List<string>();
			Setting[] all = All;
			foreach (Setting setting in all)
			{
				double num = Value(values, setting.Section, setting.Key);
				if (num != setting.Default)
				{
					list.Add(setting.Key + "=" + num.ToString(CultureInfo.InvariantCulture));
				}
			}
			return list;
		}

		public static string Summary(IDictionary<string, double> values)
		{
			List<string> list = Changes(values);
			if (list.Count == 0)
			{
				return "all settings at Riverheim defaults";
			}
			return list.Count + " changed: " + string.Join(", ", list.ToArray());
		}

		private static bool Changed(IDictionary<string, double> values, string bandKey)
		{
			return Value(values, "6. Biome Bands", bandKey) != Find("6. Biome Bands", bandKey).Default;
		}

		private static double Value(IDictionary<string, double> values, string section, string key)
		{
			if (values.TryGetValue(section + "|" + key, out var value))
			{
				return value;
			}
			return (Find(section, key) ?? throw new ArgumentException("Unknown setting " + section + "|" + key)).Default;
		}

		private static double Round(double value)
		{
			return Math.Round(value, 6);
		}

		private static object ConvertValue(double value, Type fieldType)
		{
			if (fieldType == typeof(int))
			{
				return (int)Math.Round(value);
			}
			if (fieldType == typeof(float))
			{
				return (float)value;
			}
			if (fieldType == typeof(double))
			{
				return value;
			}
			return Convert.ChangeType(value, fieldType, CultureInfo.InvariantCulture);
		}

		private static void SetCurve(object config, string path, List<string> failed, params double[] xy)
		{
			Assign(config, path, failed, delegate(Type fieldType)
			{
				Type type = fieldType.GetGenericArguments()[0];
				object obj = Activator.CreateInstance(fieldType);
				int num = xy.Length / 2;
				FindField(fieldType, "count").SetValue(obj, num);
				for (int i = 0; i < num; i++)
				{
					FindField(fieldType, "p" + i).SetValue(obj, Activator.CreateInstance(type, xy[2 * i], xy[2 * i + 1]));
				}
				return obj;
			});
		}

		private static void Assign(object root, string path, List<string> failed, Func<Type, object> makeValue)
		{
			string[] array = path.Split(new char[1] { '.' });
			object obj = root;
			object[] array2 = new object[array.Length - 1];
			FieldInfo[] array3 = new FieldInfo[array.Length - 1];
			for (int i = 0; i < array.Length - 1; i++)
			{
				FieldInfo fieldInfo = FindField(obj.GetType(), array[i]);
				object obj2 = ((fieldInfo == null) ? null : fieldInfo.GetValue(obj));
				if (obj2 == null)
				{
					failed.Add(path);
					return;
				}
				array2[i] = obj;
				array3[i] = fieldInfo;
				obj = obj2;
			}
			FieldInfo fieldInfo2 = FindField(obj.GetType(), array[^1]);
			if (fieldInfo2 == null)
			{
				failed.Add(path);
				return;
			}
			try
			{
				fieldInfo2.SetValue(obj, makeValue(fieldInfo2.FieldType));
				for (int num = array3.Length - 1; num >= 0; num--)
				{
					array3[num].SetValue(array2[num], obj);
					obj = array2[num];
				}
			}
			catch (Exception ex)
			{
				failed.Add(path + " (" + ex.GetType().Name + ")");
			}
		}

		private static FieldInfo FindField(Type type, string name)
		{
			return type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		}
	}
	internal static class ExpandWorldSizeCompatibility
	{
		private static Func<float> worldStretch;

		private static Func<WorldGene