Decompiled source of OpenWaters v0.2.0

BepInEx\plugins\OpenWaters\OpenWaters.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("OpenWaters")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+3872dc0e40fde1f7f995d63b069b3b3d7d051bd7")]
[assembly: AssemblyProduct("OpenWaters")]
[assembly: AssemblyTitle("OpenWaters")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was partially or fully created with the assistance of Generative AI (OpenCode).")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "OpenCode")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace OpenWaters
{
	internal static class GridComponents
	{
		public static int[] Label(bool[] land, int size, out int count)
		{
			int[] array = new int[land.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = -1;
			}
			Stack<int> stack = new Stack<int>();
			count = 0;
			for (int j = 0; j < land.Length; j++)
			{
				if (land[j] && array[j] < 0)
				{
					int label = (array[j] = count);
					stack.Push(j);
					while (stack.Count > 0)
					{
						int num = stack.Pop();
						int num2 = num % size;
						int num3 = num / size;
						PushIfLand(land, array, stack, size, num2 - 1, num3, label);
						PushIfLand(land, array, stack, size, num2 + 1, num3, label);
						PushIfLand(land, array, stack, size, num2, num3 - 1, label);
						PushIfLand(land, array, stack, size, num2, num3 + 1, label);
					}
					count++;
				}
			}
			return array;
		}

		private static void PushIfLand(bool[] land, int[] labels, Stack<int> stack, int size, int x, int y, int label)
		{
			if (x >= 0 && x < size && y >= 0 && y < size)
			{
				int num = y * size + x;
				if (land[num] && labels[num] < 0)
				{
					labels[num] = label;
					stack.Push(num);
				}
			}
		}
	}
	internal sealed class LandCalibrator
	{
		private const int Samples = 512;

		private const float EdgeSize = 500f;

		private const float OceanThreshold = 0.02f;

		private const float MountainThreshold = 0.4f;

		private const float MaxOffset = 0.6f;

		private const int SearchIterations = 24;

		private readonly float _radius;

		public float[] Modified { get; private set; }

		public float[] Fade { get; private set; }

		public float[] Peak { get; private set; }

		public int VanillaLand { get; private set; }

		public int TargetLand { get; private set; }

		public float Offset { get; private set; }

		public int ActualLand { get; private set; }

		public int ActualMountains { get; private set; }

		public LandCalibrator(float radius)
		{
			_radius = radius + 500f;
		}

		public void Run(NoiseField field, Func<float, float, bool> isVanillaLand)
		{
			int num = 512;
			float num2 = 2f * _radius / (float)num;
			Modified = new float[num * num];
			Fade = new float[num * num];
			Peak = new float[num * num];
			VanillaLand = 0;
			for (int i = 0; i < num; i++)
			{
				float num3 = 0f - _radius + ((float)i + 0.5f) * num2;
				for (int j = 0; j < num; j++)
				{
					int num4 = i * num + j;
					float num5 = 0f - _radius + ((float)j + 0.5f) * num2;
					if (num5 * num5 + num3 * num3 > _radius * _radius)
					{
						Modified[num4] = -1f;
						continue;
					}
					if (isVanillaLand(num5, num3))
					{
						VanillaLand++;
					}
					float num6 = field.BaseHeight(num5, num3, 0f);
					Modified[num4] = num6;
					Fade[num4] = field.Fade(num5, num3);
					Peak[num4] = field.PeakFactor(num6);
				}
			}
			TargetLand = (int)Math.Round((double)VanillaLand * (double)field.LandFraction);
			Offset = 0f;
			if (TargetLand < VanillaLand)
			{
				float num7 = 0f;
				float num8 = 0.6f;
				for (int k = 0; k < 24; k++)
				{
					float num9 = (num7 + num8) * 0.5f;
					if (Count(field, num9, 0.02f) > TargetLand)
					{
						num7 = num9;
					}
					else
					{
						num8 = num9;
					}
				}
				Offset = (num7 + num8) * 0.5f;
			}
			ActualLand = Count(field, Offset, 0.02f);
			ActualMountains = Count(field, Offset, 0.4f);
		}

		private int Count(NoiseField field, float offset, float threshold)
		{
			int num = 0;
			for (int i = 0; i < Modified.Length; i++)
			{
				if (!(Modified[i] < 0f) && field.Compress(Modified[i] - offset * Fade[i] * Peak[i]) > threshold)
				{
					num++;
				}
			}
			return num;
		}
	}
	internal interface INoise
	{
		float Perlin(double x, double y);
	}
	internal sealed class NoiseFieldConfig
	{
		public float FrequencyScale = 1f;

		public float LandFraction = 1f;

		public float DetailDamping = 1f;

		public float PeakProtection;

		public float MountainCompressionStart;

		public float MountainCompressionFactor = 1f;

		public float Offset0;

		public float Offset1;

		public float MinMountainDistance = 1000f;
	}
	internal static class MathUtil
	{
		public static float Clamp01(float value)
		{
			if (!(value < 0f))
			{
				if (!(value > 1f))
				{
					return value;
				}
				return 1f;
			}
			return 0f;
		}

		public static float Lerp(float from, float to, float t)
		{
			return from + (to - from) * Clamp01(t);
		}

		public static float LerpStep(float from, float to, float value)
		{
			return Clamp01((value - from) / (to - from));
		}

		public static float SmoothStep(float from, float to, float value)
		{
			float num = Clamp01((value - from) / (to - from));
			return num * num * (3f - 2f * num);
		}

		public static float Sqrt(float value)
		{
			return (float)Math.Sqrt(value);
		}
	}
	internal sealed class NoiseField
	{
		private const float OceanEdgeStart = 10000f;

		private const float OceanEdgeEnd = 10500f;

		private const float OceanEdgeInner = 10490f;

		private const float StartFadeInner = 800f;

		private const float StartFadeOuter = 1600f;

		private const float PeakProtectStart = 0.28f;

		private const float PeakProtectEnd = 0.45f;

		private const float MountainProtectStart = 0.28f;

		private const float MountainProtectSpan = 0.1f;

		private const float MountainProtectCap = 0.38f;

		private readonly INoise _noise;

		private readonly NoiseFieldConfig _config;

		public float LandFraction => _config.LandFraction;

		public float FrequencyScale => _config.FrequencyScale;

		public float DetailDamping => _config.DetailDamping;

		public float PeakProtection => _config.PeakProtection;

		public NoiseField(INoise noise, NoiseFieldConfig config)
		{
			_noise = noise;
			_config = config;
		}

		public float Fade(float wx, float wy)
		{
			return MathUtil.SmoothStep(800f, 1600f, MathUtil.Sqrt(wx * wx + wy * wy));
		}

		public float PeakFactor(float value)
		{
			return 1f - _config.PeakProtection * MathUtil.SmoothStep(0.28f, 0.45f, value);
		}

		public float Compress(float value)
		{
			if (value <= _config.MountainCompressionStart)
			{
				return value;
			}
			return _config.MountainCompressionStart + (value - _config.MountainCompressionStart) * _config.MountainCompressionFactor;
		}

		public float BaseHeight(float wx, float wy, float offset)
		{
			float frequencyScale = _config.FrequencyScale;
			float num = MathUtil.Sqrt(wx * wx + wy * wy);
			double num2 = (double)wx + 100000.0 + (double)_config.Offset0;
			double num3 = (double)wy + 100000.0 + (double)_config.Offset1;
			float num4 = 0f;
			num4 += _noise.Perlin(num2 * 0.002 * 0.5 * (double)frequencyScale, num3 * 0.002 * 0.5 * (double)frequencyScale) * _noise.Perlin(num2 * 0.003 * 0.5 * (double)frequencyScale, num3 * 0.003 * 0.5 * (double)frequencyScale);
			num4 += _noise.Perlin(num2 * 0.002 * (double)frequencyScale, num3 * 0.002 * (double)frequencyScale) * _noise.Perlin(num2 * 0.003 * (double)frequencyScale, num3 * 0.003 * (double)frequencyScale) * num4 * 0.9f;
			num4 += _noise.Perlin(num2 * 0.005 * (double)frequencyScale, num3 * 0.005 * (double)frequencyScale) * _noise.Perlin(num2 * 0.01 * (double)frequencyScale, num3 * 0.01 * (double)frequencyScale) * 0.5f * _config.DetailDamping * num4;
			num4 -= 0.07f;
			float num5 = _noise.Perlin(num2 * 0.002 * 0.25 * (double)frequencyScale + 0.123, num3 * 0.002 * 0.25 * (double)frequencyScale + 0.15123);
			float num6 = _noise.Perlin(num2 * 0.002 * 0.25 * (double)frequencyScale + 0.321, num3 * 0.002 * 0.25 * (double)frequencyScale + 0.231);
			float num7 = 1f - MathUtil.LerpStep(0.02f, 0.12f, Math.Abs(num5 - num6));
			num7 *= MathUtil.SmoothStep(744f, 1000f, num);
			num4 *= 1f - num7;
			num4 -= offset * Fade(wx, wy) * PeakFactor(num4);
			if (num > 10000f)
			{
				float t = MathUtil.LerpStep(10000f, 10500f, num);
				num4 = MathUtil.Lerp(num4, -0.2f, t);
				if (num > 10490f)
				{
					float t2 = MathUtil.LerpStep(10490f, 10500f, num);
					num4 = MathUtil.Lerp(num4, -2f, t2);
				}
				return num4;
			}
			if (num < _config.MinMountainDistance && num4 > 0.28f)
			{
				float t3 = MathUtil.Clamp01((num4 - 0.28f) / 0.1f);
				num4 = MathUtil.Lerp(MathUtil.Lerp(0.28f, 0.38f, t3), num4, MathUtil.LerpStep(_config.MinMountainDistance - 400f, _config.MinMountainDistance, num));
			}
			return num4;
		}
	}
	internal enum PeerInfoPayloadKind
	{
		NoExtension,
		EmptyExtension,
		OpenWaters,
		OtherMod,
		UnsupportedVersion,
		Malformed
	}
	internal static class PeerInfoPayload
	{
		private const string VersionPrefix = "OWS";

		public static PeerInfoPayloadKind Read(byte[] bytes, int position, int size, string marker, out string text, out int consumed)
		{
			text = null;
			consumed = 0;
			if (bytes == null || position < 0 || position > size || size > bytes.Length)
			{
				return PeerInfoPayloadKind.Malformed;
			}
			if (!PeerInfoProtocol.ShouldReadServerExtension(size, position))
			{
				return PeerInfoPayloadKind.NoExtension;
			}
			if (!TryReadString(bytes, position, out text, out consumed))
			{
				return PeerInfoPayloadKind.Malformed;
			}
			if (string.IsNullOrEmpty(text))
			{
				return PeerInfoPayloadKind.EmptyExtension;
			}
			if (text.StartsWith(marker, StringComparison.Ordinal))
			{
				return PeerInfoPayloadKind.OpenWaters;
			}
			if (text.StartsWith("OWS", StringComparison.Ordinal))
			{
				return PeerInfoPayloadKind.UnsupportedVersion;
			}
			return PeerInfoPayloadKind.OtherMod;
		}

		public static byte[] EncodeString(string value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			byte[] bytes = Encoding.UTF8.GetBytes(value);
			byte[] array = Encode7BitLength(bytes.Length);
			byte[] array2 = new byte[array.Length + bytes.Length];
			Buffer.BlockCopy(array, 0, array2, 0, array.Length);
			Buffer.BlockCopy(bytes, 0, array2, array.Length, bytes.Length);
			return array2;
		}

		private static bool TryReadString(byte[] bytes, int position, out string text, out int consumed)
		{
			text = null;
			consumed = 0;
			int index = position;
			if (!TryRead7BitLength(bytes, ref index, out var value) || value < 0 || value > bytes.Length - index)
			{
				return false;
			}
			try
			{
				text = Encoding.UTF8.GetString(bytes, index, value);
			}
			catch (DecoderFallbackException)
			{
				return false;
			}
			consumed = index + value - position;
			return true;
		}

		private static bool TryRead7BitLength(byte[] bytes, ref int index, out int value)
		{
			value = 0;
			uint num = 0u;
			int num2 = 0;
			for (int i = 0; i < 5; i++)
			{
				if (index >= bytes.Length)
				{
					return false;
				}
				byte b = bytes[index++];
				num |= (uint)((b & 0x7F) << num2);
				if ((b & 0x80) == 0)
				{
					value = (int)num;
					return num <= int.MaxValue;
				}
				num2 += 7;
			}
			return false;
		}

		private static byte[] Encode7BitLength(int length)
		{
			uint num = (uint)length;
			byte[] array = new byte[5];
			int num2 = 0;
			while (num >= 128)
			{
				array[num2++] = (byte)((num & 0x7F) | 0x80);
				num >>= 7;
			}
			array[num2++] = (byte)num;
			byte[] array2 = new byte[num2];
			Buffer.BlockCopy(array, 0, array2, 0, num2);
			return array2;
		}
	}
	internal static class PeerInfoProtocol
	{
		public const int VanillaTrailingBytes = 8;

		public static bool ShouldReadServerExtension(int packageSize, int position)
		{
			return packageSize - position > 8;
		}

		public static bool EndsWith(byte[] bytes, int length, byte[] suffix)
		{
			if (bytes == null || suffix == null || suffix.Length == 0 || length < suffix.Length || length > bytes.Length)
			{
				return false;
			}
			int num = length - suffix.Length;
			for (int i = 0; i < suffix.Length; i++)
			{
				if (bytes[num + i] != suffix[i])
				{
					return false;
				}
			}
			return true;
		}
	}
	internal enum RemoteSettingsStatus
	{
		NotReceived,
		NoSnapshot,
		SeedMismatch,
		InvalidPayload,
		IncompatibleGenerator,
		Accepted
	}
	internal sealed class RemoteSettingsState
	{
		private WorldSettings _settings;

		private string _seed;

		private bool _received;

		private bool _invalid;

		public void Clear()
		{
			_settings = null;
			_seed = null;
			_received = false;
			_invalid = false;
		}

		public void MarkPeerInfoReceived()
		{
			_settings = null;
			_seed = null;
			_invalid = false;
			_received = true;
		}

		public void MarkPayloadInvalid()
		{
			_settings = null;
			_seed = null;
			_invalid = true;
			_received = true;
		}

		public void Set(WorldSettings settings, string seed)
		{
			_settings = settings;
			_seed = seed;
			_invalid = false;
			_received = true;
		}

		public RemoteSettingsStatus Resolve(string seed, out WorldSettings settings)
		{
			settings = _settings;
			if (!_received)
			{
				return RemoteSettingsStatus.NotReceived;
			}
			if (_invalid)
			{
				return RemoteSettingsStatus.InvalidPayload;
			}
			if (_settings == null)
			{
				return RemoteSettingsStatus.NoSnapshot;
			}
			if (!string.Equals(_seed, seed, StringComparison.Ordinal))
			{
				return RemoteSettingsStatus.SeedMismatch;
			}
			if (!_settings.IsGeneratorCompatible)
			{
				return RemoteSettingsStatus.IncompatibleGenerator;
			}
			return RemoteSettingsStatus.Accepted;
		}
	}
	internal struct IslandCandidate
	{
		public int Id;

		public int Cells;

		public int MinX;

		public int MaxX;

		public int MinY;

		public int MaxY;
	}
	internal sealed class StartIslandSelection
	{
		public int StartId = -1;

		public readonly List<int> AbsorbedIds = new List<int>();
	}
	internal static class StartIslandSelector
	{
		public static StartIslandSelection Select(IslandCandidate[] islands, int anchorId, float anchorX, float anchorY, int minCells, float cellSize, float radius, float searchRadius, float seamRadius)
		{
			StartIslandSelection startIslandSelection = new StartIslandSelection();
			IslandCandidate first = Find(islands, anchorId);
			if (anchorId >= 0 && first.Cells >= minCells)
			{
				startIslandSelection.StartId = anchorId;
			}
			else
			{
				float num = float.MaxValue;
				float num2 = searchRadius * searchRadius;
				float num3 = seamRadius * seamRadius;
				for (int i = 0; i < islands.Length; i++)
				{
					IslandCandidate second = islands[i];
					if (second.Cells >= minCells && (anchorId < 0 || !(BBoxDistanceSqr(first, second, cellSize, radius) > num3)))
					{
						float num4 = (float)second.MinX * cellSize - radius;
						float num5 = (float)(second.MaxX + 1) * cellSize - radius;
						float num6 = (float)second.MinY * cellSize - radius;
						float num7 = (float)(second.MaxY + 1) * cellSize - radius;
						float num8 = Math.Max(0f, Math.Max(num4 - anchorX, anchorX - num5));
						float num9 = Math.Max(0f, Math.Max(num6 - anchorY, anchorY - num7));
						float num10 = num8 * num8 + num9 * num9;
						if (num10 < num && num10 <= num2)
						{
							num = num10;
							startIslandSelection.StartId = second.Id;
						}
					}
				}
			}
			if (startIslandSelection.StartId < 0 && anchorId >= 0)
			{
				startIslandSelection.StartId = anchorId;
			}
			if (startIslandSelection.StartId >= 0 && anchorId >= 0 && first.Id != startIslandSelection.StartId && first.Cells < minCells)
			{
				startIslandSelection.AbsorbedIds.Add(first.Id);
			}
			return startIslandSelection;
		}

		private static IslandCandidate Find(IslandCandidate[] islands, int id)
		{
			for (int i = 0; i < islands.Length; i++)
			{
				IslandCandidate result = islands[i];
				if (result.Id == id)
				{
					return result;
				}
			}
			return default(IslandCandidate);
		}

		private static float BBoxDistanceSqr(IslandCandidate first, IslandCandidate second, float cellSize, float radius)
		{
			float num = (float)first.MinX * cellSize - radius;
			float num2 = (float)(first.MaxX + 1) * cellSize - radius;
			float num3 = (float)first.MinY * cellSize - radius;
			float num4 = (float)(first.MaxY + 1) * cellSize - radius;
			float num5 = (float)second.MinX * cellSize - radius;
			float num6 = (float)(second.MaxX + 1) * cellSize - radius;
			float num7 = (float)second.MinY * cellSize - radius;
			float num8 = (float)(second.MaxY + 1) * cellSize - radius;
			float num9 = Math.Max(0f, Math.Max(num - num6, num5 - num2));
			float num10 = Math.Max(0f, Math.Max(num3 - num8, num7 - num4));
			return num9 * num9 + num10 * num10;
		}
	}
	internal sealed class WorldSettings
	{
		public const int SidecarVersion = 1;

		public const int GeneratorVersion = 1;

		private static readonly int[] _supportedGeneratorVersions = new int[1] { 1 };

		public const int FewIslands = 0;

		public const int MediumIslands = 1;

		public const int VanillaIslands = 2;

		public const int MinWorldRadius = 6000;

		public const int MaxWorldRadius = 10000;

		public const int DefaultWorldRadius = 10000;

		public const int MaxBiomeLimit = 3;

		public readonly int IslandAmount;

		public readonly int WorldRadius;

		public readonly int BiomeLimit;

		public readonly int StartBiomeLimit;

		public readonly bool ExcludeMountains;

		public readonly int SidecarFormatVersion;

		public readonly int GeneratorVersionValue;

		public readonly string ModVersion;

		public readonly float FewLandFraction;

		public readonly float FewFrequencyScale;

		public readonly float FewPeakProtection;

		public readonly float FewDetailDamping;

		public readonly float FewMountainCompressionStart;

		public readonly float FewMountainCompressionFactor;

		public readonly float MediumLandFraction;

		public readonly float MediumFrequencyScale;

		public readonly float MediumPeakProtection;

		public readonly float MediumDetailDamping;

		public static string SupportedVersionsText => string.Join(", ", _supportedGeneratorVersions);

		public static WorldSettings Vanilla => new WorldSettings(2, 10000, 0, 0, excludeMountains: false);

		public bool AffectsGeneration
		{
			get
			{
				if (IslandAmount == 2 && !ExcludeMountains)
				{
					return StartBiomeLimit != 0;
				}
				return true;
			}
		}

		public bool IsGeneratorCompatible
		{
			get
			{
				int[] supportedGeneratorVersions = _supportedGeneratorVersions;
				for (int i = 0; i < supportedGeneratorVersions.Length; i++)
				{
					if (supportedGeneratorVersions[i] == GeneratorVersionValue)
					{
						return true;
					}
				}
				return false;
			}
		}

		public float LandFraction
		{
			get
			{
				if (IslandAmount != 0)
				{
					if (IslandAmount != 1)
					{
						return 1f;
					}
					return MediumLandFraction;
				}
				return FewLandFraction;
			}
		}

		public float FrequencyScale
		{
			get
			{
				if (IslandAmount != 0)
				{
					return MediumFrequencyScale;
				}
				return FewFrequencyScale;
			}
		}

		public float DetailDamping
		{
			get
			{
				if (IslandAmount != 0)
				{
					return MediumDetailDamping;
				}
				return FewDetailDamping;
			}
		}

		public float PeakProtection
		{
			get
			{
				if (IslandAmount != 0)
				{
					return MediumPeakProtection;
				}
				return FewPeakProtection;
			}
		}

		public WorldSettings(int islandAmount, int worldRadius, int biomeLimit, int startBiomeLimit, bool excludeMountains, string modVersion = "0.1.0", float fewLandFraction = 0.27f, float fewFrequencyScale = 0.6f, float fewPeakProtection = 0.2f, float fewDetailDamping = 0.35f, float fewMountainCompressionStart = 0.34f, float fewMountainCompressionFactor = 0.55f, float mediumLandFraction = 0.5f, float mediumFrequencyScale = 0.7f, float mediumPeakProtection = 0.6f, float mediumDetailDamping = 0.35f, int sidecarFormatVersion = 1, int generatorVersion = 1)
		{
			IslandAmount = islandAmount;
			WorldRadius = worldRadius;
			BiomeLimit = biomeLimit;
			StartBiomeLimit = startBiomeLimit;
			ExcludeMountains = excludeMountains;
			ModVersion = modVersion;
			FewLandFraction = fewLandFraction;
			FewFrequencyScale = fewFrequencyScale;
			FewPeakProtection = fewPeakProtection;
			FewDetailDamping = fewDetailDamping;
			FewMountainCompressionStart = fewMountainCompressionStart;
			FewMountainCompressionFactor = fewMountainCompressionFactor;
			MediumLandFraction = mediumLandFraction;
			MediumFrequencyScale = mediumFrequencyScale;
			MediumPeakProtection = mediumPeakProtection;
			MediumDetailDamping = mediumDetailDamping;
			SidecarFormatVersion = sidecarFormatVersion;
			GeneratorVersionValue = generatorVersion;
		}
	}
	internal static class WorldSettingsCodec
	{
		public static string Serialize(WorldSettings settings, string seed)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("# Open Waters world settings");
			WriteInt(stringBuilder, "version", settings.SidecarFormatVersion);
			WriteInt(stringBuilder, "generatorVersion", settings.GeneratorVersionValue);
			WriteString(stringBuilder, "modVersion", settings.ModVersion);
			WriteString(stringBuilder, "seed", Encode(seed));
			WriteInt(stringBuilder, "islandAmount", settings.IslandAmount);
			WriteInt(stringBuilder, "worldRadius", settings.WorldRadius);
			WriteInt(stringBuilder, "biomeLimit", settings.BiomeLimit);
			WriteInt(stringBuilder, "startBiomeLimit", settings.StartBiomeLimit);
			WriteBool(stringBuilder, "excludeMountains", settings.ExcludeMountains);
			WriteFloat(stringBuilder, "fewLandFraction", settings.FewLandFraction);
			WriteFloat(stringBuilder, "fewFrequencyScale", settings.FewFrequencyScale);
			WriteFloat(stringBuilder, "fewPeakProtection", settings.FewPeakProtection);
			WriteFloat(stringBuilder, "fewDetailDamping", settings.FewDetailDamping);
			WriteFloat(stringBuilder, "fewMountainCompressionStart", settings.FewMountainCompressionStart);
			WriteFloat(stringBuilder, "fewMountainCompressionFactor", settings.FewMountainCompressionFactor);
			WriteFloat(stringBuilder, "mediumLandFraction", settings.MediumLandFraction);
			WriteFloat(stringBuilder, "mediumFrequencyScale", settings.MediumFrequencyScale);
			WriteFloat(stringBuilder, "mediumPeakProtection", settings.MediumPeakProtection);
			WriteFloat(stringBuilder, "mediumDetailDamping", settings.MediumDetailDamping);
			return stringBuilder.ToString();
		}

		public static bool TryParse(string text, string seed, out WorldSettings settings)
		{
			settings = null;
			if (string.IsNullOrEmpty(text) || seed == null)
			{
				return false;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			string[] array = text.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length != 0 && text2[0] != '#')
				{
					int num = text2.IndexOf('=');
					if (num <= 0)
					{
						return false;
					}
					string key = text2.Substring(0, num).Trim();
					if (dictionary.ContainsKey(key))
					{
						return false;
					}
					dictionary[key] = text2.Substring(num + 1).Trim();
				}
			}
			if (!TryGetInt(dictionary, "version", out var value) || value != 1 || !TryGetInt(dictionary, "generatorVersion", out var value2) || !TryGetString(dictionary, "modVersion", out var value3) || !dictionary.TryGetValue("seed", out var value4) || !TryDecode(value4, out var decoded) || decoded != seed || !TryGetInt(dictionary, "islandAmount", out var value5) || !TryGetInt(dictionary, "worldRadius", out var value6) || !TryGetInt(dictionary, "biomeLimit", out var value7) || !TryGetInt(dictionary, "startBiomeLimit", out var value8) || !TryGetBool(dictionary, "excludeMountains", out var value9) || !TryGetFloat(dictionary, "fewLandFraction", out var value10) || !TryGetFloat(dictionary, "fewFrequencyScale", out var value11) || !TryGetFloat(dictionary, "fewPeakProtection", out var value12) || !TryGetFloat(dictionary, "fewDetailDamping", out var value13) || !TryGetFloat(dictionary, "fewMountainCompressionStart", out var value14) || !TryGetFloat(dictionary, "fewMountainCompressionFactor", out var value15) || !TryGetFloat(dictionary, "mediumLandFraction", out var value16) || !TryGetFloat(dictionary, "mediumFrequencyScale", out var value17) || !TryGetFloat(dictionary, "mediumPeakProtection", out var value18) || !TryGetFloat(dictionary, "mediumDetailDamping", out var value19))
			{
				return false;
			}
			if (value5 < 0 || value5 > 2 || value6 < 6000 || value6 > 10000 || value7 < 0 || value7 > 3 || value8 < 0 || value8 > 3 || !IsInRange(value10, 0.01f, 1f) || !IsInRange(value11, 0.1f, 2f) || !IsInRange(value12, 0f, 1f) || !IsInRange(value13, 0f, 1f) || !IsInRange(value14, 0f, 1f) || !IsInRange(value15, 0f, 1f) || !IsInRange(value16, 0.01f, 1f) || !IsInRange(value17, 0.1f, 2f) || !IsInRange(value18, 0f, 1f) || !IsInRange(value19, 0f, 1f))
			{
				return false;
			}
			settings = new WorldSettings(value5, value6, value7, value8, value9, value3, value10, value11, value12, value13, value14, value15, value16, value17, value18, value19, value, value2);
			return true;
		}

		private static bool IsInRange(float value, float min, float max)
		{
			if (!float.IsNaN(value) && !float.IsInfinity(value) && value >= min)
			{
				return value <= max;
			}
			return false;
		}

		private static string Encode(string value)
		{
			return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
		}

		private static bool TryDecode(string value, out string decoded)
		{
			decoded = null;
			try
			{
				decoded = Encoding.UTF8.GetString(Convert.FromBase64String(value));
				return true;
			}
			catch (FormatException)
			{
				return false;
			}
		}

		private static void WriteInt(StringBuilder text, string key, int value)
		{
			text.Append(key).Append('=').Append(value.ToString(CultureInfo.InvariantCulture))
				.Append('\n');
		}

		private static void WriteBool(StringBuilder text, string key, bool value)
		{
			text.Append(key).Append('=').Append(value ? "true" : "false")
				.Append('\n');
		}

		private static void WriteFloat(StringBuilder text, string key, float value)
		{
			text.Append(key).Append('=').Append(value.ToString("R", CultureInfo.InvariantCulture))
				.Append('\n');
		}

		private static void WriteString(StringBuilder text, string key, string value)
		{
			text.Append(key).Append('=').Append(value)
				.Append('\n');
		}

		private static bool TryGetString(Dictionary<string, string> values, string key, out string value)
		{
			if (values.TryGetValue(key, out value))
			{
				return !string.IsNullOrEmpty(value);
			}
			return false;
		}

		private static bool TryGetInt(Dictionary<string, string> values, string key, out int value)
		{
			value = 0;
			if (values.TryGetValue(key, out var value2))
			{
				return int.TryParse(value2, NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
			}
			return false;
		}

		private static bool TryGetBool(Dictionary<string, string> values, string key, out bool value)
		{
			value = false;
			if (values.TryGetValue(key, out var value2))
			{
				return bool.TryParse(value2, out value);
			}
			return false;
		}

		private static bool TryGetFloat(Dictionary<string, string> values, string key, out float value)
		{
			value = 0f;
			if (values.TryGetValue(key, out var value2))
			{
				return float.TryParse(value2, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
			}
			return false;
		}
	}
	internal static class SidecarLocator
	{
		public static string FindBySeed(string[] directories, string seed, Func<string, string> read, Func<string, string> toSidecarPath)
		{
			if (directories == null || string.IsNullOrEmpty(seed))
			{
				return null;
			}
			foreach (string arg in directories)
			{
				string text = toSidecarPath(arg);
				try
				{
					if (WorldSettingsCodec.TryParse(read(text), seed, out var _))
					{
						return text;
					}
				}
				catch (Exception)
				{
				}
			}
			return null;
		}
	}
	internal interface ISidecarStorage
	{
		bool Exists(string path);

		string Read(string path);

		void Write(string path, string text);

		void Delete(string path);

		void Move(string source, string destination);

		string[] GetDirectories(string path);
	}
	internal sealed class FileSidecarStorage : ISidecarStorage
	{
		public bool Exists(string path)
		{
			return File.Exists(path);
		}

		public string Read(string path)
		{
			return File.ReadAllText(path);
		}

		public void Write(string path, string text)
		{
			File.WriteAllText(path, text);
		}

		public void Delete(string path)
		{
			File.Delete(path);
		}

		public void Move(string source, string destination)
		{
			File.Move(source, destination);
		}

		public string[] GetDirectories(string path)
		{
			return Directory.GetDirectories(path);
		}
	}
	internal static class SelfTest
	{
		public static void Run(Action<string> log)
		{
			int passed = 0;
			int failed = 0;
			log("[SelfTest] Running built-in checks...");
			Check(log, "no extension stays vanilla", ref passed, ref failed, () => PeerInfoPayload.Read(new byte[8], 0, 8, "OWS1:", out var _, out var _) == PeerInfoPayloadKind.NoExtension);
			WorldSettings settings;
			Check(log, "valid OWS1 payload decodes and parses", ref passed, ref failed, delegate
			{
				settings = Sample();
				byte[] array = Package("OWS1:" + WorldSettingsCodec.Serialize(settings, "seed-a"));
				WorldSettings settings2;
				return PeerInfoPayload.Read(array, 0, array.Length, "OWS1:", out text, out consumed) == PeerInfoPayloadKind.OpenWaters && WorldSettingsCodec.TryParse(text.Substring("OWS1:".Length), "seed-a", out settings2);
			});
			Check(log, "another mod's extension is ignored", ref passed, ref failed, delegate
			{
				byte[] array = Package("OTHERMOD:data");
				return PeerInfoPayload.Read(array, 0, array.Length, "OWS1:", out text, out consumed) == PeerInfoPayloadKind.OtherMod;
			});
			Check(log, "unsupported OWS version is detected", ref passed, ref failed, delegate
			{
				byte[] array = Package("OWS2:data");
				return PeerInfoPayload.Read(array, 0, array.Length, "OWS1:", out text, out consumed) == PeerInfoPayloadKind.UnsupportedVersion;
			});
			Check(log, "wrong seed invalidates the payload", ref passed, ref failed, () => !WorldSettingsCodec.TryParse(WorldSettingsCodec.Serialize(Sample(), "seed-a"), "seed-b", out settings));
			Check(log, "unsupported generator version is detected", ref passed, ref failed, delegate
			{
				RemoteSettingsState remoteSettingsState = new RemoteSettingsState();
				remoteSettingsState.Set(Sample(2), "seed-a");
				return remoteSettingsState.Resolve("seed-a", out settings) == RemoteSettingsStatus.IncompatibleGenerator;
			});
			Check(log, "seed mismatch is detected", ref passed, ref failed, delegate
			{
				RemoteSettingsState remoteSettingsState = new RemoteSettingsState();
				remoteSettingsState.Set(Sample(), "seed-a");
				return remoteSettingsState.Resolve("seed-b", out settings) == RemoteSettingsStatus.SeedMismatch;
			});
			Check(log, "new peer info clears the previous snapshot", ref passed, ref failed, delegate
			{
				RemoteSettingsState remoteSettingsState = new RemoteSettingsState();
				remoteSettingsState.Set(Sample(), "seed-a");
				remoteSettingsState.MarkPeerInfoReceived();
				return remoteSettingsState.Resolve("seed-a", out settings) == RemoteSettingsStatus.NoSnapshot;
			});
			log($"[SelfTest] Done: {passed} passed, {failed} failed.");
		}

		private static WorldSettings Sample(int generatorVersion = 1)
		{
			return new WorldSettings(1, 8000, 0, 1, excludeMountains: false, "0.1.2", 0.27f, 0.6f, 0.2f, 0.35f, 0.34f, 0.55f, 0.5f, 0.7f, 0.6f, 0.35f, 1, generatorVersion);
		}

		private static byte[] Package(string text)
		{
			byte[] array = PeerInfoPayload.EncodeString(text);
			byte[] array2 = new byte[array.Length + 8];
			Buffer.BlockCopy(array, 0, array2, 0, array.Length);
			return array2;
		}

		private static void Check(Action<string> log, string name, ref int passed, ref int failed, Func<bool> test)
		{
			bool flag;
			try
			{
				flag = test();
			}
			catch (Exception ex)
			{
				flag = false;
				log("[SelfTest] " + name + " threw: " + ex.Message);
			}
			if (flag)
			{
				passed++;
				log("[SelfTest] PASS: " + name);
			}
			else
			{
				failed++;
				log("[SelfTest] FAIL: " + name);
			}
		}
	}
	[HarmonyPatch(typeof(WorldGenerator), "Initialize")]
	internal static class WorldGeneratorInitializePatch
	{
		[HarmonyPrefix]
		private static void Prefix(World world)
		{
			WorldSettings worldSettings = WorldSettingsStore.Apply(world);
			NoiseModifier.SetWorld(world, worldSettings);
			OpenWatersPlugin.Log.LogInfo((object)($"[Gen] Initialize world='{world.m_worldName}' seed='{world.m_seedName}', menu={world.m_menu}, " + "preset=" + WorldSettingsStore.GetDisplayName(worldSettings) + ", " + $"generatorVersion={worldSettings.GeneratorVersionValue}, land={worldSettings.LandFraction:P0}"));
		}
	}
	[HarmonyPatch(typeof(WorldGenerator), "Pregenerate")]
	internal static class WorldGeneratorPregeneratePatch
	{
		[HarmonyPrefix]
		private static void Prefix(WorldGenerator __instance)
		{
			try
			{
				NoiseModifier.Build(__instance);
			}
			catch (Exception arg)
			{
				OpenWatersPlugin.Log.LogError((object)$"[Gen] Noise frequency failed: {arg}");
				NoiseModifier.Cancel();
			}
		}
	}
	[HarmonyPatch(typeof(WorldGenerator), "GetBiome", new Type[]
	{
		typeof(float),
		typeof(float),
		typeof(float),
		typeof(bool)
	})]
	internal static class WorldGeneratorGetBiomePatch
	{
		[HarmonyPostfix]
		private static void Postfix(float wx, float wy, ref Biome __result)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected I4, but got Unknown
			if (GenerationSession.Current.Stage == GenerationStage.Ready && !IslandAnalysis.Analyzing && (int)__result != 256 && (int)__result != 32 && (int)__result != 64 && (int)__result != 4 && StartIslandModifier.TryGetBiomeOverride(wx, wy, __result, out var biome))
			{
				__result = (Biome)(int)biome;
			}
		}
	}
	[HarmonyPatch(typeof(WorldGenerator), "GetBaseHeight")]
	internal static class WorldGeneratorGetBaseHeightPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(float wx, float wy, bool menuTerrain, ref float __result)
		{
			GenerationSession current = GenerationSession.Current;
			if (menuTerrain || current.Stage == GenerationStage.Idle || current.Stage == GenerationStage.Calibrating || !current.UsesGlobalNoise || current.Field == null)
			{
				return true;
			}
			__result = NoiseModifier.ApplyGlobal(current, wx, wy);
			return false;
		}

		[HarmonyPostfix]
		private static void Postfix(float wx, float wy, bool menuTerrain, ref float __result)
		{
			GenerationSession current = GenerationSession.Current;
			if (!menuTerrain && current.Stage == GenerationStage.Ready && !current.UsesGlobalNoise)
			{
				__result = StartIslandModifier.Apply(__result, wx, wy);
			}
		}
	}
	internal enum GenerationStage
	{
		Idle,
		Calibrating,
		Analyzing,
		Ready
	}
	internal sealed class GenerationSession
	{
		private static bool _deferNextSession;

		public readonly World World;

		public readonly WorldSettings Settings;

		public float Offset0;

		public float Offset1;

		public float MinMountainDistance = 1000f;

		public float HeightOffset;

		public bool Active;

		public bool UsesGlobalNoise;

		public NoiseField Field;

		public static GenerationSession Current { get; private set; } = new GenerationSession(null, WorldSettings.Vanilla);

		public GenerationStage Stage { get; private set; }

		public bool DeferIslandAnalysis { get; set; }

		public GenerationSession(World world, WorldSettings settings)
		{
			World = world;
			Settings = settings ?? WorldSettings.Vanilla;
		}

		public static void DeferNextSession()
		{
			_deferNextSession = true;
		}

		public static void ClearDeferredSession()
		{
			_deferNextSession = false;
		}

		public static void Begin(World world, WorldSettings settings)
		{
			Current = new GenerationSession(world, settings)
			{
				DeferIslandAnalysis = _deferNextSession
			};
			_deferNextSession = false;
			IslandAnalysis.Clear();
		}

		public void BeginBuild()
		{
			Stage = GenerationStage.Calibrating;
			Active = false;
			HeightOffset = 0f;
			Field = null;
		}

		public void BeginAnalysis()
		{
			Stage = GenerationStage.Analyzing;
		}

		public void MarkReady()
		{
			Stage = GenerationStage.Ready;
			Active = true;
		}

		public void Cancel()
		{
			Stage = GenerationStage.Idle;
			Active = false;
			HeightOffset = 0f;
			UsesGlobalNoise = false;
			Field = null;
			DeferIslandAnalysis = false;
			IslandAnalysis.Clear();
		}
	}
	internal delegate Biome GetBiomeDelegate(float wx, float wy, float oceanLevel, bool waterAlwaysOcean);
	internal delegate float GetHeightDelegate(float wx, float wy);
	internal sealed class IslandInfo
	{
		public ushort Id;

		public int Cells;

		public float CenterX;

		public float CenterY;

		public int MinX;

		public int MaxX;

		public int MinY;

		public int MaxY;

		public readonly int[] BiomeCells = new int[9];

		public Biome DominantBiome;

		public float DominantShare;
	}
	internal static class IslandAnalysis
	{
		private const int Samples = 1024;

		private const float WaterLevel = 30f;

		private const float AnchorSearchRadius = 500f;

		private const float RiverSeamRadius = 120f;

		private const float MinStartIslandAreaKm2 = 0.15f;

		private static Biome[] _cellBiome;

		private static ushort[] _cellIsland;

		private static bool[] _startMask;

		private static IslandInfo[] _islands;

		private static bool[] _land;

		private static GetBiomeDelegate _getBiome;

		private static GetHeightDelegate _getHeight;

		private static int _size;

		private static float _radius;

		private static float _cellSize;

		private static Vector2 _anchor;

		private static ushort _startIsland = ushort.MaxValue;

		private static int _startCells;

		private static int _absorbed;

		private static int _sampleRow;

		private static long _started;

		private static bool _analyzing;

		public static bool Analyzing => _analyzing;

		public static bool Ready => _cellIsland != null;

		public static int StartCells => _startCells;

		public static IReadOnlyList<IslandInfo> Islands => _islands;

		public static IslandInfo StartIsland
		{
			get
			{
				if (_startIsland != ushort.MaxValue && _islands != null)
				{
					return _islands[_startIsland];
				}
				return null;
			}
		}

		public static void Clear()
		{
			_cellBiome = null;
			_cellIsland = null;
			_startMask = null;
			_islands = null;
			_land = null;
			_getBiome = null;
			_getHeight = null;
			_startIsland = ushort.MaxValue;
			_startCells = 0;
			_absorbed = 0;
			_sampleRow = 0;
			_analyzing = false;
		}

		public static void Build(WorldGenerator generator, float radius)
		{
			if (!GenerationSession.Current.DeferIslandAnalysis && Begin(generator, radius))
			{
				while (SampleRows(16))
				{
				}
				Finish();
			}
		}

		public static bool Begin(WorldGenerator generator, float radius)
		{
			Clear();
			World val = generator?.m_world;
			NoiseModifier.LogGeneratorState((val != null && val.m_worldName == "OpenWatersPreview") ? "preview" : "world", generator);
			MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetBiome", new Type[4]
			{
				typeof(float),
				typeof(float),
				typeof(float),
				typeof(bool)
			}, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(WorldGenerator), "GetHeight", new Type[2]
			{
				typeof(float),
				typeof(float)
			}, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				OpenWatersPlugin.Log.LogError((object)"[Gen] Could not find WorldGenerator.GetBiome/GetHeight.");
				return false;
			}
			try
			{
				_getBiome = (GetBiomeDelegate)Delegate.CreateDelegate(typeof(GetBiomeDelegate), generator, methodInfo);
				_getHeight = (GetHeightDelegate)Delegate.CreateDelegate(typeof(GetHeightDelegate), generator, methodInfo2);
			}
			catch (Exception arg)
			{
				OpenWatersPlugin.Log.LogError((object)$"[Gen] Could not bind world generator methods: {arg}");
				return false;
			}
			int num = (_size = 1024);
			_radius = radius;
			_cellSize = 2f * radius / (float)num;
			_land = new bool[num * num];
			_cellBiome = (Biome[])(object)new Biome[num * num];
			_sampleRow = 0;
			_started = DateTime.UtcNow.Ticks;
			_analyzing = true;
			return true;
		}

		public static bool SampleRows(int rows)
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected I4, but got Unknown
			if (!_analyzing)
			{
				return false;
			}
			int num = Mathf.Min(_sampleRow + rows, _size);
			for (int i = _sampleRow; i < num; i++)
			{
				float num2 = 0f - _radius + ((float)i + 0.5f) * _cellSize;
				for (int j = 0; j < _size; j++)
				{
					float num3 = 0f - _radius + ((float)j + 0.5f) * _cellSize;
					int num4 = i * _size + j;
					if (!(num3 * num3 + num2 * num2 > _radius * _radius) && !(_getHeight(num3, num2) <= 30f))
					{
						_land[num4] = true;
						_cellBiome[num4] = (Biome)(int)_getBiome(num3, num2, 0.02f, waterAlwaysOcean: false);
					}
				}
			}
			_sampleRow = num;
			if (_sampleRow >= _size)
			{
				_analyzing = false;
				return false;
			}
			return true;
		}

		public static bool Finish()
		{
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			if (_land == null || _sampleRow < _size)
			{
				return false;
			}
			_analyzing = false;
			bool[] land = _land;
			int size = _size;
			float radius = _radius;
			float cellSize = _cellSize;
			Biome[] cellBiome = _cellBiome;
			Stopwatch stopwatch = Stopwatch.StartNew();
			int count;
			int[] array = GridComponents.Label(land, size, out count);
			stopwatch.Stop();
			IslandInfo[] byLabel = new IslandInfo[count];
			int num = 0;
			for (int i = 0; i < land.Length; i++)
			{
				if (land[i])
				{
					int num2 = array[i];
					IslandInfo islandInfo = byLabel[num2];
					if (islandInfo == null)
					{
						islandInfo = new IslandInfo
						{
							MinX = size,
							MinY = size,
							MaxX = -1,
							MaxY = -1
						};
						byLabel[num2] = islandInfo;
					}
					int num3 = i % size;
					int num4 = i / size;
					islandInfo.Cells++;
					islandInfo.CenterX += num3;
					islandInfo.CenterY += num4;
					if (num3 < islandInfo.MinX)
					{
						islandInfo.MinX = num3;
					}
					if (num3 > islandInfo.MaxX)
					{
						islandInfo.MaxX = num3;
					}
					if (num4 < islandInfo.MinY)
					{
						islandInfo.MinY = num4;
					}
					if (num4 > islandInfo.MaxY)
					{
						islandInfo.MaxY = num4;
					}
					islandInfo.BiomeCells[BiomeSlot(cellBiome[i])]++;
					num++;
				}
			}
			List<int> list = new List<int>(count);
			for (int j = 0; j < byLabel.Length; j++)
			{
				if (byLabel[j] != null)
				{
					list.Add(j);
				}
			}
			list.Sort(delegate(int a, int b)
			{
				int num18 = byLabel[b].Cells.CompareTo(byLabel[a].Cells);
				return (num18 == 0) ? a.CompareTo(b) : num18;
			});
			int[] array2 = new int[count];
			_islands = new IslandInfo[list.Count];
			for (int num5 = 0; num5 < list.Count; num5++)
			{
				int num6 = list[num5];
				IslandInfo islandInfo2 = byLabel[num6];
				islandInfo2.Id = (ushort)num5;
				_islands[num5] = islandInfo2;
				array2[num6] = num5;
			}
			IslandInfo[] islands = _islands;
			foreach (IslandInfo islandInfo3 in islands)
			{
				islandInfo3.CenterX = (islandInfo3.CenterX / (float)islandInfo3.Cells + 0.5f) * cellSize - radius;
				islandInfo3.CenterY = (islandInfo3.CenterY / (float)islandInfo3.Cells + 0.5f) * cellSize - radius;
				int num8 = 0;
				for (int num9 = 1; num9 < islandInfo3.BiomeCells.Length; num9++)
				{
					if (islandInfo3.BiomeCells[num9] > islandInfo3.BiomeCells[num8])
					{
						num8 = num9;
					}
				}
				islandInfo3.DominantBiome = SlotBiome(num8);
				islandInfo3.DominantShare = (float)islandInfo3.BiomeCells[num8] / (float)islandInfo3.Cells;
			}
			_cellIsland = new ushort[size * size];
			for (int num10 = 0; num10 < _cellIsland.Length; num10++)
			{
				_cellIsland[num10] = ushort.MaxValue;
			}
			for (int num11 = 0; num11 < land.Length; num11++)
			{
				if (land[num11])
				{
					_cellIsland[num11] = (ushort)array2[array[num11]];
				}
			}
			_anchor = Vector2.zero;
			int num12 = Mathf.Clamp(Mathf.FloorToInt((_anchor.x + radius) / cellSize), 0, size - 1);
			int num13 = Mathf.Clamp(Mathf.FloorToInt((_anchor.y + radius) / cellSize), 0, size - 1) * size + num12;
			int num14 = (land[num13] ? array2[array[num13]] : (-1));
			int num15 = Mathf.Max(1, Mathf.CeilToInt(150000f / (cellSize * cellSize)));
			IslandCandidate[] array3 = new IslandCandidate[_islands.Length];
			for (int num16 = 0; num16 < _islands.Length; num16++)
			{
				IslandInfo islandInfo4 = _islands[num16];
				array3[num16] = new IslandCandidate
				{
					Id = islandInfo4.Id,
					Cells = islandInfo4.Cells,
					MinX = islandInfo4.MinX,
					MaxX = islandInfo4.MaxX,
					MinY = islandInfo4.MinY,
					MaxY = islandInfo4.MaxY
				};
			}
			StartIslandSelection startIslandSelection = StartIslandSelector.Select(array3, num14, _anchor.x, _anchor.y, num15, cellSize, radius, 500f, 120f);
			_startIsland = ((startIslandSelection.StartId >= 0) ? ((ushort)startIslandSelection.StartId) : ushort.MaxValue);
			BuildStartMask(startIslandSelection);
			if (startIslandSelection.StartId >= 0 && startIslandSelection.StartId == num14 && _islands[num14].Cells < num15)
			{
				OpenWatersPlugin.Log.LogWarning((object)$"[Gen] No island >= {num15} cells near the anchor; keeping the small component '{num14}'.");
			}
			long num17 = (DateTime.UtcNow.Ticks - _started) / 10000;
			IslandInfo startIsland = StartIsland;
			OpenWatersPlugin.Log.LogInfo((object)($"[Gen] Island analysis: islands={_islands.Length}, land={num}, " + $"anchor=({_anchor.x:0},{_anchor.y:0}), " + "startIsland=" + ((startIsland != null) ? startIsland.Id.ToString() : "none") + ", " + $"startCells={_startCells}, absorbed={_absorbed}, minCells={num15}, " + "center=" + ((startIsland != null) ? $"({startIsland.CenterX:0},{startIsland.CenterY:0})" : "none") + ", extent=" + ((startIsland != null) ? $"({(float)(startIsland.MaxX - startIsland.MinX + 1) * cellSize:0}x{(float)(startIsland.MaxY - startIsland.MinY + 1) * cellSize:0} m)" : "none") + ", dominant=" + ((startIsland != null) ? ((object)Unsafe.As<Biome, Biome>(ref startIsland.DominantBiome)/*cast due to .constrained prefix*/).ToString() : "none") + " " + $"({startIsland?.DominantShare ?? 0f:P0}), labels={stopwatch.ElapsedMilliseconds} ms, time={num17} ms."));
			return true;
		}

		private static void BuildStartMask(StartIslandSelection selection)
		{
			_startCells = 0;
			_absorbed = 0;
			_startMask = new bool[(_cellIsland != null) ? _cellIsland.Length : 0];
			if (selection.StartId < 0 || _cellIsland == null)
			{
				return;
			}
			HashSet<ushort> hashSet = new HashSet<ushort> { (ushort)selection.StartId };
			foreach (int absorbedId in selection.AbsorbedIds)
			{
				hashSet.Add((ushort)absorbedId);
			}
			_absorbed = selection.AbsorbedIds.Count;
			for (int i = 0; i < _cellIsland.Length; i++)
			{
				ushort num = _cellIsland[i];
				if (num != ushort.MaxValue && hashSet.Contains(num))
				{
					_startMask[i] = true;
					_startCells++;
				}
			}
		}

		private static int BiomeSlot(Biome biome)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected I4, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			if ((int)biome <= 16)
			{
				switch (biome - 1)
				{
				default:
					if ((int)biome != 8)
					{
						if ((int)biome != 16)
						{
							break;
						}
						return 5;
					}
					return 4;
				case 0:
					return 1;
				case 1:
					return 2;
				case 3:
					return 3;
				case 2:
					break;
				}
			}
			else
			{
				if ((int)biome == 32)
				{
					return 6;
				}
				if ((int)biome == 64)
				{
					return 7;
				}
				if ((int)biome == 512)
				{
					return 8;
				}
			}
			return 0;
		}

		private static Biome SlotBiome(int slot)
		{
			return (Biome)(slot switch
			{
				1 => 1, 
				2 => 2, 
				3 => 4, 
				4 => 8, 
				5 => 16, 
				6 => 32, 
				7 => 64, 
				8 => 512, 
				_ => 0, 
			});
		}

		public static bool IsStartIsland(float wx, float wy)
		{
			if (!Ready || _startMask == null || _startIsland == ushort.MaxValue)
			{
				return false;
			}
			int num = Mathf.FloorToInt((wx + _radius) / _cellSize);
			int num2 = Mathf.FloorToInt((wy + _radius) / _cellSize);
			if (num < 0 || num >= _size || num2 < 0 || num2 >= _size)
			{
				return false;
			}
			return _startMask[num2 * _size + num];
		}

		public static bool TryGetIslandAt(float wx, float wy, out IslandInfo info)
		{
			info = null;
			if (!Ready)
			{
				return false;
			}
			int num = Mathf.FloorToInt((wx + _radius) / _cellSize);
			int num2 = Mathf.FloorToInt((wy + _radius) / _cellSize);
			if (num < 0 || num >= _size || num2 < 0 || num2 >= _size)
			{
				return false;
			}
			ushort num3 = _cellIsland[num2 * _size + num];
			if (num3 == ushort.MaxValue || _islands == null)
			{
				return false;
			}
			info = _islands[num3];
			return true;
		}

		public static bool TryGetOriginalBiome(float wx, float wy, out Biome biome)
		{
			biome = (Biome)0;
			if (!Ready)
			{
				return false;
			}
			int num = Mathf.FloorToInt((wx + _radius) / _cellSize);
			int num2 = Mathf.FloorToInt((wy + _radius) / _cellSize);
			if (num < 0 || num >= _size || num2 < 0 || num2 >= _size)
			{
				return false;
			}
			biome = _cellBiome[num2 * _size + num];
			return true;
		}

		public static bool IsIsland(float wx, float wy, ushort id)
		{
			if (TryGetIslandAt(wx, wy, out var info))
			{
				return info.Id == id;
			}
			return false;
		}

		public static List<IslandInfo> FindIslands(Predicate<IslandInfo> predicate)
		{
			List<IslandInfo> list = new List<IslandInfo>();
			if (_islands == null)
			{
				return list;
			}
			IslandInfo[] islands = _islands;
			foreach (IslandInfo islandInfo in islands)
			{
				if (predicate(islandInfo))
				{
					list.Add(islandInfo);
				}
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(ZoneSystem), "GenerateLocations")]
	internal static class ZoneSystemGenerateLocationsPatch
	{
		private const float ModdedDragonqueenMinAltitude = 40f;

		[HarmonyPrefix]
		private static void Prefix(ZoneSystem __instance)
		{
			WorldSettings settings = GenerationSession.Current.Settings;
			if (!settings.AffectsGeneration || settings.IslandAmount == 2)
			{
				return;
			}
			foreach (ZoneLocation location in __instance.m_locations)
			{
				if (location != null)
				{
					string text = (string.IsNullOrEmpty(location.m_prefabName) ? location.m_name : location.m_prefabName);
					if (!string.IsNullOrEmpty(text) && text.IndexOf("Dragonqueen", StringComparison.OrdinalIgnoreCase) >= 0 && location.m_minAltitude > 40f)
					{
						OpenWatersPlugin.Log.LogInfo((object)("[Gen] " + WorldSettingsStore.GetDisplayName(settings) + ": lowering Dragonqueen min altitude " + $"{location.m_minAltitude:0} -> {40f:0}"));
						location.m_minAltitude = 40f;
					}
				}
			}
		}
	}
	internal static class NoiseModifier
	{
		private delegate float GetBaseHeightDelegate(float wx, float wy, bool menuTerrain);

		private sealed class UnityNoise : INoise
		{
			public float Perlin(double x, double y)
			{
				return Mathf.PerlinNoise((float)x, (float)y);
			}
		}

		private const float OceanThreshold = 0.02f;

		public static bool Active => GenerationSession.Current.Active;

		public static bool UsesGlobalNoise => GenerationSession.Current.UsesGlobalNoise;

		public static float HeightOffset => GenerationSession.Current.HeightOffset;

		private static bool IsFew => GenerationSession.Current.Settings.IslandAmount == 0;

		public static void SetWorld(World world, WorldSettings settings)
		{
			GenerationSession.Begin(world, settings);
		}

		public static void Cancel()
		{
			GenerationSession.Current.Cancel();
		}

		public static void LogGeneratorState(string scope, WorldGenerator generator)
		{
			if (generator == null)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Gen] Generator state (" + scope + "): no generator."));
				return;
			}
			World world = generator.m_world;
			string text = ((world != null) ? world.m_worldName : "none");
			string text2 = ((world != null) ? world.m_seedName : "none");
			int num = world?.m_seed ?? 0;
			int num2 = world?.m_worldGenVersion ?? (-1);
			OpenWatersPlugin.Log.LogInfo((object)("[Gen] Generator state: scope=" + scope + ", world='" + text + "', seedName='" + text2 + "', " + $"seed={num}, version={num2}, " + string.Format("offset0={0:0.0000}, ", ReadFloat(generator, "m_offset0")) + string.Format("offset1={0:0.0000}, ", ReadFloat(generator, "m_offset1")) + string.Format("riverSeed={0}, ", ReadInt(generator, "m_riverSeed")) + string.Format("streamSeed={0}, ", ReadInt(generator, "m_streamSeed")) + string.Format("rivers={0}, ", ReadCount(generator, "m_rivers")) + string.Format("streams={0}, ", ReadCount(generator, "m_streams")) + string.Format("lakes={0}.", ReadCount(generator, "m_lakes"))));
		}

		private static float ReadFloat(WorldGenerator generator, string field)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(WorldGenerator), field);
			if (!(fieldInfo != null))
			{
				return float.NaN;
			}
			return (float)fieldInfo.GetValue(generator);
		}

		private static int ReadInt(WorldGenerator generator, string field)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(WorldGenerator), field);
			if (!(fieldInfo != null))
			{
				return -1;
			}
			return (int)fieldInfo.GetValue(generator);
		}

		private static int ReadCount(WorldGenerator generator, string field)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(WorldGenerator), field);
			if (fieldInfo == null)
			{
				return -1;
			}
			if (!(fieldInfo.GetValue(generator) is ICollection collection))
			{
				return 0;
			}
			return collection.Count;
		}

		public static void Build(WorldGenerator generator)
		{
			GenerationSession current = GenerationSession.Current;
			current.BeginBuild();
			WorldSettings settings = current.Settings;
			World world = current.World;
			if (world == null || world.m_menu || !settings.AffectsGeneration)
			{
				return;
			}
			long ticks = DateTime.UtcNow.Ticks;
			try
			{
				FieldInfo fieldInfo = AccessTools.Field(typeof(WorldGenerator), "m_offset0");
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(WorldGenerator), "m_offset1");
				FieldInfo fieldInfo3 = AccessTools.Field(typeof(WorldGenerator), "m_minMountainDistance");
				current.Offset0 = (float)fieldInfo.GetValue(generator);
				current.Offset1 = (float)fieldInfo2.GetValue(generator);
				current.MinMountainDistance = ((fieldInfo3 != null) ? ((float)fieldInfo3.GetValue(generator)) : 1000f);
			}
			catch (Exception arg)
			{
				OpenWatersPlugin.Log.LogError((object)$"[Gen] Could not read noise offsets: {arg}");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetBaseHeight", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				OpenWatersPlugin.Log.LogError((object)"[Gen] Could not find WorldGenerator.GetBaseHeight.");
				return;
			}
			GetBaseHeightDelegate original;
			try
			{
				original = (GetBaseHeightDelegate)Delegate.CreateDelegate(typeof(GetBaseHeightDelegate), generator, methodInfo);
			}
			catch (Exception arg2)
			{
				OpenWatersPlugin.Log.LogError((object)$"[Gen] Could not bind GetBaseHeight: {arg2}");
				return;
			}
			current.UsesGlobalNoise = settings.IslandAmount != 2;
			NoiseField noiseField = (current.Field = new NoiseField(new UnityNoise(), CreateConfig(current)));
			float num = settings.WorldRadius;
			if (!current.UsesGlobalNoise)
			{
				if (settings.ExcludeMountains || settings.StartBiomeLimit != 0)
				{
					IslandAnalysis.Build(generator, num + 500f);
					current.MarkReady();
					long num2 = (DateTime.UtcNow.Ticks - ticks) / 10000;
					OpenWatersPlugin.Log.LogInfo((object)($"[Gen] Start island only: preset=Vanilla, startIsland={IslandAnalysis.StartCells}, " + $"biomeLimit={settings.StartBiomeLimit}, time={num2} ms."));
				}
				return;
			}
			LandCalibrator landCalibrator = new LandCalibrator(num);
			landCalibrator.Run(noiseField, (float wx, float wy) => original(wx, wy, menuTerrain: false) > 0.02f);
			current.HeightOffset = landCalibrator.Offset;
			current.MarkReady();
			int num3 = 0;
			if (settings.ExcludeMountains || settings.StartBiomeLimit != 0)
			{
				IslandAnalysis.Build(generator, num + 500f);
				num3 = IslandAnalysis.StartCells;
			}
			long num4 = (DateTime.UtcNow.Ticks - ticks) / 10000;
			OpenWatersPlugin.Log.LogInfo((object)("[Gen] Noise frequency: preset=" + WorldSettingsStore.GetDisplayName(settings) + ", " + $"scale={noiseField.FrequencyScale:0.00}, detail={noiseField.DetailDamping:0.00}, " + $"peak={noiseField.PeakProtection:0.00}, vanillaLand={landCalibrator.VanillaLand}, " + $"target={landCalibrator.TargetLand}, actual={landCalibrator.ActualLand}, " + $"mountains={landCalibrator.ActualMountains} " + $"({((landCalibrator.ActualLand > 0) ? (100f * (float)landCalibrator.ActualMountains / (float)landCalibrator.ActualLand) : 0f):0}% of land), " + $"startIsland={num3}, offset={landCalibrator.Offset:0.000}, time={num4} ms."));
		}

		private static NoiseFieldConfig CreateConfig(GenerationSession session)
		{
			bool isFew = IsFew;
			WorldSettings settings = session.Settings;
			return new NoiseFieldConfig
			{
				FrequencyScale = settings.FrequencyScale,
				LandFraction = settings.LandFraction,
				DetailDamping = settings.DetailDamping,
				PeakProtection = settings.PeakProtection,
				MountainCompressionStart = (isFew ? settings.FewMountainCompressionStart : 0f),
				MountainCompressionFactor = (isFew ? settings.FewMountainCompressionFactor : 1f),
				Offset0 = session.Offset0,
				Offset1 = session.Offset1,
				MinMountainDistance = session.MinMountainDistance
			};
		}

		public static float ApplyGlobal(GenerationSession session, float wx, float wy)
		{
			NoiseField field = session.Field;
			return StartIslandModifier.Apply(field.Compress(field.BaseHeight(wx, wy, session.HeightOffset)), wx, wy);
		}
	}
	internal static class StartIslandModifier
	{
		private const float SafeRadius = 250f;

		private const float SuppressStart = 0.34f;

		private const float SuppressFactor = 0.35f;

		private const float SuppressCap = 0.39f;

		public static bool TryGetBiomeOverride(float wx, float wy, Biome originalBiome, out Biome biome)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Invalid comparison between Unknown and I4
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			biome = (Biome)0;
			int startBiomeLimit = GenerationSession.Current.Settings.StartBiomeLimit;
			if ((startBiomeLimit != 1 && startBiomeLimit != 2) || !IslandAnalysis.IsStartIsland(wx, wy))
			{
				return false;
			}
			if (startBiomeLimit == 1)
			{
				biome = (Biome)1;
				return true;
			}
			if (Mathf.Sqrt(wx * wx + wy * wy) <= 250f || (int)originalBiome == 1)
			{
				biome = (Biome)1;
				return true;
			}
			if ((int)originalBiome == 8)
			{
				biome = (Biome)8;
				return true;
			}
			float num = Mathf.PerlinNoise((wx + 1000f) * 0.0015f, (wy + 1000f) * 0.0015f);
			biome = (Biome)((num > 0.5f) ? 1 : 8);
			return true;
		}

		public static float Apply(float value, float wx, float wy)
		{
			if (!GenerationSession.Current.Settings.ExcludeMountains || !IslandAnalysis.IsStartIsland(wx, wy))
			{
				return value;
			}
			if (value <= 0.34f)
			{
				return value;
			}
			return Mathf.Min(0.34f + (value - 0.34f) * 0.35f, 0.39f);
		}
	}
	internal static class WorldSettingsSync
	{
		[HarmonyPatch(typeof(ZNet), "SendPeerInfo")]
		internal static class SendPeerInfoPatch
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase method)
			{
				//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ef: Expected O, but got Unknown
				//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fd: Expected O, but got Unknown
				//IL_022d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0233: Expected O, but got Unknown
				MethodInfo writeInt = AccessTools.Method(typeof(ZPackage), "Write", new Type[1] { typeof(int) }, (Type[])null);
				MethodInfo writeDouble = AccessTools.Method(typeof(ZPackage), "Write", new Type[1] { typeof(double) }, (Type[])null);
				MethodInfo methodInfo = AccessTools.Method(typeof(WorldSettingsSync), "AppendPeerInfo", (Type[])null, (Type[])null);
				MethodInfo methodInfo2 = AccessTools.Method(typeof(WorldSettingsSync), "AppendClientMarker", (Type[])null, (Type[])null);
				FieldInfo netTime = AccessTools.Field(typeof(ZNet), "m_netTime");
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				LocalVariableInfo[] locals = GetLocals(method);
				int num = FindSequence(list, (CodeInstruction i) => i.opcode == OpCodes.Callvirt && object.Equals(i.operand, writeInt), (CodeInstruction i) => IsPackageLoad(i, locals), (CodeInstruction i) => i.opcode == OpCodes.Ldarg_0, (CodeInstruction i) => i.opcode == OpCodes.Ldfld && object.Equals(i.operand, netTime), (CodeInstruction i) => i.opcode == OpCodes.Callvirt && object.Equals(i.operand, writeDouble));
				int num2 = FindSequence(list, (CodeInstruction i) => i.opcode == OpCodes.Ldarg_1, (CodeInstruction i) => i.opcode == OpCodes.Ldstr && "PeerInfo".Equals(i.operand as string, StringComparison.Ordinal));
				if (num < 0)
				{
					OpenWatersPlugin.Log.LogError((object)"[Network] SendPeerInfo settings pattern not found; no hooks installed.");
				}
				if (num2 < 0)
				{
					OpenWatersPlugin.Log.LogError((object)"[Network] SendPeerInfo client marker pattern not found; no hooks installed.");
				}
				if (num < 0 || num2 < 0)
				{
					SettingsWriteHookActive = false;
					ClientMarkerHookActive = false;
					return list;
				}
				CodeInstruction val = list[num + 1].Clone();
				list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
				{
					val.Clone(),
					new CodeInstruction(OpCodes.Ldarg_1, (object)null),
					new CodeInstruction(OpCodes.Call, (object)methodInfo)
				});
				int index = ((num2 > num) ? (num2 + 3) : num2);
				list.InsertRange(index, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
				{
					val.Clone(),
					new CodeInstruction(OpCodes.Call, (object)methodInfo2)
				});
				SettingsWriteHookActive = true;
				ClientMarkerHookActive = true;
				OpenWatersPlugin.Log.LogInfo((object)"[Network] SendPeerInfo hooks installed.");
				return list;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		internal static class PeerInfoMarkerPatch
		{
			private static void Prefix(ZRpc rpc, ZPackage pkg)
			{
				try
				{
					ZNet instance = ZNet.instance;
					if ((Object)(object)instance == (Object)null || rpc == null || pkg == null || !OpenWatersSettings.Enabled)
					{
						return;
					}
					if (!instance.IsServer())
					{
						WorldSettingsStore.MarkPeerInfoReceived();
					}
					else if (HasClientMarker(pkg))
					{
						_moddedClients.GetValue(rpc, (ZRpc _) => _moddedMarker);
						OpenWatersPlugin.Log.LogInfo((object)"[Network] Client advertises Open Waters support.");
					}
				}
				catch (Exception ex)
				{
					OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not read the client marker: " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		internal static class PeerInfoPatch
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0087: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Expected O, but got Unknown
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Expected O, but got Unknown
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Expected O, but got Unknown
				MethodInfo initialize = AccessTools.Method(typeof(WorldGenerator), "Initialize", (Type[])null, (Type[])null);
				MethodInfo methodInfo = AccessTools.Method(typeof(WorldSettingsSync), "ReadPeerInfo", (Type[])null, (Type[])null);
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				int num = FindSequence(list, (CodeInstruction i) => i.opcode == OpCodes.Call && object.Equals(i.operand, initialize));
				if (num < 0)
				{
					SettingsReadHookActive = false;
					OpenWatersPlugin.Log.LogError((object)"[Network] RPC_PeerInfo settings pattern not found; server settings will be ignored.");
					return list;
				}
				list.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
				{
					new CodeInstruction(OpCodes.Ldarg_1, (object)null),
					new CodeInstruction(OpCodes.Ldarg_2, (object)null),
					new CodeInstruction(OpCodes.Call, (object)methodInfo)
				});
				SettingsReadHookActive = true;
				OpenWatersPlugin.Log.LogInfo((object)"[Network] RPC_PeerInfo settings hook installed.");
				return list;
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		internal static class RegisterErrorRpcPatch
		{
			private static void Postfix(ZNetPeer peer)
			{
				if (peer == null || peer.m_rpc == null)
				{
					return;
				}
				try
				{
					peer.m_rpc.Register<string>("OpenWatersError", (Action<ZRpc, string>)OnRemoteError);
				}
				catch (Exception ex)
				{
					OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not register the error RPC: " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		internal static class OnDestroyPatch
		{
			private static void Postfix()
			{
				WorldSettingsStore.ClearRemoteSnapshot();
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static PopupButtonCallback <0>__Pop;
		}

		private const string Marker = "OWS1:";

		private const string ClientMarker = "OWC1";

		private const string ErrorRpc = "OpenWatersError";

		private static readonly byte[] ClientMarkerBytes = Encoding.UTF8.GetBytes("OWC1");

		private static readonly ConditionalWeakTable<ZRpc, object> _moddedClients = new ConditionalWeakTable<ZRpc, object>();

		private static readonly object _moddedMarker = new object();

		internal static bool ClientMarkerHookActive { get; private set; }

		internal static bool SettingsWriteHookActive { get; private set; }

		internal static bool SettingsReadHookActive { get; private set; }

		private static int FindSequence(List<CodeInstruction> code, params Func<CodeInstruction, bool>[] pattern)
		{
			for (int i = 0; i <= code.Count - pattern.Length; i++)
			{
				bool flag = true;
				for (int j = 0; j < pattern.Length; j++)
				{
					if (!pattern[j](code[i + j]))
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					return i;
				}
			}
			return -1;
		}

		private static LocalVariableInfo[] GetLocals(MethodBase method)
		{
			MethodBody methodBody = ((method != null) ? method.GetMethodBody() : null);
			if (methodBody == null)
			{
				return Array.Empty<LocalVariableInfo>();
			}
			IList<LocalVariableInfo> localVariables = methodBody.LocalVariables;
			LocalVariableInfo[] array = new LocalVariableInfo[localVariables.Count];
			localVariables.CopyTo(array, 0);
			return array;
		}

		private static int? LocalIndex(CodeInstruction instruction)
		{
			OpCode opcode = instruction.opcode;
			if (opcode == OpCodes.Ldloc_0)
			{
				return 0;
			}
			if (opcode == OpCodes.Ldloc_1)
			{
				return 1;
			}
			if (opcode == OpCodes.Ldloc_2)
			{
				return 2;
			}
			if (opcode == OpCodes.Ldloc_3)
			{
				return 3;
			}
			if (opcode == OpCodes.Ldloc || opcode == OpCodes.Ldloc_S)
			{
				if (instruction.operand is LocalBuilder localBuilder)
				{
					return localBuilder.LocalIndex;
				}
				object operand = instruction.operand;
				if (operand is int)
				{
					return (int)operand;
				}
			}
			return null;
		}

		private static bool IsPackageLoad(CodeInstruction instruction, LocalVariableInfo[] locals)
		{
			int? num = LocalIndex(instruction);
			if (num.HasValue && num.Value >= 0 && num.Value < locals.Length)
			{
				return locals[num.Value].LocalType == typeof(ZPackage);
			}
			return false;
		}

		private static void OnRemoteError(ZRpc rpc, string message)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance != (Object)null && instance.IsServer())
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] A client rejected the world settings: " + message));
			}
			else
			{
				ShowError(message);
			}
		}

		private static void RejectWithMessage(ZRpc rpc, string message)
		{
			if (rpc != null)
			{
				try
				{
					rpc.Invoke("OpenWatersError", new object[1] { message });
				}
				catch (Exception ex)
				{
					OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not report the rejection to the server: " + ex.Message));
				}
			}
			ShowError(message);
		}

		private static void ShowError(string message)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			try
			{
				object obj = <>O.<0>__Pop;
				if (obj == null)
				{
					PopupButtonCallback val = UnifiedPopup.Pop;
					<>O.<0>__Pop = val;
					obj = (object)val;
				}
				UnifiedPopup.Push((PopupBase)new WarningPopup("Open Waters: incompatible world settings", message, (PopupButtonCallback)obj, false));
			}
			catch (Exception ex)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not show the world settings error: " + ex.Message));
			}
			try
			{
				ZNet instance = ZNet.instance;
				if ((Object)(object)instance != (Object)null)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "SendDisconnect", Type.EmptyTypes, (Type[])null);
					if (methodInfo != null)
					{
						methodInfo.Invoke(instance, null);
					}
					else
					{
						OpenWatersPlugin.Log.LogError((object)"[Network] SendDisconnect() not found; could not leave an incompatible world.");
					}
				}
			}
			catch (Exception ex2)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not disconnect after a world settings error: " + ex2.Message));
			}
		}

		public static void AppendClientMarker(ZPackage pkg)
		{
			ZNet instance = ZNet.instance;
			if (!((Object)(object)instance == (Object)null) && !instance.IsServer() && pkg != null && OpenWatersSettings.Enabled)
			{
				if (!SettingsReadHookActive)
				{
					OpenWatersPlugin.Log.LogError((object)"[Network] Settings read hook is not active; not advertising Open Waters.");
					return;
				}
				pkg.Write("OWC1");
				OpenWatersPlugin.Log.LogInfo((object)"[Network] Sent client marker.");
			}
		}

		public static void AppendPeerInfo(ZPackage pkg, ZRpc rpc)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsServer() || pkg == null)
			{
				return;
			}
			if (!OpenWatersSettings.Enabled)
			{
				OpenWatersPlugin.Log.LogInfo((object)"[Network] Open Waters is disabled; no settings payload is sent.");
				return;
			}
			if (!SettingsWriteHookActive)
			{
				OpenWatersPlugin.Log.LogError((object)"[Network] SendPeerInfo hook is not active; no settings payload is sent.");
				return;
			}
			GenerationSession current = GenerationSession.Current;
			World val = current?.World;
			if (val == null || val.m_menu || val.m_worldName == "OpenWatersPreview")
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] AppendPeerInfo skipped: world='" + ((val == null) ? "none" : val.m_worldName) + "', " + $"menu={val?.m_menu ?? false}."));
				return;
			}
			WorldSettings settings = current.Settings;
			if (!settings.AffectsGeneration)
			{
				OpenWatersPlugin.Log.LogInfo((object)"[Network] Vanilla world; no settings payload is sent.");
				return;
			}
			if (!ClientMarkerHookActive)
			{
				OpenWatersPlugin.Log.LogError((object)"[Network] Client marker hook is not active; skipping settings and client enforcement.");
				return;
			}
			if (!IsClientModded(rpc))
			{
				OpenWatersPlugin.Log.LogWarning((object)"[Network] Rejecting a client without Open Waters; the server requires the mod.");
				RejectClient(rpc);
				return;
			}
			if (string.IsNullOrEmpty(val.m_seedName))
			{
				OpenWatersPlugin.Log.LogError((object)"[Network] Server world has no seed; skipping the settings payload.");
				return;
			}
			string text = WorldSettingsCodec.Serialize(settings, val.m_seedName);
			pkg.Write("OWS1:" + text);
			OpenWatersPlugin.Log.LogInfo((object)("[Network] Sending world settings: world='" + val.m_worldName + "', seed='" + val.m_seedName + "', " + $"preset={settings.IslandAmount}, radius={settings.WorldRadius}, " + $"biomes={settings.StartBiomeLimit}, mountains={settings.ExcludeMountains}, " + $"generatorVersion={settings.GeneratorVersionValue}, modVersion={settings.ModVersion}, " + $"bytes={text.Length}."));
		}

		public static void ReadPeerInfo(ZRpc rpc, ZPackage pkg)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null || instance.IsServer() || pkg == null)
			{
				OpenWatersPlugin.Log.LogInfo((object)"[Network] ReadPeerInfo skipped: not a client.");
				return;
			}
			if (!OpenWatersSettings.Enabled)
			{
				WorldSettingsStore.ClearRemoteSnapshot();
				return;
			}
			WorldSettingsStore.MarkPeerInfoReceived();
			try
			{
				int pos = pkg.GetPos();
				int num = pkg.Size();
				string text;
				int consumed;
				PeerInfoPayloadKind peerInfoPayloadKind = PeerInfoPayload.Read(pkg.GetArray(), pos, num, "OWS1:", out text, out consumed);
				OpenWatersPlugin.Log.LogInfo((object)$"[Network] ReadPeerInfo: position={pos}, remaining={num - pos}, kind={peerInfoPayloadKind}.");
				if (consumed > 0)
				{
					pkg.SetPos(pos + consumed);
				}
				switch (peerInfoPayloadKind)
				{
				case PeerInfoPayloadKind.NoExtension:
					OpenWatersPlugin.Log.LogInfo((object)"[Network] Server does not use Open Waters; playing a vanilla world.");
					return;
				case PeerInfoPayloadKind.EmptyExtension:
					OpenWatersPlugin.Log.LogWarning((object)"[Network] PeerInfo extension is empty.");
					return;
				case PeerInfoPayloadKind.OtherMod:
					OpenWatersPlugin.Log.LogInfo((object)"[Network] PeerInfo extension belongs to another mod; using vanilla generation.");
					return;
				case PeerInfoPayloadKind.Malformed:
					OpenWatersPlugin.Log.LogWarning((object)"[Network] PeerInfo extension is malformed.");
					return;
				case PeerInfoPayloadKind.UnsupportedVersion:
					OpenWatersPlugin.Log.LogError((object)"[Network] Server sent an unsupported Open Waters payload version.");
					WorldSettingsStore.MarkRemotePayloadInvalid();
					RejectWithMessage(rpc, "The server uses an Open Waters payload version this client does not support.");
					return;
				}
				string text2 = text.Substring("OWS1:".Length);
				FieldInfo fieldInfo = AccessTools.Field(typeof(ZNet), "m_world");
				World val = (World)((fieldInfo != null) ? /*isinst with value type is only supported in some contexts*/: null);
				string text3 = ((val != null) ? val.m_seedName : string.Empty);
				if (!WorldSettingsCodec.TryParse(text2, text3, out var settings))
				{
					OpenWatersPlugin.Log.LogError((object)"[Network] Server sent invalid Open Waters settings.");
					WorldSettingsStore.MarkRemotePayloadInvalid();
					RejectWithMessage(rpc, "The server sent invalid Open Waters world settings.");
				}
				else if (!settings.IsGeneratorCompatible)
				{
					OpenWatersPlugin.Log.LogError((object)($"[Network] Server generator version {settings.GeneratorVersionValue} is not supported " + "(" + WorldSettings.SupportedVersionsText + ")."));
					WorldSettingsStore.MarkRemotePayloadInvalid();
					RejectWithMessage(rpc, $"The server uses generator version {settings.GeneratorVersionValue}; " + "this client supports " + WorldSettings.SupportedVersionsText + ".");
				}
				else
				{
					WorldSettingsStore.SetRemoteSnapshot(settings, text3);
					OpenWatersPlugin.Log.LogInfo((object)("[Network] Received world settings from server for seed '" + text3 + "': " + $"preset={settings.IslandAmount}, generatorVersion={settings.GeneratorVersionValue}."));
				}
			}
			catch (Exception ex)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not read world settings: " + ex.Message));
			}
		}

		private static bool HasClientMarker(ZPackage pkg)
		{
			return PeerInfoProtocol.EndsWith(pkg.GetArray(), pkg.Size(), ClientMarkerBytes);
		}

		private static bool IsClientModded(ZRpc rpc)
		{
			object value;
			if (rpc != null)
			{
				return _moddedClients.TryGetValue(rpc, out value);
			}
			return false;
		}

		private static void RejectClient(ZRpc rpc)
		{
			if (rpc == null)
			{
				return;
			}
			try
			{
				rpc.Invoke("Error", new object[1] { 3 });
			}
			catch (Exception ex)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not reject the client: " + ex.Message));
			}
			try
			{
				ZNet instance = ZNet.instance;
				MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null);
				ZNetPeer val = (ZNetPeer)(((Object)(object)instance != (Object)null && methodInfo != null) ? /*isinst with value type is only supported in some contexts*/: null);
				if (val != null)
				{
					instance.Disconnect(val);
					OpenWatersPlugin.Log.LogWarning((object)"[Network] Kicked a client without Open Waters.");
				}
				else
				{
					OpenWatersPlugin.Log.LogWarning((object)"[Network] Could not find the peer to kick; the client may stay connected.");
				}
			}
			catch (Exception ex2)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Network] Could not disconnect the client: " + ex2.Message));
			}
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "OnWorldStart")]
	internal static class FejdStartupOnWorldStartPatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static PopupButtonCallback <0>__Pop;
		}

		[HarmonyPrefix]
		private static bool Prefix(FejdStartup __instance)
		{
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			WorldSettingsStore.ClearRemoteSnapshot();
			if (!OpenWatersSettings.Enabled)
			{
				return true;
			}
			try
			{
				World value = Traverse.Create((object)__instance).Field("m_world").GetValue<World>();
				if (value == null || value.m_menu)
				{
					return true;
				}
				if (WorldSettingsStore.ValidateForLoad(value) == SidecarStatus.Invalid)
				{
					string lastMessage = WorldSettingsStore.LastMessage;
					OpenWatersPlugin.Log.LogError((object)("[Settings] Blocking world load: " + lastMessage));
					object obj = <>O.<0>__Pop;
					if (obj == null)
					{
						PopupButtonCallback val = UnifiedPopup.Pop;
						<>O.<0>__Pop = val;
						obj = (object)val;
					}
					UnifiedPopup.Push((PopupBase)new WarningPopup("Open Waters: incompatible world", lastMessage, (PopupButtonCallback)obj, false));
					return false;
				}
			}
			catch (Exception ex)
			{
				string text = "Could not validate the world settings: " + ex.Message;
				OpenWatersPlugin.Log.LogError((object)("[Settings] " + text));
				object obj2 = <>O.<0>__Pop;
				if (obj2 == null)
				{
					PopupButtonCallback val2 = UnifiedPopup.Pop;
					<>O.<0>__Pop = val2;
					obj2 = (object)val2;
				}
				UnifiedPopup.Push((PopupBase)new WarningPopup("Open Waters: could not validate world", text, (PopupButtonCallback)obj2, false));
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "OnNewWorldDone")]
	internal static class FejdStartupOnNewWorldDonePatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static PopupButtonCallback <0>__Pop;
		}

		[HarmonyPrefix]
		private static bool Prefix()
		{
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			WorldSettingsStore.ClearRemoteSnapshot();
			if (!OpenWatersSettings.Enabled)
			{
				return true;
			}
			FejdStartup instance = FejdStartup.instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.m_newWorldName != (Object)null && (Object)(object)instance.m_newWorldSeed != (Object)null)
			{
				string text = ((TMP_InputField)instance.m_newWorldName).text;
				if (!string.IsNullOrEmpty(text) && !World.HaveWorld(text))
				{
					string text2 = ((TMP_InputField)instance.m_newWorldSeed).text;
					if (!WorldSettingsStore.TryWriteForNewWorld(text, text2, out var error))
					{
						string text3 = "Could not save Open Waters settings for world '" + text + "': " + error + ". World creation was cancelled.";
						OpenWatersPlugin.Log.LogError((object)("[Settings] " + text3));
						object obj = <>O.<0>__Pop;
						if (obj == null)
						{
							PopupButtonCallback val = UnifiedPopup.Pop;
							<>O.<0>__Pop = val;
							obj = (object)val;
						}
						UnifiedPopup.Push((PopupBase)new WarningPopup("Open Waters: could not save world settings", text3, (PopupButtonCallback)obj, false));
						return false;
					}
				}
			}
			return true;
		}
	}
	[BepInPlugin("valheim.openwaters", "Open Waters", "0.2.0")]
	[BepInProcess("valheim.exe")]
	public class OpenWatersPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "valheim.openwaters";

		public const string PluginName = "Open Waters";

		public const string PluginVersion = "0.2.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> EnabledConfig;

		internal static ConfigEntry<bool> DebugSelfTestConfig;

		internal static ConfigEntry<float> FewLandFractionConfig;

		internal static ConfigEntry<float> FewFrequencyScaleConfig;

		internal static ConfigEntry<float> FewPeakProtectionConfig;

		internal static ConfigEntry<float> FewDetailDampingConfig;

		internal static ConfigEntry<float> FewMountainCompressionStartConfig;

		internal static ConfigEntry<float> FewMountainCompressionFactorConfig;

		internal static ConfigEntry<float> MediumLandFractionConfig;

		internal static ConfigEntry<float> MediumFrequencyScaleConfig;

		internal static ConfigEntry<float> MediumPeakProtectionConfig;

		internal static ConfigEntry<float> MediumDetailDampingConfig;

		private void Awake()
		{
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			EnabledConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable Open Waters world generation and UI controls.");
			DebugSelfTestConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DebugSelfTest", false, "Run built-in generation and network checks at startup and write results to the log.");
			FewLandFractionConfig = BindFloat("Few", "LandFraction", 0.27f, 0.01f, 1f, "Target land fraction for Few (relative to vanilla land).");
			FewFrequencyScaleConfig = BindFloat("Few", "FrequencyScale", 0.6f, 0.1f, 2f, "Noise frequency multiplier for Few. Lower values create larger islands.");
			FewPeakProtectionConfig = BindFloat("Few", "PeakProtection", 0.2f, 0f, 1f, "How strongly high peaks resist the land-lowering offset for Few.");
			FewDetailDampingConfig = BindFloat("Few", "DetailDamping", 0.35f, 0f, 1f, "Detail noise multiplier for Few.");
			FewMountainCompressionStartConfig = BindFloat("Few", "MountainCompressionStart", 0.34f, 0f, 1f, "Height above which Few compresses mountain terrain.");
			FewMountainCompressionFactorConfig = BindFloat("Few", "MountainCompressionFactor", 0.55f, 0f, 1f, "Compression factor for high terrain in Few. Lower values flatten mountains.");
			MediumLandFractionConfig = BindFloat("Medium", "LandFraction", 0.5f, 0.01f, 1f, "Target land fraction for Medium (relative to vanilla land).");
			MediumFrequencyScaleConfig = BindFloat("Medium", "FrequencyScale", 0.7f, 0.1f, 2f, "Noise frequency multiplier for Medium. Lower values create larger islands.");
			MediumPeakProtectionConfig = BindFloat("Medium", "PeakProtection", 0.6f, 0f, 1f, "How strongly high peaks resist the land-lowering offset for Medium.");
			MediumDetailDampingConfig = BindFloat("Medium", "DetailDamping", 0.35f, 0f, 1f, "Detail noise multiplier for Medium.");
			OpenWatersSettings.Enabled = EnabledConfig.Value;
			OpenWatersSettings.DebugSelfTest = DebugSelfTestConfig.Value;
			new Harmony("valheim.openwaters").PatchAll();
			if (OpenWatersSettings.DebugSelfTest)
			{
				SelfTest.Run(delegate(string message)
				{
					Log.LogInfo((object)message);
				});
			}
			((Component)this).gameObject.AddComponent<WorldCreationUI>();
			Log.LogInfo((object)$"Open Waters plugin loaded (enabled={OpenWatersSettings.Enabled}).");
		}

		private ConfigEntry<float> BindFloat(string section, string key, float defaultValue, float min, float max, string description)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			return ((BaseUnityPlugin)this).Config.Bind<float>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), Array.Empty<object>()));
		}

		internal static void SetEnabled(bool enabled)
		{
			OpenWatersSettings.Enabled = enabled;
			if (EnabledConfig != null)
			{
				EnabledConfig.Value = enabled;
				((ConfigEntryBase)EnabledConfig).ConfigFile.Save();
			}
			Log.LogInfo((object)$"Open Waters enabled={enabled}");
		}
	}
	internal static class OpenWatersSettings
	{
		public const int MinWorldRadius = 6000;

		public const int MaxWorldRadius = 10000;

		public const int DefaultWorldRadius = 10000;

		public const int FewIslands = 0;

		public const int MediumIslands = 1;

		public const int VanillaIslandAmount = 2;

		public const string PreviewWorldName = "OpenWatersPreview";

		public static int WorldRadius = 10000;

		public static int IslandAmount = 2;

		public static int BiomeLimit;

		public static int StartBiomeLimit;

		public static bool ExcludeMountains = false;

		public static bool Enabled = true;

		public static bool DebugSelfTest;

		public static bool PreviewEnabled;

		public static float FewLandFraction => Clamp(OpenWatersPlugin.FewLandFractionConfig?.Value, 0.27f, 0.01f, 1f);

		public static float MediumLandFraction => Clamp(OpenWatersPlugin.MediumLandFractionConfig?.Value, 0.5f, 0.01f, 1f);

		public static float FewFrequencyScale => Clamp(OpenWatersPlugin.FewFrequencyScaleConfig?.Value, 0.6f, 0.1f, 2f);

		public static float MediumFrequencyScale => Clamp(OpenWatersPlugin.MediumFrequencyScaleConfig?.Value, 0.7f, 0.1f, 2f);

		public static float FewPeakProtection => Clamp(OpenWatersPlugin.FewPeakProtectionConfig?.Value, 0.2f, 0f, 1f);

		public static float MediumPeakProtection => Clamp(OpenWatersPlugin.MediumPeakProtectionConfig?.Value, 0.6f, 0f, 1f);

		public static float FewDetailDamping => Clamp(OpenWatersPlugin.FewDetailDampingConfig?.Value, 0.35f, 0f, 1f);

		public static float MediumDetailDamping => Clamp(OpenWatersPlugin.MediumDetailDampingConfig?.Value, 0.35f, 0f, 1f);

		public static float FewMountainCompressionStart => Clamp(OpenWatersPlugin.FewMountainCompressionStartConfig?.Value, 0.34f, 0f, 1f);

		public static float FewMountainCompressionFactor => Clamp(OpenWatersPlugin.FewMountainCompressionFactorConfig?.Value, 0.55f, 0f, 1f);

		public static bool AffectsGeneration
		{
			get
			{
				if (Enabled)
				{
					if (IslandAmount == 2 && !ExcludeMountains)
					{
						return StartBiomeLimit != 0;
					}
					return true;
				}
				return false;
			}
		}

		public static string IslandAmountName
		{
			get
			{
				if (IslandAmount == 0)
				{
					return "Few";
				}
				if (IslandAmount == 1)
				{
					return "Medium";
				}
				if (IslandAmount == 2)
				{
					return "Vanilla";
				}
				return "Unknown";
			}
		}

		public static float LandFraction
		{
			get
			{
				if (IslandAmount == 0)
				{
					return FewLandFraction;
				}
				if (IslandAmount == 1)
				{
					return MediumLandFraction;
				}
				return 1f;
			}
		}

		private static float Clamp(float? value, float fallback, float min, float max)
		{
			return Mathf.Clamp(value ?? fallback, min, max);
		}
	}
	internal enum SidecarStatus
	{
		Ok,
		Missing,
		Invalid
	}
	internal static class WorldSettingsStore
	{
		private const string SidecarFileName = "OpenWaters.worldSettings";

		private static ISidecarStorage _storage = new FileSidecarStorage();

		private static readonly RemoteSettingsState _remote = new RemoteSettingsState();

		public static SidecarStatus LastStatus { get; private set; } = SidecarStatus.Missing;

		public static string LastMessage { get; private set; } = string.Empty;

		internal static void SetStorage(ISidecarStorage storage)
		{
			_storage = storage ?? new FileSidecarStorage();
		}

		public static void SetRemoteSnapshot(WorldSettings settings, string seed)
		{
			_remote.Set(settings, seed);
		}

		public static void MarkPeerInfoReceived()
		{
			_remote.MarkPeerInfoReceived();
		}

		public static void MarkRemotePayloadInvalid()
		{
			_remote.MarkPayloadInvalid();
		}

		public static void ClearRemoteSnapshot()
		{
			_remote.Clear();
		}

		public static WorldSettings FromCurrentSettings(string seed)
		{
			return new WorldSettings(OpenWatersSettings.IslandAmount, OpenWatersSettings.WorldRadius, OpenWatersSettings.BiomeLimit, OpenWatersSettings.StartBiomeLimit, OpenWatersSettings.ExcludeMountains, "0.2.0", OpenWatersSettings.FewLandFraction, OpenWatersSettings.FewFrequencyScale, OpenWatersSettings.FewPeakProtection, OpenWatersSettings.FewDetailDamping, OpenWatersSettings.FewMountainCompressionStart, OpenWatersSettings.FewMountainCompressionFactor, OpenWatersSettings.MediumLandFraction, OpenWatersSettings.MediumFrequencyScale, OpenWatersSettings.MediumPeakProtection, OpenWatersSettings.MediumDetailDamping);
		}

		public static bool TryWriteForNewWorld(string name, string seed, out string error)
		{
			error = null;
			if (string.IsNullOrEmpty(name) || seed == null)
			{
				error = (string.IsNullOrEmpty(name) ? "World name is empty." : "World seed is missing.");
				return false;
			}
			string sidecarPath = GetSidecarPath(name);
			if (sidecarPath == null)
			{
				error = "Could not resolve the local save directory.";
				return false;
			}
			try
			{
				string directoryName = Path.GetDirectoryName(sidecarPath);
				if (!string.IsNullOrEmpty(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				string text = sidecarPath + ".tmp";
				_storage.Write(text, WorldSettingsCodec.Serialize(FromCurrentSettings(seed), seed));
				if (_storage.Exists(sidecarPath))
				{
					_storage.Delete(sidecarPath);
				}
				_storage.Move(text, sidecarPath);
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] Saved sidecar '" + sidecarPath + "'."));
				return true;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				OpenWatersPlugin.Log.LogError((object)$"[Settings] Failed to write sidecar '{sidecarPath}': {ex}");
				return false;
			}
		}

		public static WorldSettings Apply(World world)
		{
			LastStatus = SidecarStatus.Missing;
			LastMessage = string.Empty;
			if (world == null || world.m_menu)
			{
				OpenWatersPlugin.Log.LogInfo((object)"[Settings] Apply: menu or null world, staying vanilla.");
				return WorldSettings.Vanilla;
			}
			if (!OpenWatersSettings.Enabled)
			{
				LastMessage = "Open Waters is disabled; generation stays vanilla.";
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] " + LastMessage));
				return WorldSettings.Vanilla;
			}
			OpenWatersPlugin.Log.LogInfo((object)("[Settings] Apply: world='" + world.m_worldName + "', seed='" + world.m_seedName + "', " + $"enabled={OpenWatersSettings.Enabled}."));
			if (world.m_worldName == "OpenWatersPreview")
			{
				LastStatus = SidecarStatus.Ok;
				WorldSettings worldSettings = FromCurrentSettings(world.m_seedName);
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] Apply: preview world, preset=" + GetDisplayName(worldSettings) + ", " + $"radius={worldSettings.WorldRadius}, biomes={worldSettings.StartBiomeLimit}, mountains={worldSettings.ExcludeMountains}."));
				return worldSettings;
			}
			WorldSettings settings;
			switch (_remote.Resolve(world.m_seedName, out settings))
			{
			case RemoteSettingsStatus.Accepted:
				LastStatus = SidecarStatus.Ok;
				LastMessage = "Using settings received from the server for seed '" + world.m_seedName + "'.";
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] " + LastMessage + "; preset=" + GetDisplayName(settings) + ", " + $"radius={settings.WorldRadius}, biomes={settings.StartBiomeLimit}, " + $"mountains={settings.ExcludeMountains}, " + $"generatorVersion={settings.GeneratorVersionValue}."));
				return settings;
			case RemoteSettingsStatus.NoSnapshot:
				LastStatus = SidecarStatus.Missing;
				LastMessage = "Server does not use Open Waters; generation stays vanilla.";
				goto default;
			case RemoteSettingsStatus.SeedMismatch:
				LastStatus = SidecarStatus.Invalid;
				LastMessage = "Server world settings belong to a different seed; generation stays vanilla.";
				goto default;
			case RemoteSettingsStatus.InvalidPayload:
				LastStatus = SidecarStatus.Invalid;
				LastMessage = "Server world settings are incompatible; generation stays vanilla.";
				goto default;
			case RemoteSettingsStatus.IncompatibleGenerator:
				LastStatus = SidecarStatus.Invalid;
				LastMessage = $"Server uses generator version {settings.GeneratorVersionValue}, " + "this mod supports " + WorldSettings.SupportedVersionsText + ".";
				goto default;
			default:
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] " + LastMessage));
				return WorldSettings.Vanilla;
			case RemoteSettingsStatus.NotReceived:
			{
				string text = FindSidecarPath(world);
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] Sidecar path: '" + (text ?? "none") + "'."));
				if (text == null || !_storage.Exists(text))
				{
					LastMessage = "No sidecar for '" + world.m_worldName + "'; using vanilla generation.";
					OpenWatersPlugin.Log.LogInfo((object)("[Settings] " + LastMessage));
					return WorldSettings.Vanilla;
				}
				WorldSettings settings2;
				try
				{
					if (!WorldSettingsCodec.TryParse(_storage.Read(text), world.m_seedName, out settings2))
					{
						LastStatus = SidecarStatus.Invalid;
						LastMessage = "Sidecar for '" + world.m_worldName + "' is unreadable or has an incompatible format.";
						OpenWatersPlugin.Log.LogError((object)("[Settings] " + LastMessage));
						return WorldSettings.Vanilla;
					}
				}
				catch (Exception ex)
				{
					LastStatus = SidecarStatus.Invalid;
					LastMessage = "Failed to read sidecar for '" + world.m_worldName + "': " + ex.Message;
					OpenWatersPlugin.Log.LogError((object)("[Settings] " + LastMessage));
					return WorldSettings.Vanilla;
				}
				if (!settings2.IsGeneratorCompatible)
				{
					int generatorVersionValue = settings2.GeneratorVersionValue;
					settings2 = WorldSettings.Vanilla;
					LastStatus = SidecarStatus.Invalid;
					LastMessage = $"World '{world.m_worldName}' was generated by generator version {generatorVersionValue}, " + "but this mod supports " + WorldSettings.SupportedVersionsText + ".";
					OpenWatersPlugin.Log.LogError((object)("[Settings] " + LastMessage));
					return settings2;
				}
				LastStatus = SidecarStatus.Ok;
				LastMessage = "Loaded settings for '" + world.m_worldName + "'";
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] " + LastMessage + ": file='" + text + "', seed='" + world.m_seedName + "', " + $"preset={GetDisplayName(settings2)}, radius={settings2.WorldRadius}, " + $"biomes={settings2.StartBiomeLimit}, mountains={settings2.ExcludeMountains}, " + $"generatorVersion={settings2.GeneratorVersionValue}, modVersion={settings2.ModVersion}."));
				return settings2;
			}
			}
		}

		public static SidecarStatus ValidateForLoad(World world)
		{
			Apply(world);
			return LastStatus;
		}

		public static string GetDisplayName(WorldSettings settings)
		{
			if (settings.IslandAmount != 0)
			{
				if (settings.IslandAmount != 1)
				{
					return "Vanilla";
				}
				return "Medium";
			}
			return "Few";
		}

		private static string FindSidecarPath(World world)
		{
			string sidecarPath = GetSidecarPath(world.m_worldName);
			if (sidecarPath != null)
			{
				return sidecarPath;
			}
			if (string.IsNullOrEmpty(world.m_seedName))
			{
				return null;
			}
			try
			{
				string worldsSaveRootPath = SaveSystem.GetWorldsSaveRootPath((FileSource)2);
				string[] directories = _storage.GetDirectories(worldsSaveRootPath);
				OpenWatersPlugin.Log.LogInfo((object)$"[Settings] World name is empty; searching {directories.Length} local folders for seed '{world.m_seedName}'.");
				string text = SidecarLocator.FindBySeed(directories, world.m_seedName, (string path) => (!_storage.Exists(path)) ? null : _storage.Read(path), (string directory) => Path.Combine(directory, "OpenWaters.worldSettings"));
				OpenWatersPlugin.Log.LogInfo((object)("[Settings] Seed search result: '" + (text ?? "none") + "'."));
				return text;
			}
			catch (Exception ex)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Settings] Could not search sidecars by seed: " + ex.Message));
				return null;
			}
		}

		private static string GetSidecarPath(string worldName)
		{
			if (string.IsNullOrEmpty(worldName) || worldName == "." || worldName == "..")
			{
				return null;
			}
			char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
			foreach (char value in invalidFileNameChars)
			{
				if (worldName.IndexOf(value) >= 0)
				{
					return null;
				}
			}
			try
			{
				return Path.Combine(SaveSystem.GetWorldsSaveRootPath((FileSource)2) + "/" + worldName + "/", "OpenWaters.worldSettings");
			}
			catch (Exception ex)
			{
				OpenWatersPlugin.Log.LogWarning((object)("[Settings] Failed to resolve save directory for '" + worldName + "': " + ex.Message));
				return null;
			}
		}
	}
	internal static class BiomePalette
	{
		public static readonly Color32 Outside = new Color32((byte)4, (byte)8, (byte)16, byte.MaxValue);

		public static readonly Color32 Water = new Color32((byte)30, (byte)70, (byte)122, byte.MaxValue);

		public static readonly Color32 Land = new Color32((byte)116, (byte)178, (byte)94, byte.MaxValue);

		public static readonly Color32 SwampWater = new Color32((byte)88, (byte)116, (byte)92, byte.MaxValue);

		public static readonly Color32 HiddenL