Decompiled source of Voyage Recorder v0.2.2

BepInEx/plugins/VoyageRecorder/VoyageRecorder.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("0.2.2.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.1", FrameworkDisplayName = ".NET Framework 4.7.1")]
[assembly: AssemblyVersion("0.2.2.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 VoyageRecorder
{
	internal sealed class ConfigurationManagerAttributes
	{
		public int? Order;
	}
	internal static class Discoveries
	{
		private static class ScrambledSeas
		{
			private const string PluginId = "com.nandbrew.scrambledseas";

			private static bool resolved;

			private static bool present;

			private static ConfigFile config;

			private static MethodInfo headingDegrees;

			private static FieldInfo enabled;

			private static PropertyInfo saveContainer;

			private static string version;

			public static bool Active
			{
				get
				{
					Resolve();
					bool flag = default(bool);
					int num;
					if (config != null)
					{
						object value = enabled.GetValue(null);
						if (value is bool)
						{
							flag = (bool)value;
							num = 1;
						}
						else
						{
							num = 0;
						}
					}
					else
					{
						num = 0;
					}
					return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				}
			}

			public static string HintKind => Setting("Destination Hint")?.ToString() ?? "";

			public static int Points
			{
				get
				{
					if (!(Setting("Number of ordinal directions") is int num) || (num != 4 && num != 8 && num != 16))
					{
						return 32;
					}
					return num;
				}
			}

			public static int Decimals
			{
				get
				{
					if (!(Setting("Coordinate precision") is int num))
					{
						return 0;
					}
					return Mathf.Clamp(num, 0, 6);
				}
			}

			public static bool HidesDistance
			{
				get
				{
					object obj = Setting("Hide mission distance");
					bool flag = default(bool);
					int num;
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
					return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				}
			}

			private static void Resolve()
			{
				if (resolved)
				{
					return;
				}
				resolved = true;
				if (Chainloader.PluginInfos.TryGetValue("com.nandbrew.scrambledseas", out var value) && !((Object)(object)value.Instance == (Object)null))
				{
					present = true;
					Assembly assembly = ((object)value.Instance).GetType().Assembly;
					headingDegrees = assembly.GetType("ScrambledSeas.CompassRose")?.GetMethod("GetHeadingDegrees", BindingFlags.Static | BindingFlags.Public);
					Type? type = assembly.GetType("ScrambledSeas.Main");
					enabled = type?.GetField("pluginEnabled", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					saveContainer = type?.GetProperty("saveContainer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					config = value.Instance.Config;
					version = value.Metadata.Version?.ToString();
					if (headingDegrees == null || enabled == null)
					{
						Plugin.LogOnce("Scrambled Seas was found, but not the parts mission hints need, so missions aren't recorded.");
						config = null;
					}
				}
			}

			public static Vector3? IslandOffset(int island)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				if (!Active)
				{
					return Vector3.zero;
				}
				if (saveContainer == null || island < 1)
				{
					return null;
				}
				object value = saveContainer.GetValue(null, null);
				if (!(value?.GetType().GetProperty("islandOffsets")?.GetValue(value, null) is Vector3[] array))
				{
					return null;
				}
				return (island - 1 < array.Length) ? array[island - 1] : Vector3.zero;
			}

			public static WorldInfo World()
			{
				//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_0104: Unknown result type (might be due to invalid IL or missing references)
				//IL_010f: Unknown result type (might be due to invalid IL or missing references)
				//IL_011a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				Resolve();
				if (!present)
				{
					return new WorldInfo();
				}
				object obj = enabled?.GetValue(null);
				if (!(obj is bool))
				{
					Plugin.LogOnce("Voyage Recorder could not tell whether Scrambled Seas is on, so recordings leave the world out.");
					return null;
				}
				if (!(bool)obj)
				{
					return new WorldInfo();
				}
				object container = saveContainer?.GetValue(null, null);
				if (container == null)
				{
					Plugin.LogOnce("Voyage Recorder could not read Scrambled Seas' world settings, so recordings leave the world out.");
					return null;
				}
				Type type = container.GetType();
				List<string> missing = new List<string>();
				List<double> list = new List<double>();
				string[] array = new string[2] { "archOffsets", "islandOffsets" };
				foreach (string text in array)
				{
					if (type.GetProperty(text)?.GetValue(container, null) is Vector3[] array2)
					{
						Vector3[] array3 = array2;
						foreach (Vector3 val in array3)
						{
							list.AddRange(new double[3] { val.x, val.y, val.z });
						}
					}
					else
					{
						missing.Add(text);
					}
				}
				WorldInfo result = new WorldInfo
				{
					Scrambled = true,
					Seed = Number("worldScramblerSeed"),
					IslandSpread = Number("islandSpread"),
					MinArchipelagoSeparation = Number("minArchipelagoSeparation"),
					MinIslandSeparation = Number("minIslandSeparation"),
					LonMin = Number("worldLonMin"),
					LonMax = Number("worldLonMax"),
					LatMin = Number("worldLatMin"),
					LatMax = Number("worldLatMax"),
					BorderExpander = Number("borderExpander"),
					Scrambler = Number("version"),
					ScrambledSeas = version,
					Layout = LogFormat.LayoutFingerprint(list)
				};
				if (missing.Count == 0)
				{
					return result;
				}
				Plugin.LogOnce("Voyage Recorder could not read Scrambled Seas' " + string.Join(", ", missing) + ", so recordings leave the world out.");
				return null;
				int Number(string name)
				{
					object obj2 = type.GetProperty(name)?.GetValue(container, null);
					if (obj2 is int)
					{
						return (int)obj2;
					}
					missing.Add(name);
					return 0;
				}
			}

			public static double HeadingDegrees(Vector3 origin, Vector3 target)
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				return Convert.ToDouble(headingDegrees.Invoke(null, new object[2] { origin, target }));
			}

			private static object Setting(string key)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Expected O, but got Unknown
				ConfigDefinition val = new ConfigDefinition("Settings", key);
				if (config == null || !config.ContainsKey(val))
				{
					return null;
				}
				return config[val].BoxedValue;
			}
		}

		public static int IslandOf(Port port)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			Transform[] islands = Refs.islands;
			if (islands == null || (Object)(object)port == (Object)null)
			{
				return -1;
			}
			Vector3 position = ((Component)port).transform.position;
			int result = -1;
			float num = float.MaxValue;
			for (int i = 0; i < islands.Length; i++)
			{
				if (!((Object)(object)islands[i] == (Object)null))
				{
					Vector3 val = islands[i].position - position;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (sqrMagnitude < num)
					{
						num = sqrMagnitude;
						result = i;
					}
				}
			}
			return result;
		}

		public static PortVisit Visit(Port port, int day, double hour)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			int num = IslandOf(port);
			Vector3 globeCoords = FloatingOriginManager.instance.GetGlobeCoords(((Component)port).transform);
			Vector3 val = ((num >= 0) ? FloatingOriginManager.instance.GetGlobeCoords(Refs.islands[num]) : globeCoords);
			Vector3? val2 = ScrambledSeas.IslandOffset(num);
			return new PortVisit
			{
				Day = day,
				Hour = hour,
				Port = port.GetPortName(),
				Island = num,
				Lat = val.z,
				Lon = val.x,
				PortLat = globeCoords.z,
				PortLon = globeCoords.x,
				OffsetLat = (double?)val2?.z / 9000.0,
				OffsetLon = (double?)val2?.x / 9000.0
			};
		}

		public static MissionHint? Hint(Mission mission, int day, double hour)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)mission?.originPort == (Object)null || (Object)(object)mission.destinationPort == (Object)null)
			{
				return null;
			}
			if (!ScrambledSeas.Active)
			{
				Plugin.LogOnce("Missions aren't recorded: Scrambled Seas isn't installed or is off for this game.");
				return null;
			}
			Port originPort = mission.originPort;
			Port destinationPort = mission.destinationPort;
			Vector3 globeCoords = FloatingOriginManager.instance.GetGlobeCoords(((Component)originPort).transform);
			MissionHint value = new MissionHint
			{
				Day = day,
				Hour = hour,
				Origin = originPort.GetPortName(),
				OriginIsland = IslandOf(originPort),
				OriginLat = globeCoords.z,
				OriginLon = globeCoords.x,
				Destination = destinationPort.GetPortName(),
				DestinationIsland = IslandOf(destinationPort)
			};
			string hintKind = ScrambledSeas.HintKind;
			if (hintKind == "Heading")
			{
				int points = ScrambledSeas.Points;
				value.Heading = LogFormat.CompassHeading(ScrambledSeas.HeadingDegrees(((Component)originPort).transform.position, ((Component)destinationPort).transform.position), points);
				value.Points = points;
			}
			else
			{
				if (!(hintKind == "Coords"))
				{
					Plugin.LogOnce("Missions aren't recorded: Scrambled Seas' Destination Hint is " + ((hintKind == "") ? "missing" : hintKind) + ", so the mission screen gives no heading or coordinates.");
					return null;
				}
				Vector3 globeCoords2 = FloatingOriginManager.instance.GetGlobeCoords(((Component)destinationPort).transform);
				int decimals = ScrambledSeas.Decimals;
				value.ApproxLat = Math.Round(globeCoords2.z, decimals);
				value.ApproxLon = Math.Round(globeCoords2.x, decimals);
				value.Decimals = decimals;
			}
			if (!ScrambledSeas.HidesDistance)
			{
				value.Miles = Mathf.RoundToInt(mission.distance * 100f / (0.514444f / Sun.sun.initialTimescale));
			}
			return value;
		}

		public static WorldInfo World()
		{
			return ScrambledSeas.World();
		}

		public static List<LoadedPlugin> Plugins()
		{
			List<LoadedPlugin> list = new List<LoadedPlugin>();
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				if (((value != null) ? value.Metadata : null) != null)
				{
					list.Add(new LoadedPlugin
					{
						Guid = value.Metadata.GUID,
						Name = value.Metadata.Name,
						Version = value.Metadata.Version?.ToString()
					});
				}
			}
			list.Sort((LoadedPlugin a, LoadedPlugin b) => string.CompareOrdinal(a.Guid, b.Guid));
			return list;
		}
	}
	internal struct Reading
	{
		public int Day;

		public double Hour;

		public double Lat;

		public double Lon;

		public string Event;

		public string Id;

		public string Boat;

		public double? Course;

		public double? Knots;

		public double? WindFrom;

		public double? WindKnots;

		public int? Hull;
	}
	internal struct PortVisit
	{
		public int Day;

		public double Hour;

		public string Port;

		public int Island;

		public double Lat;

		public double Lon;

		public double PortLat;

		public double PortLon;

		public double? OffsetLat;

		public double? OffsetLon;
	}
	internal struct PortDeparture
	{
		public int Day;

		public double Hour;

		public string Port;

		public int Island;
	}
	internal sealed class WorldInfo
	{
		public bool Scrambled;

		public int Seed;

		public int IslandSpread;

		public int MinArchipelagoSeparation;

		public int MinIslandSeparation;

		public int LonMin;

		public int LonMax;

		public int LatMin;

		public int LatMax;

		public int BorderExpander;

		public int Scrambler;

		public string ScrambledSeas;

		public string Layout;
	}
	internal struct RecorderKeys
	{
		public string Record;

		public string Location;

		public string Marker;
	}
	internal struct LoadedPlugin
	{
		public string Guid;

		public string Name;

		public string Version;
	}
	internal struct MissionHint
	{
		public int Day;

		public double Hour;

		public string Origin;

		public int OriginIsland;

		public double OriginLat;

		public double OriginLon;

		public string Destination;

		public int DestinationIsland;

		public double? Heading;

		public int? Points;

		public double? ApproxLat;

		public double? ApproxLon;

		public int? Decimals;

		public int? Miles;
	}
	internal static class LogFormat
	{
		private sealed class Line
		{
			private readonly StringBuilder text = new StringBuilder(200);

			private bool empty = true;

			public Line(string type)
			{
				text.Append("{\"type\":").Append(Quote(type));
				empty = false;
				Number("utc", (Now() - Epoch).TotalSeconds, 3);
			}

			public Line()
			{
				text.Append('{');
			}

			private StringBuilder Name(string name)
			{
				if (!empty)
				{
					text.Append(',');
				}
				empty = false;
				return text.Append('"').Append(name).Append("\":");
			}

			public Line Int(string name, int? value)
			{
				if (value.HasValue)
				{
					Name(name).Append(value.Value.ToString(Invariant));
				}
				return this;
			}

			public Line Number(string name, double? value, int decimals)
			{
				if (!value.HasValue)
				{
					return this;
				}
				double num = Math.Round(value.Value, decimals);
				if (num == 0.0)
				{
					num = 0.0;
				}
				Name(name).Append(num.ToString("0." + new string('#', decimals), Invariant));
				return this;
			}

			public Line Text(string name, string value)
			{
				if (!string.IsNullOrEmpty(value))
				{
					Name(name).Append(Quote(value));
				}
				return this;
			}

			public Line Object(string name, Line value)
			{
				Name(name).Append(value.Close());
				return this;
			}

			public Line Array(string name, IEnumerable<Line> values)
			{
				StringBuilder stringBuilder = Name(name).Append('[');
				bool flag = true;
				foreach (Line value in values)
				{
					if (!flag)
					{
						stringBuilder.Append(',');
					}
					flag = false;
					stringBuilder.Append(value.Close());
				}
				stringBuilder.Append(']');
				return this;
			}

			private string Close()
			{
				return text.Append('}').ToString();
			}

			public string End()
			{
				return text.Append("}\n").ToString();
			}
		}

		public const string Format = "voyage-recorder";

		public const int Version = 1;

		public const double KnotsPerMetrePerSecond = 1.944;

		public const int MaxNoteLength = 20000;

		private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;

		private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

		public static Func<DateTime> Now = () => DateTime.UtcNow;

		public static string Header(string modVersion, int slot)
		{
			return new Line("header").Text("format", "voyage-recorder").Int("version", 1).Text("mod", modVersion)
				.Int("slot", slot)
				.End();
		}

		public static string Session(int day, double hour, string game, WorldInfo world = null, IList<LoadedPlugin> plugins = null, RecorderKeys? keys = null)
		{
			Line line = new Line("session").Int("day", day).Number("hour", hour, 4).Text("game", game);
			if (keys.HasValue)
			{
				line.Object("keys", Keys(keys.Value));
			}
			if (world != null)
			{
				line.Object("world", World(world));
			}
			if (plugins != null)
			{
				List<Line> list = new List<Line>(plugins.Count);
				foreach (LoadedPlugin plugin in plugins)
				{
					list.Add(new Line().Text("guid", plugin.Guid).Text("name", plugin.Name).Text("version", plugin.Version));
				}
				line.Array("plugins", list);
			}
			return line.End();
		}

		public static string KeysChanged(RecorderKeys keys)
		{
			return new Line("keys").Object("keys", Keys(keys)).End();
		}

		private static Line Keys(RecorderKeys keys)
		{
			return new Line().Text("record", keys.Record).Text("location", keys.Location).Text("marker", keys.Marker);
		}

		private static Line World(WorldInfo world)
		{
			if (!world.Scrambled)
			{
				return new Line().Text("kind", "vanilla");
			}
			return new Line().Text("kind", "scrambled").Int("seed", world.Seed).Int("islandSpread", world.IslandSpread)
				.Int("minArchipelagoSeparation", world.MinArchipelagoSeparation)
				.Int("minIslandSeparation", world.MinIslandSeparation)
				.Int("lonMin", world.LonMin)
				.Int("lonMax", world.LonMax)
				.Int("latMin", world.LatMin)
				.Int("latMax", world.LatMax)
				.Int("borderExpander", world.BorderExpander)
				.Int("scrambler", world.Scrambler)
				.Text("scrambledSeas", world.ScrambledSeas)
				.Text("layout", world.Layout);
		}

		public static string Position(Reading reading)
		{
			return ReadingFields(new Line("position"), reading).End();
		}

		public static string Note(Reading reading, string id, string text)
		{
			string text2 = text ?? "";
			if (text2.Length > 20000)
			{
				text2 = text2.Substring(0, 20000);
			}
			reading.Id = id;
			return ReadingFields(new Line("note"), reading).Text("text", text2).End();
		}

		public static string Undo(string id)
		{
			return new Line("undo").Text("id", id).End();
		}

		private static Line ReadingFields(Line line, Reading reading)
		{
			return line.Text("id", reading.Id).Int("day", reading.Day).Number("hour", reading.Hour, 4)
				.Number("lat", reading.Lat, 7)
				.Number("lon", reading.Lon, 7)
				.Text("event", reading.Event)
				.Text("boat", reading.Boat)
				.Number("course", reading.Course, 1)
				.Number("knots", reading.Knots, 1)
				.Number("windFrom", reading.WindFrom, 1)
				.Number("windKnots", reading.WindKnots, 1)
				.Int("hull", reading.Hull);
		}

		public static string Port(PortVisit visit)
		{
			return new Line("port").Int("day", visit.Day).Number("hour", visit.Hour, 4).Text("port", visit.Port)
				.Int("island", visit.Island)
				.Number("lat", visit.Lat, 7)
				.Number("lon", visit.Lon, 7)
				.Number("portLat", visit.PortLat, 7)
				.Number("portLon", visit.PortLon, 7)
				.Number("offsetLat", visit.OffsetLat, 7)
				.Number("offsetLon", visit.OffsetLon, 7)
				.End();
		}

		public static string Depart(PortDeparture departure)
		{
			return new Line("depart").Int("day", departure.Day).Number("hour", departure.Hour, 4).Text("port", departure.Port)
				.Int("island", departure.Island)
				.End();
		}

		public static string Mission(MissionHint mission)
		{
			return new Line("mission").Int("day", mission.Day).Number("hour", mission.Hour, 4).Text("origin", mission.Origin)
				.Int("originIsland", mission.OriginIsland)
				.Number("originLat", mission.OriginLat, 7)
				.Number("originLon", mission.OriginLon, 7)
				.Text("destination", mission.Destination)
				.Int("destinationIsland", mission.DestinationIsland)
				.Number("heading", mission.Heading, 4)
				.Int("points", mission.Points)
				.Number("approxLat", mission.ApproxLat, 6)
				.Number("approxLon", mission.ApproxLon, 6)
				.Int("decimals", mission.Decimals)
				.Int("miles", mission.Miles)
				.End();
		}

		public static string LayoutFingerprint(IEnumerable<double> offsetsMetres)
		{
			ulong num = 14695981039346656037uL;
			foreach (double offsetsMetre in offsetsMetres)
			{
				long num2 = (long)Math.Round(offsetsMetre);
				for (int i = 0; i < 8; i++)
				{
					num ^= (byte)(num2 >> i * 8);
					num *= 1099511628211L;
				}
			}
			return num.ToString("x16", Invariant);
		}

		public static double Bearing(double east, double north)
		{
			double value = Math.Atan2(east, north) * 180.0 / Math.PI;
			value = Math.Round(value, 1);
			if (!(value < 0.0))
			{
				if (!(value >= 360.0))
				{
					return value;
				}
				return value - 360.0;
			}
			return value + 360.0;
		}

		public static string BoatName(string objectName)
		{
			string text = (objectName ?? "").Trim();
			if (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				text = text.Substring(0, text.Length - 7).TrimEnd(Array.Empty<char>());
			}
			if (text.EndsWith(")", StringComparison.Ordinal))
			{
				int num = text.LastIndexOf('(');
				if (num >= 0 && IsDigits(text, num + 1, text.Length - 1))
				{
					text = text.Substring(0, num).TrimEnd(Array.Empty<char>());
				}
			}
			if (text.StartsWith("BOAT ", StringComparison.Ordinal))
			{
				text = text.Substring(5).TrimStart(Array.Empty<char>());
			}
			return text;
		}

		public static double CompassHeading(double degrees, int points)
		{
			double num = 360.0 / (double)points;
			return (double)((int)Math.Round(degrees / num) % points) * num;
		}

		private static bool IsDigits(string text, int start, int end)
		{
			if (end <= start)
			{
				return false;
			}
			for (int i = start; i < end; i++)
			{
				if (text[i] < '0' || text[i] > '9')
				{
					return false;
				}
			}
			return true;
		}

		private static string Quote(string text)
		{
			StringBuilder stringBuilder = new StringBuilder(text.Length + 2).Append('"');
			foreach (char c in text)
			{
				if (c == '"' || c == '\\')
				{
					stringBuilder.Append('\\').Append(c);
				}
				else if (c < ' ')
				{
					StringBuilder stringBuilder2 = stringBuilder.Append("\\u");
					int num = c;
					stringBuilder2.Append(num.ToString("x4", Invariant));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.Append('"').ToString();
		}
	}
	internal sealed class MarkerMenu : MonoBehaviour
	{
		internal static readonly (string Event, string Label)[] Choices = new(string, string)[4]
		{
			("race-start", "Race start"),
			("race-checkpoint", "Race checkpoint"),
			("race-finish", "Race finish"),
			("note", "Write a note")
		};

		private const float Width = 300f;

		private const float ButtonHeight = 34f;

		private const float Gap = 8f;

		private bool closed;

		private Action<string> choose;

		private string undoLabel;

		private Rect window;

		public static MarkerMenu Open(MonoBehaviour owner, string undoLabel, Action<string> choose)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			MarkerMenu markerMenu = new GameObject("Voyage Recorder markers").AddComponent<MarkerMenu>();
			((Component)markerMenu).transform.SetParent(((Component)owner).transform, false);
			markerMenu.choose = choose;
			markerMenu.undoLabel = undoLabel;
			MouseLook.ToggleMouseLookAndCursor(false);
			return markerMenu;
		}

		public void Close()
		{
			if (!closed)
			{
				closed = true;
				MouseLook.ToggleMouseLookAndCursor(true);
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}

		private void Update()
		{
			if (!closed && Input.GetKeyDown((KeyCode)27))
			{
				Close();
			}
		}

		private void OnGUI()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!closed)
			{
				float num = (float)Screen.height / 1080f;
				GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f));
				float num2 = 28f + (float)(Choices.Length + ((undoLabel == null) ? 1 : 2)) * 42f + 8f;
				if (((Rect)(ref window)).width == 0f)
				{
					window = new Rect(((float)Screen.width / num - 300f) / 2f, (1080f - num2) / 2f, 300f, num2);
				}
				window = GUI.ModalWindow(((Object)this).GetInstanceID(), window, new WindowFunction(Draw), "Mark this location");
			}
		}

		private void Draw(int id)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			float num = 28f;
			(string, string)[] choices = Choices;
			for (int i = 0; i < choices.Length; i++)
			{
				(string, string) tuple = choices[i];
				if (GUI.Button(new Rect(12f, num, 276f, 34f), tuple.Item2))
				{
					Close();
					choose(tuple.Item1);
					return;
				}
				num += 42f;
			}
			if (undoLabel != null)
			{
				if (GUI.Button(new Rect(12f, num, 276f, 34f), "Undo " + undoLabel))
				{
					Close();
					choose("undo");
					return;
				}
				num += 42f;
			}
			if (GUI.Button(new Rect(12f, num, 276f, 34f), "Cancel"))
			{
				Close();
			}
			GUI.DragWindow(new Rect(0f, 0f, 300f, 24f));
		}
	}
	internal sealed class NoteBox : MonoBehaviour
	{
		private const string FieldName = "VoyageRecorderNote";

		private const float Width = 520f;

		private const float Height = 300f;

		private string text = "";

		private bool focused;

		private bool closed;

		private Func<string, bool> save;

		private Rect window;

		public static NoteBox Open(MonoBehaviour owner, Func<string, bool> save)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			NoteBox noteBox = new GameObject("Voyage Recorder note").AddComponent<NoteBox>();
			((Component)noteBox).transform.SetParent(((Component)owner).transform, false);
			noteBox.save = save;
			MouseLook.ToggleMouseLookAndCursor(false);
			return noteBox;
		}

		public void Close()
		{
			if (!closed)
			{
				closed = true;
				MouseLook.ToggleMouseLookAndCursor(true);
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}

		private void Update()
		{
			if (!closed && Input.GetKeyDown((KeyCode)27))
			{
				Close();
			}
		}

		private void OnGUI()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (!closed)
			{
				float num = (float)Screen.height / 1080f;
				GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f));
				float num2 = (float)Screen.width / num;
				if (((Rect)(ref window)).width == 0f)
				{
					window = new Rect((num2 - 520f) / 2f, 390f, 520f, 300f);
				}
				window = GUI.ModalWindow(((Object)this).GetInstanceID(), window, new WindowFunction(Draw), "Note");
			}
		}

		private void Draw(int id)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			GUI.SetNextControlName("VoyageRecorderNote");
			text = GUI.TextArea(new Rect(12f, 28f, 496f, 220f), text, 20000);
			if (!focused)
			{
				GUI.FocusControl("VoyageRecorderNote");
				focused = true;
			}
			if (GUI.Button(new Rect(308f, 258f, 96f, 30f), "Cancel"))
			{
				Close();
			}
			else if (GUI.Button(new Rect(412f, 258f, 96f, 30f), "Save") && (text.Trim().Length == 0 || save(text)))
			{
				Close();
			}
			GUI.DragWindow(new Rect(0f, 0f, 520f, 24f));
		}
	}
	[BepInPlugin("com.skeptic043.sailwind.voyagerecorder", "Voyage Recorder", "0.2.2")]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(MissionListUI), "DisplayMissions")]
		private static class MissionListPatch
		{
			private static void Postfix(Mission[] missions)
			{
				if ((Object)(object)instance != (Object)null)
				{
					instance.RecordMissions(missions);
				}
			}
		}

		[HarmonyPatch(typeof(SaveLoadManager), "LoadGame")]
		private static class LoadGamePatch
		{
			private static void Prefix()
			{
				ResetForNewSession();
			}

			private static void Postfix()
			{
				if (GameId == null)
				{
					NewGameId();
				}
			}
		}

		[HarmonyPatch(typeof(StartMenu), "StartNewGame")]
		private static class NewGamePatch
		{
			private static void Prefix()
			{
				ResetForNewSession();
				NewGameId();
			}
		}

		[HarmonyPatch(typeof(Sleep), "FallAsleep")]
		private static class FallAsleepPatch
		{
			private static void Postfix()
			{
				if (!((Object)(object)instance == (Object)null) && instance.recording)
				{
					if (instance.sleepReadings.Value)
					{
						instance.Record("sleep");
					}
					if (!instance.duringSleep.Value)
					{
						instance.StopTimer();
					}
					instance.UpdateDot();
				}
			}
		}

		[HarmonyPatch(typeof(Sleep), "WakeUp")]
		private static class WakeUpPatch
		{
			private static void Postfix()
			{
				if (!((Object)(object)instance == (Object)null) && instance.recording)
				{
					if (instance.sleepReadings.Value)
					{
						instance.Record("wake");
					}
					if (!instance.duringSleep.Value)
					{
						instance.StartTimer();
					}
					instance.UpdateDot();
				}
			}
		}

		public const string Id = "com.skeptic043.sailwind.voyagerecorder";

		public const string Version = "0.2.2";

		private static Plugin instance;

		private static ManualLogSource log;

		private ConfigEntry<KeyboardShortcut> recordKey;

		private ConfigEntry<KeyboardShortcut> locationKey;

		private ConfigEntry<KeyboardShortcut> markerKey;

		private ConfigEntry<int> interval;

		private ConfigEntry<bool> sleepReadings;

		private ConfigEntry<bool> duringSleep;

		private ConfigEntry<bool> onlyAboard;

		private ConfigEntry<bool> recordBoat;

		private ConfigEntry<bool> recordCourse;

		private ConfigEntry<bool> recordWind;

		private ConfigEntry<bool> recordHull;

		private ConfigEntry<bool> recordPorts;

		private ConfigEntry<bool> recordMissions;

		private ConfigEntry<bool> showDot;

		private ConfigEntry<DotCorner> dotCorner;

		private ConfigEntry<DotSize> dotSize;

		private bool recording;

		private bool sessionPending = true;

		private Coroutine timer;

		private RecordingDot dot;

		private bool writeFailed;

		private NoteBox noteBox;

		private MarkerMenu markerMenu;

		private (string Id, string Label, Vector3? Before)? lastMark;

		private Vector3? lastWritten;

		private Port atPort;

		private readonly HashSet<string> writtenMissions = new HashSet<string>();

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

		private const float PortReachMetres = 1500f;

		private const double StoppedKnots = 1.0;

		private const float StillMetres = 10f;

		private RecorderKeys Keys => new RecorderKeys
		{
			Record = ((object)recordKey.Value/*cast due to .constrained prefix*/).ToString(),
			Location = ((object)locationKey.Value/*cast due to .constrained prefix*/).ToString(),
			Marker = ((object)markerKey.Value/*cast due to .constrained prefix*/).ToString()
		};

		private static bool CanRead
		{
			get
			{
				if (GameState.playing)
				{
					return !GameState.currentlyLoading;
				}
				return false;
			}
		}

		private static string GameId
		{
			get
			{
				if (GameState.modData == null || !GameState.modData.TryGetValue("com.skeptic043.sailwind.voyagerecorder", out var value))
				{
					return null;
				}
				return value;
			}
		}

		private void Awake()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Expected O, but got Unknown
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Expected O, but got Unknown
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			instance = this;
			log = ((BaseUnityPlugin)this).Logger;
			recordKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "Record key", new KeyboardShortcut((KeyCode)106, Array.Empty<KeyCode>()), "Press to start or stop recording.");
			locationKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "Location key", new KeyboardShortcut((KeyCode)118, Array.Empty<KeyCode>()), "Press to record your location once, whether or not you're recording.");
			markerKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "Marker menu key", new KeyboardShortcut((KeyCode)118, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Press to mark a race start, checkpoint or finish, write a note about where you are, or undo your last mark, whether or not you're recording.");
			interval = ((BaseUnityPlugin)this).Config.Bind<int>("Recording", "Interval", 60, new ConfigDescription("Seconds between readings while recording, in game time.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 600), Array.Empty<object>()));
			sleepReadings = ((BaseUnityPlugin)this).Config.Bind<bool>("Recording", "Sleep and wake readings", true, "Take a reading when you fall asleep and when you wake up.");
			duringSleep = ((BaseUnityPlugin)this).Config.Bind<bool>("Recording", "Record during sleep", false, "Keep taking readings while you sleep.");
			onlyAboard = ((BaseUnityPlugin)this).Config.Bind<bool>("Recording", "Only while aboard", false, "Skip readings while you are not aboard a boat.");
			recordBoat = ((BaseUnityPlugin)this).Config.Bind<bool>("Details", "Boat", true, "Record which boat you are aboard.");
			recordCourse = ((BaseUnityPlugin)this).Config.Bind<bool>("Details", "Course and speed", true, "Record the boat's course and speed.");
			recordWind = ((BaseUnityPlugin)this).Config.Bind<bool>("Details", "Wind", true, "Record the wind's direction and strength.");
			recordHull = ((BaseUnityPlugin)this).Config.Bind<bool>("Details", "Hull damage", true, "Record the hull damage of the boat you're aboard, in percent.");
			recordPorts = ((BaseUnityPlugin)this).Config.Bind<bool>("Details", "Port visits", true, "Record each port you stop at.");
			recordMissions = ((BaseUnityPlugin)this).Config.Bind<bool>("Details", "Missions", true, "Record the missions you see in your mission book or on a port's mission board, with the heading or coordinates Scrambled Seas shows, so Chartroom can draw search areas. Needs Scrambled Seas giving a destination hint.");
			showDot = ((BaseUnityPlugin)this).Config.Bind<bool>("Recording dot", "Show", false, new ConfigDescription("Show a flashing red dot in a corner of the screen while recording.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 3
				}
			}));
			dotCorner = ((BaseUnityPlugin)this).Config.Bind<DotCorner>("Recording dot", "Corner", DotCorner.TopRight, new ConfigDescription("The corner the dot sits in.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 2
				}
			}));
			dotSize = ((BaseUnityPlugin)this).Config.Bind<DotSize>("Recording dot", "Size", DotSize.Small, new ConfigDescription("How big the dot is.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 1
				}
			}));
			recordKey.SettingChanged += delegate
			{
				KeysChanged();
			};
			locationKey.SettingChanged += delegate
			{
				KeysChanged();
			};
			markerKey.SettingChanged += delegate
			{
				KeysChanged();
			};
			showDot.SettingChanged += delegate
			{
				UpdateDot();
			};
			dotCorner.SettingChanged += delegate
			{
				UpdateDot();
			};
			dotSize.SettingChanged += delegate
			{
				UpdateDot();
			};
			interval.SettingChanged += delegate
			{
				StartTimer();
			};
			duringSleep.SettingChanged += delegate
			{
				if (GameState.sleeping)
				{
					StartTimer();
				}
			};
			new Harmony("com.skeptic043.sailwind.voyagerecorder").PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Voyage Recorder loaded.");
		}

		private void Update()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!Input.anyKeyDown)
			{
				return;
			}
			bool flag = Pressed(recordKey.Value);
			bool flag2 = Pressed(locationKey.Value);
			bool flag3 = Pressed(markerKey.Value);
			if (flag3)
			{
				flag2 = false;
			}
			if ((!flag && !flag2 && !flag3) || (Object)(object)noteBox != (Object)null || (Object)(object)markerMenu != (Object)null || !GameState.playing || GameState.inCursorMenu)
			{
				return;
			}
			if (flag)
			{
				if (recording)
				{
					StopRecording();
				}
				else
				{
					StartRecording();
				}
			}
			if (flag2)
			{
				RecordLocation();
			}
			if (flag3)
			{
				OpenMarkerMenu();
			}
		}

		private void KeysChanged()
		{
			if (sessionPending || !CanRead)
			{
				return;
			}
			try
			{
				Write(LogFormat.KeysChanged(Keys), GameState.day, Sun.sun.globalTime);
			}
			catch (Exception exception)
			{
				ReadingFailed(exception);
			}
		}

		private static bool Pressed(KeyboardShortcut key)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if ((int)((KeyboardShortcut)(ref key)).MainKey == 0 || !Input.GetKeyDown(((KeyboardShortcut)(ref key)).MainKey))
			{
				return false;
			}
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref key)).Modifiers)
			{
				if (!Input.GetKey(modifier))
				{
					return false;
				}
			}
			return true;
		}

		private void RecordLocation()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (!CanRead)
			{
				return;
			}
			try
			{
				WriteMark("mark", "Location", GameState.currentBoat, PlayerGlobe());
				Notify("Location recorded");
			}
			catch (Exception exception)
			{
				ReadingFailed(exception);
			}
		}

		private void OpenMarkerMenu()
		{
			if (!CanRead || (Object)(object)markerMenu != (Object)null)
			{
				return;
			}
			markerMenu = MarkerMenu.Open((MonoBehaviour)(object)this, lastMark?.Label.ToLowerInvariant(), delegate(string choice)
			{
				//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
				markerMenu = null;
				if (choice == "note")
				{
					OpenNote();
				}
				else if (CanRead)
				{
					try
					{
						if (choice == "undo")
						{
							if (lastMark.HasValue)
							{
								Write(LogFormat.Undo(lastMark.Value.Id), GameState.day, Sun.sun.globalTime);
								Notify(lastMark.Value.Label + " removed");
								lastWritten = lastMark.Value.Before;
								lastMark = null;
							}
						}
						else
						{
							(string, string)[] choices = MarkerMenu.Choices;
							for (int i = 0; i < choices.Length; i++)
							{
								(string, string) tuple = choices[i];
								if (!(tuple.Item1 != choice))
								{
									WriteMark(choice, tuple.Item2, GameState.currentBoat, PlayerGlobe());
									Notify(tuple.Item2 + " recorded");
								}
							}
						}
					}
					catch (Exception exception)
					{
						ReadingFailed(exception);
					}
				}
			});
		}

		private void OpenNote()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (!CanRead || (Object)(object)noteBox != (Object)null)
			{
				return;
			}
			try
			{
				Reading reading = TakeReading(null, GameState.currentBoat, PlayerGlobe());
				noteBox = NoteBox.Open((MonoBehaviour)(object)this, (string text) => WriteNote(reading, text));
			}
			catch (Exception exception)
			{
				ReadingFailed(exception);
			}
		}

		private bool WriteNote(Reading reading, string text)
		{
			try
			{
				string id = Guid.NewGuid().ToString("N").Substring(0, 12);
				Write(LogFormat.Note(reading, id, text), reading.Day, reading.Hour);
				Notify("Note saved");
				return true;
			}
			catch (Exception exception)
			{
				ReadingFailed(exception);
				return false;
			}
		}

		private void StartRecording()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)atPort != (Object)null && Vector3.Distance(((Component)atPort).transform.position, ((Component)Refs.observerMirror).transform.position) > 1500f)
			{
				atPort = null;
			}
			recording = true;
			Record("start");
			StartTimer();
			UpdateDot();
			Notify("Recording");
		}

		private void StopRecording()
		{
			Record("stop");
			recording = false;
			StopTimer();
			UpdateDot();
			Notify("Stopped recording");
		}

		private void StartTimer()
		{
			StopTimer();
			if (recording && (!GameState.sleeping || duringSleep.Value))
			{
				timer = ((MonoBehaviour)this).StartCoroutine(Readings(interval.Value));
			}
		}

		private void StopTimer()
		{
			if (timer != null)
			{
				((MonoBehaviour)this).StopCoroutine(timer);
			}
			timer = null;
		}

		private IEnumerator Readings(int seconds)
		{
			WaitForSeconds wait = new WaitForSeconds((float)seconds);
			while (true)
			{
				yield return wait;
				Record(null);
			}
		}

		private void UpdateDot()
		{
			if (recording && showDot.Value)
			{
				(dot ?? (dot = new RecordingDot((MonoBehaviour)(object)this))).Show(dotCorner.Value, dotSize.Value);
			}
			else
			{
				dot?.Hide();
			}
		}

		private static void Notify(string text)
		{
			if ((Object)(object)NotificationUi.instance != (Object)null)
			{
				NotificationUi.instance.ShowNotification(text);
			}
		}

		private void Record(string eventName)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if (!recording || !CanRead)
			{
				return;
			}
			try
			{
				Transform currentBoat = GameState.currentBoat;
				Vector3 val = PlayerGlobe();
				if ((eventName != null || !lastWritten.HasValue || !(GlobeMetres(lastWritten.Value, val) < 10f)) && ((Object)(object)currentBoat != (Object)null || !onlyAboard.Value))
				{
					WritePosition(eventName, currentBoat, val);
				}
				if (recordPorts.Value)
				{
					RecordPort(currentBoat);
				}
			}
			catch (Exception exception)
			{
				ReadingFailed(exception);
			}
		}

		private void ReadingFailed(Exception exception)
		{
			if (!writeFailed)
			{
				log.LogError((object)("Voyage Recorder could not take a reading: " + exception));
			}
			writeFailed = true;
		}

		private static Vector3 PlayerGlobe()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			return FloatingOriginManager.instance.GetGlobeCoords(((Component)Refs.observerMirror).transform);
		}

		private static float GlobeMetres(Vector3 a, Vector3 b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = new Vector2(a.x - b.x, a.z - b.z);
			return ((Vector2)(ref val)).magnitude * 9000f;
		}

		private static Transform BoatRoot(Transform boat)
		{
			if (!((Object)(object)boat.parent != (Object)null))
			{
				return boat;
			}
			return boat.parent;
		}

		private static double Knots(Vector3 velocity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = new Vector2(velocity.x, velocity.z);
			return (double)((Vector2)(ref val)).magnitude * 1.944;
		}

		private void WriteMark(string eventName, string label, Transform boat, Vector3 globe)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Reading reading = TakeReading(eventName, boat, globe);
			reading.Id = Guid.NewGuid().ToString("N").Substring(0, 12);
			Vector3? item = lastWritten;
			Write(LogFormat.Position(reading), reading.Day, reading.Hour);
			lastWritten = globe;
			lastMark = (reading.Id, label, item);
		}

		private void WritePosition(string eventName, Transform boat, Vector3 globe)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Reading reading = TakeReading(eventName, boat, globe);
			Write(LogFormat.Position(reading), reading.Day, reading.Hour);
			lastWritten = globe;
		}

		private Reading TakeReading(string eventName, Transform boat, Vector3 globe)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			Reading result = new Reading
			{
				Day = GameState.day,
				Hour = Sun.sun.globalTime,
				Lat = globe.z,
				Lon = globe.x,
				Event = eventName
			};
			if ((Object)(object)boat != (Object)null)
			{
				Transform val = BoatRoot(boat);
				if (recordBoat.Value)
				{
					result.Boat = LogFormat.BoatName(((Object)val).name);
				}
				Rigidbody component = ((Component)val).GetComponent<Rigidbody>();
				if (recordCourse.Value && (Object)(object)component != (Object)null)
				{
					Vector3 velocity = component.velocity;
					double num = Knots(velocity);
					result.Knots = num;
					if (num >= 0.1)
					{
						result.Course = LogFormat.Bearing(velocity.x, velocity.z);
					}
				}
				BoatDamage component2 = ((Component)val).GetComponent<BoatDamage>();
				if (recordHull.Value && (Object)(object)component2 != (Object)null)
				{
					result.Hull = Mathf.RoundToInt(component2.hullDamage * 100f);
				}
			}
			if (recordWind.Value)
			{
				Vector3 currentWind = Wind.currentWind;
				result.WindKnots = Knots(currentWind);
				result.WindFrom = LogFormat.Bearing(0f - currentWind.x, 0f - currentWind.z);
			}
			return result;
		}

		private void RecordPort(Transform boat)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			int day = GameState.day;
			double hour = Sun.sun.globalTime;
			if ((Object)(object)atPort != (Object)null)
			{
				if (Vector3.Distance(((Component)atPort).transform.position, ((Component)Refs.observerMirror).transform.position) <= 1500f)
				{
					return;
				}
				Write(LogFormat.Depart(new PortDeparture
				{
					Day = day,
					Hour = hour,
					Port = atPort.GetPortName(),
					Island = Discoveries.IslandOf(atPort)
				}), day, hour);
				atPort = null;
			}
			Port lastVisitedPort = GameState.lastVisitedPort;
			if (!((Object)(object)lastVisitedPort == (Object)null))
			{
				Rigidbody val = (((Object)(object)boat == (Object)null) ? null : ((Component)BoatRoot(boat)).GetComponent<Rigidbody>());
				if ((!((Object)(object)val != (Object)null) || !(Knots(val.velocity) >= 1.0)) && !(Vector3.Distance(((Component)lastVisitedPort).transform.position, ((Component)Refs.observerMirror).transform.position) > 1500f))
				{
					Write(LogFormat.Port(Discoveries.Visit(lastVisitedPort, day, hour)), day, hour);
					atPort = lastVisitedPort;
				}
			}
		}

		private void RecordMissions(Mission[] missions)
		{
			try
			{
				if (!recordMissions.Value || !GameState.playing || missions == null)
				{
					return;
				}
				int day = GameState.day;
				double hour = Sun.sun.globalTime;
				int num = 0;
				foreach (Mission val in missions)
				{
					if ((Object)(object)val?.originPort == (Object)null || (Object)(object)val.destinationPort == (Object)null)
					{
						continue;
					}
					string item = val.originPort.portIndex + ">" + val.destinationPort.portIndex;
					if (!writtenMissions.Contains(item))
					{
						MissionHint? missionHint = Discoveries.Hint(val, day, hour);
						if (missionHint.HasValue)
						{
							Write(LogFormat.Mission(missionHint.Value), day, hour);
							writtenMissions.Add(item);
							num++;
						}
					}
				}
				if (num > 0)
				{
					log.LogInfo((object)string.Format("Voyage Recorder noted {0} mission{1}.", num, (num == 1) ? "" : "s"));
				}
			}
			catch (Exception ex)
			{
				LogOnce("Voyage Recorder could not record missions: " + ex);
			}
		}

		internal static void LogOnce(string message)
		{
			if (logged.Add(message))
			{
				log.LogWarning((object)message);
			}
		}

		private void Write(string line, int day, double hour)
		{
			string text = Path.Combine(Application.persistentDataPath, "Voyage Recorder");
			string path = Path.Combine(text, "slot" + SaveSlots.currentSlot + ".jsonl");
			string text2 = "";
			if (!File.Exists(path))
			{
				Directory.CreateDirectory(text);
				text2 += LogFormat.Header("0.2.2", SaveSlots.currentSlot);
			}
			if (sessionPending)
			{
				text2 += LogFormat.Session(day, hour, GameId, Optional(Discoveries.World, "the world"), Optional(Discoveries.Plugins, "the loaded mods"), Keys);
			}
			text2 += line;
			File.AppendAllText(path, text2);
			sessionPending = false;
			writeFailed = false;
		}

		private static T Optional<T>(Func<T> read, string what) where T : class
		{
			try
			{
				return read();
			}
			catch (Exception arg)
			{
				LogOnce($"Voyage Recorder could not read {what}: {arg}");
				return null;
			}
		}

		private static void ResetForNewSession()
		{
			if (!((Object)(object)instance == (Object)null))
			{
				instance.recording = false;
				instance.StopTimer();
				instance.UpdateDot();
				instance.sessionPending = true;
				instance.lastWritten = null;
				instance.atPort = null;
				if ((Object)(object)instance.noteBox != (Object)null)
				{
					instance.noteBox.Close();
				}
				instance.noteBox = null;
				if ((Object)(object)instance.markerMenu != (Object)null)
				{
					instance.markerMenu.Close();
				}
				instance.markerMenu = null;
				instance.lastMark = null;
				instance.writtenMissions.Clear();
			}
		}

		private static void NewGameId()
		{
			if (GameState.modData != null)
			{
				GameState.modData["com.skeptic043.sailwind.voyagerecorder"] = Guid.NewGuid().ToString("N").Substring(0, 12);
			}
		}
	}
	internal enum DotCorner
	{
		TopLeft,
		TopRight,
		BottomLeft,
		BottomRight
	}
	internal enum DotSize
	{
		Small,
		Large
	}
	internal sealed class RecordingDot
	{
		private const float ReferenceHeight = 1080f;

		private const float Margin = 24f;

		private static readonly Color Red = new Color(0.85f, 0.1f, 0.1f, 0.9f);

		private const float OnSeconds = 1f;

		private const float OffSeconds = 0.5f;

		private readonly MonoBehaviour owner;

		private readonly GameObject canvas;

		private readonly RectTransform dot;

		private readonly Image picture;

		private Coroutine flashing;

		public RecordingDot(MonoBehaviour owner)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			this.owner = owner;
			canvas = new GameObject("Voyage Recorder dot", new Type[2]
			{
				typeof(Canvas),
				typeof(CanvasScaler)
			});
			canvas.transform.SetParent(((Component)owner).transform, false);
			Canvas component = canvas.GetComponent<Canvas>();
			component.renderMode = (RenderMode)0;
			component.sortingOrder = 32767;
			CanvasScaler component2 = canvas.GetComponent<CanvasScaler>();
			component2.uiScaleMode = (ScaleMode)1;
			component2.referenceResolution = new Vector2(1920f, 1080f);
			component2.matchWidthOrHeight = 1f;
			GameObject val = new GameObject("dot", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent(canvas.transform, false);
			picture = val.GetComponent<Image>();
			picture.sprite = Circle();
			((Graphic)picture).color = Red;
			((Graphic)picture).raycastTarget = false;
			dot = val.GetComponent<RectTransform>();
			canvas.SetActive(false);
		}

		public void Show(DotCorner corner, DotSize size)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			float num = ((corner == DotCorner.TopLeft || corner == DotCorner.BottomLeft) ? 0f : 1f);
			float num2 = ((corner == DotCorner.BottomLeft || corner == DotCorner.BottomRight) ? 0f : 1f);
			RectTransform obj = dot;
			RectTransform obj2 = dot;
			RectTransform obj3 = dot;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(num, num2);
			obj3.pivot = val;
			Vector2 anchorMin = (obj2.anchorMax = val);
			obj.anchorMin = anchorMin;
			dot.anchoredPosition = new Vector2((num == 0f) ? 24f : (-24f), (num2 == 0f) ? 24f : (-24f));
			float num3 = ((size == DotSize.Large) ? 32f : 16f);
			dot.sizeDelta = new Vector2(num3, num3);
			canvas.SetActive(true);
			if (flashing != null)
			{
				owner.StopCoroutine(flashing);
			}
			flashing = owner.StartCoroutine(Flash());
		}

		public void Hide()
		{
			if (flashing != null)
			{
				owner.StopCoroutine(flashing);
			}
			flashing = null;
			canvas.SetActive(false);
		}

		private IEnumerator Flash()
		{
			while (true)
			{
				((Behaviour)picture).enabled = true;
				yield return (object)new WaitForSeconds(1f * Mathf.Max(Time.timeScale, 1f));
				((Behaviour)picture).enabled = false;
				yield return (object)new WaitForSeconds(0.5f * Mathf.Max(Time.timeScale, 1f));
			}
		}

		private static Sprite Circle()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(64, 64, (TextureFormat)5, false)
			{
				wrapMode = (TextureWrapMode)1
			};
			Color32[] array = (Color32[])(object)new Color32[4096];
			float num = 32f;
			for (int i = 0; i < 64; i++)
			{
				for (int j = 0; j < 64; j++)
				{
					Vector2 val2 = new Vector2((float)j + 0.5f - num, (float)i + 0.5f - num);
					float magnitude = ((Vector2)(ref val2)).magnitude;
					byte b = (byte)(Mathf.Clamp01(num - magnitude) * 255f);
					array[i * 64 + j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, b);
				}
			}
			val.SetPixels32(array);
			val.Apply(false, true);
			return Sprite.Create(val, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f));
		}
	}
}