Decompiled source of SimpleRoadMap v0.5.3

BepInEx/plugins/SimpleRoadMap/SimpleRoadMap.dll

Decompiled 10 hours ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.GUI;
using Jotunn.Managers;
using Jotunn.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace SimpleRoadMap;

[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("cz.misaw.simpleroadmap", "Simple Road Map", "0.5.3")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "cz.misaw.simpleroadmap";

	internal static Plugin Instance;

	private Harmony harmony;

	private RoadData data;

	private readonly RoadRecorder recorder = new RoadRecorder();

	private string file;

	private bool writable;

	private bool unsaved;

	private float lastBuild;

	private float nextSave;

	private ConfigEntry<bool> visible;

	private ConfigEntry<bool> showDirt;

	private ConfigEntry<bool> showPaved;

	private MapOverlay dirtFilter;

	private MapOverlay pavedFilter;

	private MapOverlay eraserFilter;

	private Minimap filterMap;

	private ConfigEntry<float> dash;

	private ConfigEntry<float> gap;

	private ConfigEntry<float> width;

	private ConfigEntry<float> connection;

	private ConfigEntry<float> proximity;

	private ConfigEntry<Color> paved;

	private ConfigEntry<Color> dirt;

	private RoadGraphic large;

	private RoadGraphic small;

	private RoadEditor editor;

	private ConfigEntry<float> eraserRadius;

	private string eraseStroke;

	private string undoStroke;

	private bool strokeChanged;

	private RoadEraseIndex eraseIndex;

	private int eraseIndexRevision = -1;

	private RoadNetwork network;

	private int networkRevision = -1;

	private readonly TableSharing sharing = new TableSharing();

	private int geometryRevision;

	public RoadData Data => data;

	public int Revision { get; private set; }

	public bool RoadsVisible => visible.Value;

	public float StrokeWidth => width.Value;

	public float DashLength => dash.Value;

	public float GapLength => gap.Value;

	internal MapOverlay EraserControl => eraserFilter;

	public bool CanEdit
	{
		get
		{
			if (writable && data != null)
			{
				return RoadsVisible;
			}
			return false;
		}
	}

	public bool CanUndoErase
	{
		get
		{
			if (writable && data != null)
			{
				return undoStroke != null;
			}
			return false;
		}
	}

	public float EraserRadius
	{
		get
		{
			return eraserRadius.Value;
		}
		set
		{
			eraserRadius.Value = Mathf.Clamp(value, 4f, 100f);
		}
	}

	public RoadEraseIndex EraseIndex
	{
		get
		{
			if (eraseIndex == null || eraseIndexRevision != geometryRevision)
			{
				eraseIndex = new RoadEraseIndex(data);
				eraseIndexRevision = geometryRevision;
			}
			return eraseIndex;
		}
	}

	public RoadNetwork Network
	{
		get
		{
			if (network == null || networkRevision != geometryRevision)
			{
				network = new RoadNetwork(data, proximity.Value);
				networkRevision = geometryRevision;
			}
			return network;
		}
	}

	private void RoadsChanged()
	{
		geometryRevision++;
		Revision++;
	}

	public Color RoadColor(int kind)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		if (kind != 1)
		{
			return dirt.Value;
		}
		return paved.Value;
	}

	public bool RoadVisible(int kind)
	{
		if (kind != 1)
		{
			return showDirt.Value;
		}
		return showPaved.Value;
	}

	private void Awake()
	{
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Expected O, but got Unknown
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Expected O, but got Unknown
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Expected O, but got Unknown
		//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Expected O, but got Unknown
		//IL_0235: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Expected O, but got Unknown
		//IL_028b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0295: Expected O, but got Unknown
		//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Expected O, but got Unknown
		Instance = this;
		visible = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "Visible", true, "Show recorded roads on both maps.");
		showDirt = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "ShowDirtRoads", true, "Show dirt paths; also controlled by the map layer toggle.");
		showPaved = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "ShowPavedRoads", true, "Show paved roads; also controlled by the map layer toggle.");
		showDirt.SettingChanged += delegate
		{
			if (dirtFilter != null && (Object)(object)filterMap != (Object)null)
			{
				dirtFilter.Enabled = showDirt.Value;
			}
		};
		showPaved.SettingChanged += delegate
		{
			if (pavedFilter != null && (Object)(object)filterMap != (Object)null)
			{
				pavedFilter.Enabled = showPaved.Value;
			}
		};
		paved = ((BaseUnityPlugin)this).Config.Bind<Color>("Map", "PavedColor", new Color(1f, 0.84f, 0.2f, 1f), "Paved road color.");
		dirt = ((BaseUnityPlugin)this).Config.Bind<Color>("Map", "DirtColor", new Color(0.57f, 0.31f, 0.12f, 1f), "Dirt path color.");
		width = ((BaseUnityPlugin)this).Config.Bind<float>("Curves", "WidthScreenPixels", 1.25f, new ConfigDescription("Curve width in screen pixels, independent of map zoom.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 5f), new object[0]));
		dash = ((BaseUnityPlugin)this).Config.Bind<float>("Curves", "DashScreenPixels", 6f, new ConfigDescription("Dash length in screen pixels.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), new object[0]));
		gap = ((BaseUnityPlugin)this).Config.Bind<float>("Curves", "GapScreenPixels", 4f, new ConfigDescription("Gap length in screen pixels.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), new object[0]));
		connection = ((BaseUnityPlugin)this).Config.Bind<float>("Recording", "MaxConnectionMetres", 6f, new ConfigDescription("Maximum distance between consecutive road placements to connect.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 12f), new object[0]));
		proximity = ((BaseUnityPlugin)this).Config.Bind<float>("Recording", "MergeRadiusMetres", 3f, new ConfigDescription("Road placements near an existing route update that route instead of drawing a parallel line.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 6f), new object[0]));
		proximity.SettingChanged += delegate
		{
			geometryRevision++;
		};
		eraserRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Editing", "EraserRadiusScreenPixels", 20f, new ConfigDescription("Map eraser radius in screen pixels; adjusted with the slider under the eraser toggle.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 100f), new object[0]));
		((BaseUnityPlugin)this).Config.SettingChanged += delegate
		{
			Revision++;
		};
		MinimapManager.OnVanillaMapAvailable += RegisterRoadFilters;
		harmony = new Harmony("cz.misaw.simpleroadmap");
		harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Simple Road Map 0.5.3 loaded: cached route geometry and viewport-only rendering.");
	}

	private void RegisterRoadFilters()
	{
		filterMap = Minimap.instance;
		dirtFilter = MinimapManager.Instance.GetMapOverlay("Prašné cesty", false);
		pavedFilter = MinimapManager.Instance.GetMapOverlay("Dlážděné cesty", false);
		eraserFilter = MinimapManager.Instance.GetMapOverlay("Guma – mazat cesty", false);
		dirtFilter.Enabled = showDirt.Value;
		pavedFilter.Enabled = showPaved.Value;
		eraserFilter.Enabled = false;
		Revision++;
	}

	private void ReadRoadFilters()
	{
		if (!((Object)(object)filterMap == (Object)null) && !((Object)(object)filterMap != (Object)(object)Minimap.instance))
		{
			if (dirtFilter != null && dirtFilter.Enabled != showDirt.Value)
			{
				showDirt.Value = dirtFilter.Enabled;
			}
			if (pavedFilter != null && pavedFilter.Enabled != showPaved.Value)
			{
				showPaved.Value = pavedFilter.Enabled;
			}
			if (eraserFilter != null && (Object)(object)editor != (Object)null && eraserFilter.Enabled != editor.Editing)
			{
				editor.SetEditing(eraserFilter.Enabled);
			}
		}
	}

	internal void SyncEraserFilter(bool enabled)
	{
		if (eraserFilter != null && (Object)(object)filterMap != (Object)null)
		{
			eraserFilter.Enabled = enabled;
		}
	}

	private void Update()
	{
		sharing.Tick();
		if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null)
		{
			if (data != null)
			{
				Save();
				if (!unsaved)
				{
					data = null;
					recorder.Reset();
					eraseStroke = (undoStroke = null);
					RoadsChanged();
				}
			}
			return;
		}
		long worldUID = ZNet.instance.GetWorldUID();
		if (data == null || data.world != worldUID)
		{
			Load(worldUID);
		}
		ReadRoadFilters();
		if ((Object)(object)Minimap.instance != (Object)null)
		{
			if ((Object)(object)large == (Object)null && (Object)(object)Minimap.instance.m_mapImageLarge != (Object)null)
			{
				large = RoadGraphic.Create(Minimap.instance.m_mapImageLarge, circular: false);
			}
			if ((Object)(object)small == (Object)null && (Object)(object)Minimap.instance.m_mapImageSmall != (Object)null)
			{
				small = RoadGraphic.Create(Minimap.instance.m_mapImageSmall, circular: true);
			}
			if ((Object)(object)editor == (Object)null && (Object)(object)large != (Object)null && (Object)(object)Minimap.instance.m_largeRoot != (Object)null)
			{
				editor = RoadEditor.Create(Minimap.instance, large);
			}
		}
		if (writable && unsaved && Time.unscaledTime >= nextSave)
		{
			Save();
		}
	}

	private void Load(long world)
	{
		EndEraseStroke();
		if (data != null)
		{
			Save();
			if (unsaved)
			{
				return;
			}
		}
		recorder.Reset();
		eraseStroke = (undoStroke = null);
		unsaved = false;
		file = Path.Combine(Path.Combine(Paths.ConfigPath, "SimpleRoadMap"), world.ToString(CultureInfo.InvariantCulture) + ".json");
		writable = true;
		data = new RoadData
		{
			world = world
		};
		try
		{
			if (File.Exists(file))
			{
				bool legacy;
				try
				{
					data = RoadStore.Read(file, world, out legacy);
					if (legacy)
					{
						bool legacy2 = true;
						RoadData roadData = null;
						try
						{
							if (File.Exists(file + ".bak"))
							{
								roadData = RoadStore.Read(file + ".bak", world, out legacy2);
							}
						}
						catch (Exception)
						{
						}
						if (roadData != null && !legacy2)
						{
							data = roadData;
							unsaved = true;
						}
						else
						{
							((BaseUnityPlugin)this).Logger.LogWarning((object)"Legacy road file contains only world metadata, no recorded points. New roads will now save correctly.");
						}
						if (!File.Exists(file + ".legacy"))
						{
							File.Copy(file, file + ".legacy");
						}
					}
				}
				catch (Exception ex2)
				{
					if (!File.Exists(file + ".bak"))
					{
						throw;
					}
					data = RoadStore.Read(file + ".bak", world, out legacy);
					if (legacy)
					{
						throw new InvalidDataException("Backup has no recorded points.", ex2);
					}
					File.Copy(file, file + ".corrupt-" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture));
					unsaved = true;
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Recovered roads from backup: " + ex2.Message));
				}
				int num = 0;
				foreach (RoadLine line in data.lines)
				{
					num += line.points.Count;
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded " + num + " road points from " + file));
			}
		}
		catch (Exception ex3)
		{
			writable = false;
			((BaseUnityPlugin)this).Logger.LogError((object)("Road file could not be loaded; recording disabled to protect it: " + ex3.Message));
		}
		RoadsChanged();
		nextSave = Time.unscaledTime + 5f;
		if (writable && RoadMerge.EnsureIds(data))
		{
			unsaved = true;
			Save();
		}
	}

	internal void ShareAtTable(MapTable table, bool write)
	{
		sharing.Use(table, write);
	}

	internal RoadData RoadsForSharing(long world)
	{
		EndEraseStroke();
		if (data == null || data.world != world)
		{
			Load(world);
		}
		if (!writable || data == null || data.world != world)
		{
			return null;
		}
		if (RoadMerge.EnsureIds(data))
		{
			unsaved = true;
		}
		Save();
		return data;
	}

	internal int AcceptSharedRoads(RoadData incoming)
	{
		EndEraseStroke();
		if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.GetWorldUID() != incoming.world)
		{
			throw new InvalidDataException("World changed while reading table.");
		}
		if (data == null || data.world != incoming.world)
		{
			Load(incoming.world);
		}
		if (!writable || data == null || data.world != incoming.world)
		{
			throw new IOException("Local road file is unavailable.");
		}
		int addedPoints;
		RoadData roadData = RoadMerge.Merge(data, incoming, out addedPoints);
		RoadStore.Save(file, roadData);
		data = roadData;
		recorder.Reset();
		unsaved = false;
		RoadsChanged();
		return addedPoints;
	}

	internal void BeginEraseStroke()
	{
		EndEraseStroke();
		if (CanEdit)
		{
			eraseStroke = System.Guid.NewGuid().ToString("N");
			strokeChanged = false;
			recorder.Reset();
		}
	}

	internal void EraseAt(RoadPoint point, float radius, RoadGraphic graphic)
	{
		if (CanEdit && eraseStroke != null && RoadEditing.Erase(data, eraseStroke, point, radius, graphic.ProjectForEditing, (int kind) => RoadsVisible && RoadVisible(kind), graphic.ExploredForEditing, Network))
		{
			strokeChanged = true;
			unsaved = true;
			RoadsChanged();
		}
	}

	internal void EndEraseStroke()
	{
		if (eraseStroke != null)
		{
			if (strokeChanged)
			{
				RoadEditing.CompactUnpublishedStroke(data, eraseStroke);
				RoadsChanged();
				undoStroke = eraseStroke;
				Save();
			}
			eraseStroke = null;
			strokeChanged = false;
		}
	}

	internal void UndoErase()
	{
		EndEraseStroke();
		if (CanUndoErase)
		{
			if (RoadEditing.Undo(data, undoStroke) > 0)
			{
				unsaved = true;
				RoadsChanged();
				Save();
			}
			undoStroke = null;
		}
	}

	internal void Save()
	{
		nextSave = Time.unscaledTime + 5f;
		if (!writable || !unsaved || data == null || file == null)
		{
			return;
		}
		try
		{
			RoadStore.Save(file, data);
			unsaved = false;
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not save roads: " + ex.Message));
		}
	}

	internal void Record(Piece piece, Vector3 position)
	{
		if ((Object)(object)piece == (Object)null || (Object)(object)ZNet.instance == (Object)null)
		{
			return;
		}
		int kind;
		switch (((Object)((Component)piece).gameObject).name.Replace("(Clone)", ""))
		{
		default:
			return;
		case "path":
		case "path_v2":
			kind = 0;
			break;
		case "paved_road":
		case "paved_road_v2":
			kind = 1;
			break;
		}
		long worldUID = ZNet.instance.GetWorldUID();
		if (data == null || data.world != worldUID)
		{
			Load(worldUID);
		}
		if (writable && data != null && data.world == worldUID)
		{
			if (Time.unscaledTime - lastBuild > 30f)
			{
				recorder.Reset();
			}
			bool flag = recorder.Record(data, new RoadPoint(position.x, position.z), kind, connection.Value, proximity.Value, Network);
			lastBuild = Time.unscaledTime;
			if (flag)
			{
				RoadsChanged();
				unsaved = true;
				Save();
			}
		}
	}

	private void OnApplicationQuit()
	{
		Save();
	}

	private void OnDestroy()
	{
		Save();
		MinimapManager.OnVanillaMapAvailable -= RegisterRoadFilters;
		if ((Object)(object)editor != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)editor).gameObject);
		}
		if ((Object)(object)large != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)((Component)large).transform.parent).gameObject);
		}
		if ((Object)(object)small != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)((Component)small).transform.parent).gameObject);
		}
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		Instance = null;
	}
}
[HarmonyPatch(typeof(Player), "PlacePiece", new Type[]
{
	typeof(Piece),
	typeof(Vector3),
	typeof(Quaternion),
	typeof(bool),
	typeof(bool)
})]
internal static class RoadPlacementPatch
{
	private static void Postfix(Player __instance, Piece __0, Vector3 __1)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)Plugin.Instance == (Object)null)
		{
			return;
		}
		try
		{
			Plugin.Instance.Record(__0, __1);
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Simple Road Map: " + ex));
		}
	}
}
[HarmonyPatch(typeof(ZNet), "Shutdown")]
internal static class RoadShutdownPatch
{
	private static void Prefix()
	{
		if ((Object)(object)Plugin.Instance != (Object)null)
		{
			Plugin.Instance.Save();
		}
	}
}
public static class RoadCurve
{
	public static RoadPoint Sample(RoadPoint a, RoadPoint b, RoadPoint c, RoadPoint d, float t)
	{
		float num = (c.x - a.x) * 0.5f;
		float num2 = (c.z - a.z) * 0.5f;
		float num3 = (d.x - b.x) * 0.5f;
		float num4 = (d.z - b.z) * 0.5f;
		double num5 = RoadModel.Distance(b, c);
		double num6 = Math.Sqrt(num * num + num2 * num2);
		double num7 = Math.Sqrt(num3 * num3 + num4 * num4);
		if (num6 > num5 && num6 > 0.0)
		{
			num *= (float)(num5 / num6);
			num2 *= (float)(num5 / num6);
		}
		if (num7 > num5 && num7 > 0.0)
		{
			num3 *= (float)(num5 / num7);
			num4 *= (float)(num5 / num7);
		}
		float num8 = t * t;
		float num9 = num8 * t;
		float num10 = 2f * num9 - 3f * num8 + 1f;
		float num11 = num9 - 2f * num8 + t;
		float num12 = -2f * num9 + 3f * num8;
		float num13 = num9 - num8;
		return new RoadPoint(num10 * b.x + num11 * num + num12 * c.x + num13 * num3, num10 * b.z + num11 * num2 + num12 * c.z + num13 * num4);
	}
}
public struct RoadDash
{
	private double position;

	private double length;

	private double dash;

	private double period;

	private int iterations;

	public RoadInterval Current;

	public RoadDash(double distance, double length, double dash, double gap)
	{
		this.length = length;
		this.dash = dash;
		period = dash + gap;
		position = ((period > 0.0) ? (Math.Floor(distance / period) * period - distance) : 0.0);
		iterations = 0;
		Current = default(RoadInterval);
	}

	public bool MoveNext()
	{
		if (period <= 0.0 || dash <= 0.0 || double.IsNaN(position) || double.IsInfinity(position))
		{
			return false;
		}
		while (position < length && iterations++ < 10000)
		{
			double num = Math.Max(0.0, position);
			double num2 = Math.Min(length, position + dash);
			double num3 = position + period;
			if (num3 <= position)
			{
				return false;
			}
			position = num3;
			if (num2 > num)
			{
				Current = new RoadInterval(num, num2);
				return true;
			}
		}
		return false;
	}
}
public struct RoadInterval
{
	public double from;

	public double to;

	public RoadInterval(double from, double to)
	{
		this.from = from;
		this.to = to;
	}
}
public sealed class RoadEraseIndex
{
	private readonly Dictionary<string, List<RoadInterval>> hidden = new Dictionary<string, List<RoadInterval>>();

	public RoadEraseIndex(RoadData data)
	{
		HashSet<string> hashSet = new HashSet<string>(data.restored);
		foreach (RoadErase erasure in data.erasures)
		{
			if (!hashSet.Contains(erasure.id))
			{
				if (!hidden.TryGetValue(erasure.line, out var value))
				{
					hidden.Add(erasure.line, value = new List<RoadInterval>());
				}
				value.Add(new RoadInterval(erasure.from, erasure.to));
			}
		}
		foreach (List<RoadInterval> value2 in hidden.Values)
		{
			Combine(value2);
		}
	}

	public bool IsErased(string line, double point)
	{
		if (line == null || !hidden.TryGetValue(line, out var value))
		{
			return false;
		}
		foreach (RoadInterval item in value)
		{
			if (point >= item.from && point <= item.to)
			{
				return true;
			}
		}
		return false;
	}

	public List<RoadInterval> Visible(string line, double from, double to)
	{
		List<RoadInterval> list = new List<RoadInterval>();
		if (line == null || !hidden.TryGetValue(line, out var value))
		{
			list.Add(new RoadInterval(from, to));
			return list;
		}
		double num = from;
		foreach (RoadInterval item in value)
		{
			if (!(item.to < num))
			{
				if (item.from > to)
				{
					break;
				}
				if (item.from > num)
				{
					list.Add(new RoadInterval(num, Math.Min(to, item.from)));
				}
				num = Math.Max(num, item.to);
				if (num >= to)
				{
					break;
				}
			}
		}
		if (num < to)
		{
			list.Add(new RoadInterval(num, to));
		}
		return list;
	}

	internal static void Combine(List<RoadInterval> ranges)
	{
		ranges.Sort((RoadInterval a, RoadInterval b) => a.from.CompareTo(b.from));
		int num = 1;
		while (num < ranges.Count)
		{
			RoadInterval roadInterval = ranges[num - 1];
			RoadInterval roadInterval2 = ranges[num];
			if (roadInterval2.from <= roadInterval.to + 1E-08)
			{
				ranges[num - 1] = new RoadInterval(roadInterval.from, Math.Max(roadInterval.to, roadInterval2.to));
				ranges.RemoveAt(num);
			}
			else
			{
				num++;
			}
		}
	}
}
public static class RoadEditing
{
	public static bool Erase(RoadData data, string stroke, RoadPoint center, double radius, Func<RoadPoint, RoadPoint> project, Func<int, bool> visible, Func<RoadPoint, bool> explored, RoadNetwork network = null)
	{
		if (radius <= 0.0)
		{
			return false;
		}
		RoadMerge.EnsureIds(data);
		RoadEraseIndex roadEraseIndex = new RoadEraseIndex(data);
		RoadPaintIndex roadPaintIndex = new RoadPaintIndex(data);
		bool result = false;
		foreach (RoadLine line in data.lines)
		{
			List<RoadInterval> list = new List<RoadInterval>();
			if (line.points.Count == 1)
			{
				RoadPoint roadPoint = line.points[0];
				if (!explored(roadPoint) || RoadModel.Distance(project(roadPoint), center) > radius || roadEraseIndex.IsErased(line.id, 0.0))
				{
					continue;
				}
				int kind = roadPaintIndex.Kind(line, 0.0);
				network?.Resolve(line, 0.0, roadPoint, 0.0, 0.0, out kind);
				if (visible(kind))
				{
					list.Add(new RoadInterval(0.0, 0.0));
				}
			}
			for (int i = 0; i + 1 < line.points.Count; i++)
			{
				RoadPoint a = line.points[Math.Max(0, i - 1)];
				RoadPoint roadPoint2 = line.points[i];
				RoadPoint roadPoint3 = line.points[i + 1];
				RoadPoint d = line.points[Math.Min(line.points.Count - 1, i + 2)];
				RoadPoint a2 = project(roadPoint2);
				RoadPoint roadPoint4 = roadPoint2;
				double num = RoadModel.Distance(a2, project(roadPoint3));
				int num2 = Math.Max(4, Math.Min(256, (int)Math.Ceiling(num / 2.0)));
				for (int j = 1; j <= num2; j++)
				{
					RoadPoint roadPoint5 = RoadCurve.Sample(a, roadPoint2, roadPoint3, d, (float)j / (float)num2);
					RoadPoint roadPoint6 = project(roadPoint5);
					RoadPoint roadPoint7 = new RoadPoint((roadPoint5.x + roadPoint4.x) * 0.5f, (roadPoint5.z + roadPoint4.z) * 0.5f);
					if (CircleHit(a2, roadPoint6, center, radius, out var from, out var to) && explored(roadPoint7))
					{
						int kind2 = roadPaintIndex.Kind(line, (double)i + ((double)j - 0.5) / (double)num2);
						network?.Resolve(line, (double)i + ((double)j - 0.5) / (double)num2, roadPoint7, roadPoint5.x - roadPoint4.x, roadPoint5.z - roadPoint4.z, out kind2);
						double num3 = (double)i + ((double)j - 1.0 + from) / (double)num2;
						double num4 = (double)i + ((double)j - 1.0 + to) / (double)num2;
						if (visible(kind2) && num4 > num3 + 1E-10)
						{
							list.AddRange(roadEraseIndex.Visible(line.id, num3, num4));
						}
					}
					a2 = roadPoint6;
					roadPoint4 = roadPoint5;
				}
			}
			RoadEraseIndex.Combine(list);
			foreach (RoadInterval item in list)
			{
				data.erasures.Add(new RoadErase
				{
					id = Guid.NewGuid().ToString("N"),
					stroke = stroke,
					line = line.id,
					from = item.from,
					to = item.to
				});
				result = true;
			}
		}
		return result;
	}

	public static int Undo(RoadData data, string stroke)
	{
		if (string.IsNullOrEmpty(stroke))
		{
			return 0;
		}
		int num = 0;
		HashSet<string> hashSet = new HashSet<string>(data.restored);
		foreach (RoadErase erasure in data.erasures)
		{
			if (erasure.stroke == stroke && hashSet.Add(erasure.id))
			{
				data.restored.Add(erasure.id);
				num++;
			}
		}
		return num;
	}

	public static void CompactUnpublishedStroke(RoadData data, string stroke)
	{
		Dictionary<string, List<RoadInterval>> dictionary = new Dictionary<string, List<RoadInterval>>();
		HashSet<string> hashSet = new HashSet<string>(data.restored);
		foreach (RoadErase erasure in data.erasures)
		{
			if (erasure.stroke == stroke)
			{
				if (hashSet.Contains(erasure.id))
				{
					return;
				}
				if (!dictionary.TryGetValue(erasure.line, out var value))
				{
					dictionary.Add(erasure.line, value = new List<RoadInterval>());
				}
				value.Add(new RoadInterval(erasure.from, erasure.to));
			}
		}
		data.erasures.RemoveAll((RoadErase erase) => erase.stroke == stroke);
		foreach (KeyValuePair<string, List<RoadInterval>> item in dictionary)
		{
			RoadEraseIndex.Combine(item.Value);
			foreach (RoadInterval item2 in item.Value)
			{
				data.erasures.Add(new RoadErase
				{
					id = Guid.NewGuid().ToString("N"),
					stroke = stroke,
					line = item.Key,
					from = item2.from,
					to = item2.to
				});
			}
		}
	}

	public static bool CircleHit(RoadPoint a, RoadPoint b, RoadPoint center, double radius, out double from, out double to)
	{
		double num = a.x - center.x;
		double num2 = a.z - center.z;
		double num3 = b.x - a.x;
		double num4 = b.z - a.z;
		double num5 = num3 * num3 + num4 * num4;
		double num6 = 2.0 * (num * num3 + num2 * num4);
		double num7 = num * num + num2 * num2 - radius * radius;
		from = 0.0;
		to = 1.0;
		if (num5 < 1E-16)
		{
			return num7 <= 0.0;
		}
		double num8 = num6 * num6 - 4.0 * num5 * num7;
		if (num8 < 0.0)
		{
			return false;
		}
		double num9 = Math.Sqrt(num8);
		from = Math.Max(0.0, (0.0 - num6 - num9) / (2.0 * num5));
		to = Math.Min(1.0, (0.0 - num6 + num9) / (2.0 * num5));
		return from <= to;
	}
}
public class RoadEditor : MonoBehaviour
{
	private static RoadEditor current;

	private RoadGraphic map;

	private RoadEraseSurface surface;

	private RoadEraseCursor cursor;

	private Toggle undo;

	private Text radiusText;

	private Slider radiusSlider;

	private MinimapOverlayPanel panel;

	public bool Editing { get; private set; }

	public static bool Active
	{
		get
		{
			if ((Object)(object)current != (Object)null && current.Editing)
			{
				return ((Component)current).gameObject.activeInHierarchy;
			}
			return false;
		}
	}

	private Camera EventCamera
	{
		get
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)((Graphic)map).canvas == (Object)null) && (int)((Graphic)map).canvas.renderMode != 0)
			{
				return ((Graphic)map).canvas.worldCamera;
			}
			return null;
		}
	}

	private float Scale
	{
		get
		{
			if (!((Object)(object)((Graphic)map).canvas == (Object)null))
			{
				return Mathf.Max(0.01f, ((Graphic)map).canvas.scaleFactor);
			}
			return 1f;
		}
	}

	public static RoadEditor Create(Minimap minimap, RoadGraphic graphic)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Expected O, but got Unknown
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Expected O, but got Unknown
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Expected O, but got Unknown
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Expected O, but got Unknown
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Expected O, but got Unknown
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Expected O, but got Unknown
		GameObject val = new GameObject("SimpleRoadMapEditingController", new Type[1] { typeof(RectTransform) });
		RectTransform val2 = (RectTransform)val.transform;
		((Transform)val2).SetParent(minimap.m_largeRoot.transform, false);
		val2.sizeDelta = Vector2.zero;
		RoadEditor roadEditor = val.AddComponent<RoadEditor>();
		roadEditor.map = graphic;
		current = roadEditor;
		roadEditor.AttachPanelControls();
		GameObject val3 = new GameObject("SimpleRoadMapEraser", new Type[3]
		{
			typeof(RectTransform),
			typeof(CanvasRenderer),
			typeof(Image)
		});
		Stretch((RectTransform)val3.transform, ((Component)graphic.MapImage).transform);
		((Graphic)val3.GetComponent<Image>()).color = Color.clear;
		((Graphic)val3.GetComponent<Image>()).raycastTarget = true;
		val3.GetComponent<CanvasRenderer>().cullTransparentMesh = false;
		roadEditor.surface = val3.AddComponent<RoadEraseSurface>();
		roadEditor.surface.Owner = roadEditor;
		GameObject val4 = new GameObject("EraserCursor", new Type[2]
		{
			typeof(RectTransform),
			typeof(CanvasRenderer)
		});
		Stretch((RectTransform)val4.transform, val3.transform);
		roadEditor.cursor = val4.AddComponent<RoadEraseCursor>();
		((Graphic)roadEditor.cursor).raycastTarget = false;
		val3.SetActive(false);
		return roadEditor;
	}

	private static void Stretch(RectTransform rect, Transform parent)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		((Transform)rect).SetParent(parent, false);
		rect.anchorMin = Vector2.zero;
		rect.anchorMax = Vector2.one;
		Vector2 offsetMin = (rect.offsetMax = Vector2.zero);
		rect.offsetMin = offsetMin;
	}

	private void AttachPanelControls()
	{
		ref MinimapOverlayPanel reference = ref panel;
		object? value = AccessTools.Field(typeof(MinimapManager), "OverlayPanel").GetValue(MinimapManager.Instance);
		reference = (MinimapOverlayPanel)((value is MinimapOverlayPanel) ? value : null);
		if ((Object)(object)panel == (Object)null || (Object)(object)Plugin.Instance == (Object)null || Plugin.Instance.EraserControl == null)
		{
			return;
		}
		MapOverlay eraserControl = Plugin.Instance.EraserControl;
		object? value2 = AccessTools.Field(((object)eraserControl).GetType().BaseType, "Toggle").GetValue(eraserControl);
		Toggle val = (Toggle)((value2 is Toggle) ? value2 : null);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		radiusText = ((Component)val).GetComponentInChildren<Text>();
		CreateRadiusSlider(val);
		undo = panel.AddOverlayToggle("Simple Road Map", "Zpět");
		undo.SetIsOnWithoutNotify(false);
		((UnityEvent<bool>)(object)undo.onValueChanged).AddListener((UnityAction<bool>)delegate(bool clicked)
		{
			if (clicked && (Object)(object)Plugin.Instance != (Object)null)
			{
				Plugin.Instance.UndoErase();
			}
			if ((Object)(object)undo != (Object)null)
			{
				undo.SetIsOnWithoutNotify(false);
			}
		});
	}

	private void CreateRadiusSlider(Toggle eraserToggle)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Expected O, but got Unknown
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Expected O, but got Unknown
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: 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)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Expected O, but got Unknown
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Expected O, but got Unknown
		//IL_0209: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Unknown result type (might be due to invalid IL or missing references)
		//IL_026f: Expected O, but got Unknown
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Expected O, but got Unknown
		//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0357: Unknown result type (might be due to invalid IL or missing references)
		RectTransform val = (RectTransform)((Component)radiusText).transform;
		val.anchorMin = Vector2.zero;
		val.anchorMax = Vector2.one;
		val.offsetMin = new Vector2(26f, 0f);
		val.offsetMax = new Vector2(-78f, 0f);
		radiusText.alignment = (TextAnchor)3;
		GameObject val2 = new GameObject("RadiusSlider", new Type[5]
		{
			typeof(RectTransform),
			typeof(CanvasRenderer),
			typeof(Image),
			typeof(Slider),
			typeof(LayoutElement)
		});
		val2.GetComponent<LayoutElement>().ignoreLayout = true;
		RectTransform val3 = (RectTransform)val2.transform;
		((Transform)val3).SetParent(((Component)eraserToggle).transform, false);
		Vector2 val4 = (val3.pivot = new Vector2(1f, 0.5f));
		Vector2 anchorMin = (val3.anchorMax = val4);
		val3.anchorMin = anchorMin;
		val3.sizeDelta = new Vector2(64f, 14f);
		val3.anchoredPosition = new Vector2(-5f, 0f);
		((Graphic)val2.GetComponent<Image>()).color = Color.clear;
		val2.GetComponent<CanvasRenderer>().cullTransparentMesh = false;
		radiusSlider = val2.GetComponent<Slider>();
		Image val7 = SliderImage("Background", (Transform)(object)val3, new Color(0.12f, 0.1f, 0.08f, 1f));
		((Graphic)val7).rectTransform.anchorMin = new Vector2(0f, 0.4f);
		((Graphic)val7).rectTransform.anchorMax = new Vector2(1f, 0.6f);
		GameObject val8 = new GameObject("FillArea", new Type[1] { typeof(RectTransform) });
		Stretch((RectTransform)val8.transform, (Transform)(object)val3);
		Image val9 = SliderImage("Fill", val8.transform, new Color(1f, 0.7f, 0.2f, 1f));
		((Graphic)val9).rectTransform.anchorMin = new Vector2(0f, 0.4f);
		((Graphic)val9).rectTransform.anchorMax = new Vector2(1f, 0.6f);
		GameObject val10 = new GameObject("HandleArea", new Type[1] { typeof(RectTransform) });
		Stretch((RectTransform)val10.transform, (Transform)(object)val3);
		Image val11 = SliderImage("Handle", val10.transform, new Color(1f, 0.9f, 0.65f, 1f));
		RectTransform rectTransform = ((Graphic)val11).rectTransform;
		Vector2 anchorMin2 = (((Graphic)val11).rectTransform.anchorMax = new Vector2(0f, 0.5f));
		rectTransform.anchorMin = anchorMin2;
		radiusSlider.fillRect = ((Graphic)val9).rectTransform;
		radiusSlider.handleRect = ((Graphic)val11).rectTransform;
		((Selectable)radiusSlider).targetGraphic = (Graphic)(object)val11;
		radiusSlider.direction = (Direction)0;
		radiusSlider.minValue = 4f;
		radiusSlider.maxValue = 100f;
		radiusSlider.wholeNumbers = true;
		GUIManager.Instance.ApplySliderStyle(radiusSlider, new Vector2(8f, 12f));
		val11.sprite = val9.sprite;
		radiusSlider.SetValueWithoutNotify(Plugin.Instance.EraserRadius);
		((UnityEvent<float>)(object)radiusSlider.onValueChanged).AddListener((UnityAction<float>)delegate(float value)
		{
			if ((Object)(object)Plugin.Instance != (Object)null)
			{
				Plugin.Instance.EraserRadius = value;
			}
		});
	}

	private static Image SliderImage(string name, Transform parent, Color color)
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Expected O, but got Unknown
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject(name, new Type[3]
		{
			typeof(RectTransform),
			typeof(CanvasRenderer),
			typeof(Image)
		});
		Stretch((RectTransform)val.transform, parent);
		Image component = val.GetComponent<Image>();
		((Graphic)component).color = color;
		return component;
	}

	internal bool LocalPoint(Vector2 screen, out Vector2 point)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: 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_004f: Unknown result type (might be due to invalid IL or missing references)
		point = Vector2.zero;
		if ((Object)(object)surface == (Object)null || OverPanel(screen))
		{
			return false;
		}
		RectTransform val = (RectTransform)((Component)surface).transform;
		if (RectTransformUtility.ScreenPointToLocalPointInRectangle(val, screen, EventCamera, ref point))
		{
			Rect rect = val.rect;
			return ((Rect)(ref rect)).Contains(point);
		}
		return false;
	}

	private bool OverPanel(Vector2 screen)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Expected O, but got Unknown
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Expected O, but got Unknown
		if ((Object)(object)panel == (Object)null)
		{
			return false;
		}
		if ((Object)(object)panel.Button != (Object)null && ((Component)panel.Button).gameObject.activeInHierarchy && RectTransformUtility.RectangleContainsScreenPoint((RectTransform)((Component)panel.Button).transform, screen, EventCamera))
		{
			return true;
		}
		if ((Object)(object)panel.OverlayGroup != (Object)null && panel.OverlayGroup.activeInHierarchy)
		{
			return RectTransformUtility.RectangleContainsScreenPoint((RectTransform)panel.OverlayGroup.transform, screen, EventCamera);
		}
		return false;
	}

	internal void Apply(Vector2 previous, Vector2 point, bool connect)
	{
		//IL_002f: 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_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: 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_005a: 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 (Editing && !((Object)(object)Plugin.Instance == (Object)null))
		{
			float num = Plugin.Instance.EraserRadius / Scale;
			int num2 = ((!connect) ? 1 : Mathf.Max(1, Mathf.CeilToInt(Vector2.Distance(previous, point) / Mathf.Max(1f, num * 0.5f))));
			for (int i = 1; i <= num2; i++)
			{
				Vector2 val = (connect ? Vector2.Lerp(previous, point, (float)i / (float)num2) : point);
				Plugin.Instance.EraseAt(new RoadPoint(val.x, val.y), num, map);
			}
		}
	}

	internal void SetEditing(bool enabled)
	{
		if (enabled && ((Object)(object)Plugin.Instance == (Object)null || !Plugin.Instance.CanEdit))
		{
			if ((Object)(object)Plugin.Instance != (Object)null)
			{
				Plugin.Instance.SyncEraserFilter(enabled: false);
			}
			return;
		}
		if (!enabled && (Object)(object)Plugin.Instance != (Object)null)
		{
			Plugin.Instance.EndEraseStroke();
		}
		Editing = enabled;
		if ((Object)(object)Plugin.Instance != (Object)null)
		{
			Plugin.Instance.SyncEraserFilter(enabled);
		}
		if ((Object)(object)surface != (Object)null)
		{
			((Component)surface).gameObject.SetActive(enabled);
		}
	}

	private void Update()
	{
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)map == (Object)null) && !((Object)(object)Plugin.Instance == (Object)null))
		{
			if ((Object)(object)undo == (Object)null)
			{
				AttachPanelControls();
			}
			if ((Object)(object)undo != (Object)null)
			{
				((Selectable)undo).interactable = Plugin.Instance.CanUndoErase;
			}
			if ((Object)(object)radiusText != (Object)null)
			{
				radiusText.text = "Guma " + Mathf.RoundToInt(Plugin.Instance.EraserRadius);
			}
			if ((Object)(object)radiusSlider != (Object)null)
			{
				radiusSlider.SetValueWithoutNotify(Plugin.Instance.EraserRadius);
			}
			if (Editing && !Plugin.Instance.CanEdit)
			{
				SetEditing(enabled: false);
			}
			if (Editing && !((Object)(object)cursor == (Object)null))
			{
				Vector2 point;
				bool show = LocalPoint(Vector2.op_Implicit(ZInput.pointerPosition), out point);
				cursor.SetState(show, point, Plugin.Instance.EraserRadius / Scale, 1f / Scale);
			}
		}
	}

	private void OnDisable()
	{
		SetEditing(enabled: false);
	}

	private void OnDestroy()
	{
		SetEditing(enabled: false);
		if ((Object)(object)undo != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)undo).gameObject);
		}
		if ((Object)(object)radiusSlider != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)radiusSlider).gameObject);
		}
		if ((Object)(object)surface != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)surface).gameObject);
		}
		if ((Object)(object)current == (Object)(object)this)
		{
			current = null;
		}
	}
}
public class RoadEraseSurface : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IEventSystemHandler, ICanvasRaycastFilter
{
	public RoadEditor Owner;

	private bool stroke;

	private bool connected;

	private Vector2 previous;

	public bool IsRaycastLocationValid(Vector2 screen, Camera camera)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		Vector2 point;
		if ((Object)(object)Owner != (Object)null && Owner.Editing)
		{
			return Owner.LocalPoint(screen, out point);
		}
		return false;
	}

	public void OnPointerDown(PointerEventData e)
	{
		//IL_0001: 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_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		if ((int)e.button == 0 && !((Object)(object)Owner == (Object)null) && Owner.Editing && Owner.LocalPoint(e.position, out var point))
		{
			Plugin.Instance.BeginEraseStroke();
			stroke = true;
			Owner.Apply(point, point, connect: false);
			previous = point;
			connected = true;
			((AbstractEventData)e).Use();
		}
	}

	public void OnBeginDrag(PointerEventData e)
	{
		if (stroke)
		{
			((AbstractEventData)e).Use();
		}
	}

	public void OnDrag(PointerEventData e)
	{
		//IL_001e: 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_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		if (stroke && !((Object)(object)Owner == (Object)null))
		{
			if (Owner.LocalPoint(e.position, out var point))
			{
				Owner.Apply(previous, point, connected);
				previous = point;
				connected = true;
			}
			else
			{
				connected = false;
			}
			((AbstractEventData)e).Use();
		}
	}

	public void OnPointerUp(PointerEventData e)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		if ((int)e.button == 0)
		{
			Finish();
		}
	}

	public void OnEndDrag(PointerEventData e)
	{
		Finish();
	}

	private void Finish()
	{
		if (stroke && (Object)(object)Plugin.Instance != (Object)null)
		{
			Plugin.Instance.EndEraseStroke();
		}
		stroke = (connected = false);
	}

	private void OnDisable()
	{
		Finish();
	}
}
public class RoadEraseCursor : MaskableGraphic
{
	public Vector2 Center;

	public float Radius;

	public float Thickness;

	public bool Show;

	public void SetState(bool show, Vector2 center, float radius, float thickness)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: 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_0012: Unknown result type (might be due to invalid IL or missing references)
		if (Show != show || (show && (!(Center == center) || Radius != radius || Thickness != thickness)))
		{
			Show = show;
			Center = center;
			Radius = radius;
			Thickness = thickness;
			((Graphic)this).SetVerticesDirty();
		}
	}

	protected override void OnPopulateMesh(VertexHelper mesh)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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)
		//IL_0087: 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_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: 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)
		mesh.Clear();
		if (!Show)
		{
			return;
		}
		Color32 val = Color32.op_Implicit(new Color(1f, 0.35f, 0.2f, 0.95f));
		Vector2 val2 = default(Vector2);
		for (int i = 0; i <= 80; i++)
		{
			float num = (float)i * (float)Math.PI * 2f / 80f;
			((Vector2)(ref val2))..ctor(Mathf.Cos(num), Mathf.Sin(num));
			mesh.AddVert(Vector2.op_Implicit(Center + val2 * (Radius - Thickness * 0.5f)), val, Vector4.op_Implicit(Vector2.zero));
			mesh.AddVert(Vector2.op_Implicit(Center + val2 * (Radius + Thickness * 0.5f)), val, Vector4.op_Implicit(Vector2.zero));
			if (i != 0)
			{
				int num2 = i * 2;
				mesh.AddTriangle(num2 - 2, num2 - 1, num2 + 1);
				mesh.AddTriangle(num2 - 2, num2 + 1, num2);
			}
		}
	}
}
[HarmonyPatch(typeof(Minimap), "UpdateMap")]
internal static class EraserMapInputPatch
{
	private static void Prefix(ref float ___m_leftDownTime, ref bool ___m_dragView)
	{
		if (RoadEditor.Active)
		{
			___m_leftDownTime = 0f;
			___m_dragView = false;
		}
	}
}
[HarmonyPatch]
internal static class EraserMapClickPatch
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		try
		{
			string[] array = new string[6] { "OnMapLeftDown", "OnMapLeftUp", "OnMapLeftClick", "OnMapDblClick", "OnMapMiddleClick", "RemovePinUnderPointer" };
			foreach (string name in array)
			{
				MethodInfo method = AccessTools.Method(typeof(Minimap), name, (Type[])null, (Type[])null);
				if (method != null)
				{
					yield return method;
				}
			}
		}
		finally
		{
		}
	}

	private static bool Prefix()
	{
		return !RoadEditor.Active;
	}
}
public class RoadGraphic : MaskableGraphic
{
	private delegate void MapPoint(Vector3 position, out float x, out float y);

	public RawImage MapImage;

	public bool Circular;

	private MapPoint project;

	private Func<Vector3, bool> explored;

	private Minimap boundMap;

	private Rect previousUV;

	private Rect previousRect;

	private int revision = -1;

	private float nextFogCheck;

	private float previousScale;

	private float nextRebuild;

	private static readonly RoadPoint Origin = new RoadPoint(0f, 0f);

	private static readonly RoadPoint Reference = new RoadPoint(100f, 0f);

	public static RoadGraphic Create(RawImage image, bool circular)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Expected O, but got Unknown
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		GameObject val = new GameObject("SimpleRoadMapClip", new Type[2]
		{
			typeof(RectTransform),
			typeof(RectMask2D)
		});
		Stretch((RectTransform)val.transform, ((Component)image).transform);
		val.transform.SetAsFirstSibling();
		GameObject val2 = new GameObject("SimpleRoadMapCurves", new Type[2]
		{
			typeof(RectTransform),
			typeof(CanvasRenderer)
		});
		Stretch((RectTransform)val2.transform, val.transform);
		RoadGraphic roadGraphic = val2.AddComponent<RoadGraphic>();
		roadGraphic.MapImage = image;
		roadGraphic.Circular = circular;
		((Graphic)roadGraphic).raycastTarget = false;
		return roadGraphic;
	}

	private static void Stretch(RectTransform rect, Transform parent)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		((Transform)rect).SetParent(parent, false);
		rect.anchorMin = Vector2.zero;
		rect.anchorMax = Vector2.one;
		Vector2 offsetMin = (rect.offsetMax = Vector2.zero);
		rect.offsetMin = offsetMin;
	}

	private void LateUpdate()
	{
		//IL_0072: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: 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_0095: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)MapImage == (Object)null) && ((Behaviour)MapImage).isActiveAndEnabled && !((Object)(object)Plugin.Instance == (Object)null) && (revision != Plugin.Instance.Revision || !(Time.unscaledTime < nextRebuild)))
		{
			float num = (((Object)(object)((Graphic)this).canvas == (Object)null) ? 1f : ((Graphic)this).canvas.scaleFactor);
			if (previousUV != MapImage.uvRect || previousRect != ((Graphic)this).rectTransform.rect || revision != Plugin.Instance.Revision || previousScale != num || Time.unscaledTime >= nextFogCheck)
			{
				previousUV = MapImage.uvRect;
				previousRect = ((Graphic)this).rectTransform.rect;
				previousScale = num;
				revision = Plugin.Instance.Revision;
				nextFogCheck = Time.unscaledTime + 1f;
				nextRebuild = Time.unscaledTime + 1f / 30f;
				((Graphic)this).SetVerticesDirty();
			}
		}
	}

	private void BindMap(Minimap map)
	{
		if (!((Object)(object)boundMap == (Object)(object)map) || project == null)
		{
			boundMap = map;
			project = (MapPoint)Delegate.CreateDelegate(typeof(MapPoint), map, AccessTools.Method(typeof(Minimap), "WorldToMapPoint", (Type[])null, (Type[])null));
			explored = (Func<Vector3, bool>)Delegate.CreateDelegate(typeof(Func<Vector3, bool>), map, AccessTools.Method(typeof(Minimap), "IsExplored", new Type[1] { typeof(Vector3) }, (Type[])null));
		}
	}

	internal RoadPoint ProjectForEditing(RoadPoint point)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		BindMap(Minimap.instance);
		Vector2 val = Project(point, MapImage.uvRect, ((Graphic)this).rectTransform.rect);
		return new RoadPoint(val.x, val.y);
	}

	internal bool ExploredForEditing(RoadPoint point)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		BindMap(Minimap.instance);
		Vector2 val = Project(point, MapImage.uvRect, ((Graphic)this).rectTransform.rect);
		Rect rect = ((Graphic)this).rectTransform.rect;
		if (((Rect)(ref rect)).Contains(val))
		{
			return explored(new Vector3(point.x, 0f, point.z));
		}
		return false;
	}

	private Vector2 Project(RoadPoint p, Rect uv, Rect rect)
	{
		//IL_0017: 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)
		project(new Vector3(p.x, 0f, p.z), out var x, out var y);
		return new Vector2(((Rect)(ref rect)).xMin + (x - ((Rect)(ref uv)).x) / ((Rect)(ref uv)).width * ((Rect)(ref rect)).width, ((Rect)(ref rect)).yMin + (y - ((Rect)(ref uv)).y) / ((Rect)(ref uv)).height * ((Rect)(ref rect)).height);
	}

	protected override void OnPopulateMesh(VertexHelper mesh)
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: 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_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: 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_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0296: Unknown result type (might be due to invalid IL or missing references)
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_0256: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		//IL_026e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0285: Unknown result type (might be due to invalid IL or missing references)
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_028b: Unknown result type (might be due to invalid IL or missing references)
		mesh.Clear();
		Plugin instance = Plugin.Instance;
		Minimap instance2 = Minimap.instance;
		if ((Object)(object)instance == (Object)null || instance.Data == null || !instance.RoadsVisible || (Object)(object)instance2 == (Object)null || (Object)(object)MapImage == (Object)null || !((Behaviour)MapImage).isActiveAndEnabled)
		{
			return;
		}
		BindMap(instance2);
		Rect uvRect = MapImage.uvRect;
		Rect rect = ((Graphic)this).rectTransform.rect;
		if (((Rect)(ref uvRect)).width <= 0f || ((Rect)(ref uvRect)).height <= 0f)
		{
			return;
		}
		float num = (((Object)(object)((Graphic)this).canvas == (Object)null) ? 1f : Mathf.Max(0.01f, ((Graphic)this).canvas.scaleFactor));
		float num2 = instance.StrokeWidth / num;
		float dash = instance.DashLength / num;
		float gap = instance.GapLength / num;
		IList<RoadRenderPart> renderParts = instance.Network.GetRenderParts();
		double num3 = (double)Vector2.Distance(Project(Origin, uvRect, rect), Project(Reference, uvRect, rect)) / 100.0;
		for (int i = 0; i < renderParts.Count; i++)
		{
			RoadRenderPart roadRenderPart = renderParts[i];
			if (!instance.RoadVisible(roadRenderPart.kind))
			{
				continue;
			}
			Vector2 a = Project(roadRenderPart.a, uvRect, rect);
			Vector2 b = Project(roadRenderPart.b, uvRect, rect);
			if (Mathf.Max(a.x, b.x) < ((Rect)(ref rect)).xMin - num2 || Mathf.Min(a.x, b.x) > ((Rect)(ref rect)).xMax + num2 || Mathf.Max(a.y, b.y) < ((Rect)(ref rect)).yMin - num2 || Mathf.Min(a.y, b.y) > ((Rect)(ref rect)).yMax + num2 || !explored(new Vector3((roadRenderPart.a.x + roadRenderPart.b.x) * 0.5f, 0f, (roadRenderPart.a.z + roadRenderPart.b.z) * 0.5f)))
			{
				continue;
			}
			Color32 color = Color32.op_Implicit(instance.RoadColor(roadRenderPart.kind));
			if (roadRenderPart.point)
			{
				b = a + Vector2.right * num2 * 0.5f;
				if (Clip(ref a, ref b, rect, num2))
				{
					Quad(mesh, a, b, num2, color);
				}
			}
			else
			{
				DashedSegment(mesh, a, b, roadRenderPart.distance * num3, num2, dash, gap, color, rect);
			}
			if (mesh.currentVertCount > 60000)
			{
				break;
			}
		}
	}

	private void DashedSegment(VertexHelper mesh, Vector2 a, Vector2 b, double distance, float width, float dash, float gap, Color32 color, Rect rect)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: 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_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: 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)
		Vector2 val = a;
		if (!Clip(ref a, ref b, rect, width))
		{
			return;
		}
		distance += (double)Vector2.Distance(val, a);
		double num = Vector2.Distance(a, b);
		if (!(num < 0.0001))
		{
			RoadDash roadDash = new RoadDash(distance, num, dash, gap);
			while (roadDash.MoveNext())
			{
				RoadInterval current = roadDash.Current;
				Quad(mesh, Vector2.Lerp(a, b, (float)(current.from / num)), Vector2.Lerp(a, b, (float)(current.to / num)), width, color);
			}
		}
	}

	private bool Clip(ref Vector2 a, ref Vector2 b, Rect rect, float width)
	{
		//IL_0001: 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_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)
		//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0204: Unknown result type (might be due to invalid IL or missing references)
		//IL_0209: Unknown result type (might be due to invalid IL or missing references)
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_0215: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		Vector2 val = b - a;
		float low = 0f;
		float high = 1f;
		if (!Boundary(0f - val.x, a.x - ((Rect)(ref rect)).xMin, ref low, ref high) || !Boundary(val.x, ((Rect)(ref rect)).xMax - a.x, ref low, ref high) || !Boundary(0f - val.y, a.y - ((Rect)(ref rect)).yMin, ref low, ref high) || !Boundary(val.y, ((Rect)(ref rect)).yMax - a.y, ref low, ref high))
		{
			return false;
		}
		if (Circular)
		{
			Vector2 val2 = ((Rect)(ref rect)).size * 0.5f - Vector2.one * width;
			if (val2.x <= 0f || val2.y <= 0f)
			{
				return false;
			}
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor((a.x - ((Rect)(ref rect)).center.x) / val2.x, (a.y - ((Rect)(ref rect)).center.y) / val2.y);
			Vector2 val4 = default(Vector2);
			((Vector2)(ref val4))..ctor(val.x / val2.x, val.y / val2.y);
			float num = Vector2.Dot(val4, val4);
			float num2 = 2f * Vector2.Dot(val3, val4);
			float num3 = Vector2.Dot(val3, val3) - 1f;
			if (num < 1E-07f)
			{
				if (num3 > 0f)
				{
					return false;
				}
			}
			else
			{
				float num4 = num2 * num2 - 4f * num * num3;
				if (num4 < 0f)
				{
					return false;
				}
				float num5 = Mathf.Sqrt(num4);
				low = Mathf.Max(low, (0f - num2 - num5) / (2f * num));
				high = Mathf.Min(high, (0f - num2 + num5) / (2f * num));
				if (high < low)
				{
					return false;
				}
			}
		}
		b = a + val * high;
		a += val * low;
		return true;
	}

	private static bool Boundary(float p, float q, ref float low, ref float high)
	{
		if (Mathf.Abs(p) < 1E-06f)
		{
			return q >= 0f;
		}
		float num = q / p;
		if (p < 0f)
		{
			low = Mathf.Max(low, num);
		}
		else
		{
			high = Mathf.Min(high, num);
		}
		return low <= high;
	}

	private static void Quad(VertexHelper mesh, Vector2 a, Vector2 b, float width, Color32 color)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: 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_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: 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_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: 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_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: 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)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: 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_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: 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_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: 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_00df: Unknown result type (might be due to invalid IL or missing references)
		Vector2 val = b - a;
		Vector2 normalized = ((Vector2)(ref val)).normalized;
		if (!(((Vector2)(ref normalized)).sqrMagnitude < 0.1f))
		{
			Vector2 val2 = new Vector2(0f - normalized.y, normalized.x) * width * 0.5f;
			a -= normalized * 0.02f;
			b += normalized * 0.02f;
			int currentVertCount = mesh.currentVertCount;
			mesh.AddVert(Vector2.op_Implicit(a - val2), color, Vector4.op_Implicit(Vector2.zero));
			mesh.AddVert(Vector2.op_Implicit(a + val2), color, Vector4.op_Implicit(Vector2.zero));
			mesh.AddVert(Vector2.op_Implicit(b + val2), color, Vector4.op_Implicit(Vector2.zero));
			mesh.AddVert(Vector2.op_Implicit(b - val2), color, Vector4.op_Implicit(Vector2.zero));
			mesh.AddTriangle(currentVertCount, currentVertCount + 1, currentVertCount + 2);
			mesh.AddTriangle(currentVertCount, currentVertCount + 2, currentVertCount + 3);
		}
	}
}
public static class RoadMerge
{
	public static void Validate(RoadData data, long world)
	{
		if (data == null || data.world != world || data.version < 1 || data.version > 3 || data.lines == null || data.lines.Count > 50000 || data.erasures == null || data.restored == null || data.paints == null || data.erasures.Count > 100000 || data.restored.Count > 100000 || data.paints.Count > 100000)
		{
			throw new InvalidDataException("Invalid road data or wrong world.");
		}
		int num = 0;
		HashSet<string> hashSet = new HashSet<string>();
		foreach (RoadLine line in data.lines)
		{
			if (line == null || line.points == null || (line.kind != 0 && line.kind != 1) || (!string.IsNullOrEmpty(line.id) && (line.id.Length > 128 || !hashSet.Add(line.id))))
			{
				throw new InvalidDataException("Invalid or duplicate road identity.");
			}
			num += line.points.Count;
			if (num > 250000)
			{
				throw new InvalidDataException("Too many road points.");
			}
			foreach (RoadPoint point in line.points)
			{
				if (point == null || float.IsNaN(point.x) || float.IsNaN(point.z) || float.IsInfinity(point.x) || float.IsInfinity(point.z) || Math.Abs(point.x) > 20000f || Math.Abs(point.z) > 20000f)
				{
					throw new InvalidDataException("Invalid road coordinate.");
				}
			}
		}
		HashSet<string> hashSet2 = new HashSet<string>();
		foreach (RoadErase erasure in data.erasures)
		{
			if (erasure == null || !ValidId(erasure.id) || !ValidId(erasure.stroke) || !ValidId(erasure.line) || !hashSet2.Add(erasure.id) || double.IsNaN(erasure.from) || double.IsNaN(erasure.to) || double.IsInfinity(erasure.from) || double.IsInfinity(erasure.to) || erasure.from < 0.0 || erasure.to < erasure.from || erasure.to > 250000.0)
			{
				throw new InvalidDataException("Invalid road erasure.");
			}
		}
		HashSet<string> hashSet3 = new HashSet<string>();
		foreach (string item in data.restored)
		{
			if (!ValidId(item) || !hashSet3.Add(item))
			{
				throw new InvalidDataException("Invalid road undo.");
			}
		}
		HashSet<string> hashSet4 = new HashSet<string>();
		foreach (RoadPaint paint in data.paints)
		{
			if (paint == null || !ValidId(paint.id) || !ValidId(paint.line) || !hashSet4.Add(paint.id) || (paint.kind != 0 && paint.kind != 1) || paint.time < 0 || paint.time >= long.MaxValue || double.IsNaN(paint.from) || double.IsNaN(paint.to) || double.IsInfinity(paint.from) || double.IsInfinity(paint.to) || paint.from < 0.0 || paint.to < paint.from || paint.to > 250000.0)
			{
				throw new InvalidDataException("Invalid road material edit.");
			}
		}
	}

	private static bool ValidId(string value)
	{
		if (!string.IsNullOrEmpty(value))
		{
			return value.Length <= 128;
		}
		return false;
	}

	public static bool EnsureIds(RoadData data)
	{
		bool result = false;
		HashSet<string> hashSet = new HashSet<string>();
		foreach (RoadLine line in data.lines)
		{
			if (!string.IsNullOrEmpty(line.id))
			{
				hashSet.Add(line.id);
			}
		}
		foreach (RoadLine line2 in data.lines)
		{
			if (!string.IsNullOrEmpty(line2.id))
			{
				continue;
			}
			StringBuilder stringBuilder = new StringBuilder(line2.kind.ToString(CultureInfo.InvariantCulture));
			foreach (RoadPoint point in line2.points)
			{
				stringBuilder.Append('|').Append(point.x.ToString("R", CultureInfo.InvariantCulture)).Append(',')
					.Append(point.z.ToString("R", CultureInfo.InvariantCulture));
			}
			using (SHA256 sHA = SHA256.Create())
			{
				line2.id = "legacy-" + Convert.ToBase64String(sHA.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())));
			}
			string id = line2.id;
			int num = 1;
			while (!hashSet.Add(line2.id))
			{
				int num2 = ++num;
				line2.id = id + "-" + num2.ToString(CultureInfo.InvariantCulture);
			}
			result = true;
		}
		return result;
	}

	public static RoadData Merge(RoadData target, RoadData incoming, out int addedPoints)
	{
		Validate(target, target.world);
		Validate(incoming, target.world);
		RoadData roadData = new RoadData();
		roadData.world = target.world;
		RoadData roadData2 = roadData;
		Dictionary<string, RoadLine> dictionary = new Dictionary<string, RoadLine>();
		addedPoints = 0;
		foreach (RoadLine line in target.lines)
		{
			RoadLine item = Clone(line);
			roadData2.lines.Add(item);
		}
		EnsureIds(roadData2);
		foreach (RoadLine line2 in roadData2.lines)
		{
			if (!dictionary.ContainsKey(line2.id))
			{
				dictionary.Add(line2.id, line2);
			}
		}
		foreach (RoadLine line3 in incoming.lines)
		{
			RoadLine roadLine = Clone(line3);
			RoadData roadData3 = new RoadData();
			roadData3.lines.Add(roadLine);
			EnsureIds(roadData3);
			if (!dictionary.TryGetValue(roadLine.id, out var value))
			{
				roadData2.lines.Add(roadLine);
				dictionary.Add(roadLine.id, roadLine);
				addedPoints += roadLine.points.Count;
				continue;
			}
			if (value.kind != roadLine.kind)
			{
				throw new InvalidDataException("Conflicting road material.");
			}
			int num = Math.Min(value.points.Count, roadLine.points.Count);
			for (int i = 0; i < num; i++)
			{
				if (value.points[i].x != roadLine.points[i].x || value.points[i].z != roadLine.points[i].z)
				{
					throw new InvalidDataException("Conflicting road coordinates.");
				}
			}
			for (int j = value.points.Count; j < roadLine.points.Count; j++)
			{
				value.points.Add(roadLine.points[j]);
				addedPoints++;
			}
		}
		Dictionary<string, RoadErase> dictionary2 = new Dictionary<string, RoadErase>();
		RoadData[] array = new RoadData[2] { target, incoming };
		foreach (RoadData roadData4 in array)
		{
			foreach (RoadErase erasure in roadData4.erasures)
			{
				if (dictionary2.TryGetValue(erasure.id, out var value2))
				{
					if (value2.line != erasure.line || value2.stroke != erasure.stroke || value2.from != erasure.from || value2.to != erasure.to)
					{
						throw new InvalidDataException("Conflicting erasure identity.");
					}
					continue;
				}
				RoadErase roadErase = new RoadErase();
				roadErase.id = erasure.id;
				roadErase.stroke = erasure.stroke;
				roadErase.line = erasure.line;
				roadErase.from = erasure.from;
				roadErase.to = erasure.to;
				RoadErase roadErase2 = roadErase;
				dictionary2.Add(roadErase2.id, roadErase2);
				roadData2.erasures.Add(roadErase2);
			}
		}
		HashSet<string> hashSet = new HashSet<string>();
		RoadData[] array2 = new RoadData[2] { target, incoming };
		foreach (RoadData roadData5 in array2)
		{
			foreach (string item2 in roadData5.restored)
			{
				if (hashSet.Add(item2))
				{
					roadData2.restored.Add(item2);
				}
			}
		}
		Dictionary<string, RoadPaint> dictionary3 = new Dictionary<string, RoadPaint>();
		RoadData[] array3 = new RoadData[2] { target, incoming };
		foreach (RoadData roadData6 in array3)
		{
			foreach (RoadPaint paint in roadData6.paints)
			{
				if (dictionary3.TryGetValue(paint.id, out var value3))
				{
					if (value3.line != paint.line || value3.from != paint.from || value3.to != paint.to || value3.time != paint.time || value3.kind != paint.kind)
					{
						throw new InvalidDataException("Conflicting material edit identity.");
					}
					continue;
				}
				RoadPaint roadPaint = new RoadPaint();
				roadPaint.id = paint.id;
				roadPaint.line = paint.line;
				roadPaint.from = paint.from;
				roadPaint.to = paint.to;
				roadPaint.kind = paint.kind;
				roadPaint.time = paint.time;
				RoadPaint roadPaint2 = roadPaint;
				dictionary3.Add(roadPaint2.id, roadPaint2);
				roadData2.paints.Add(roadPaint2);
			}
		}
		Validate(roadData2, target.world);
		return roadData2;
	}

	private static RoadLine Clone(RoadLine line)
	{
		RoadLine roadLine = new RoadLine();
		roadLine.id = line.id;
		roadLine.kind = line.kind;
		RoadLine roadLine2 = roadLine;
		foreach (RoadPoint point in line.points)
		{
			roadLine2.points.Add(new RoadPoint(point.x, point.z));
		}
		return roadLine2;
	}
}
[Serializable]
public class RoadPoint
{
	public float x;

	public float z;

	public RoadPoint(float x, float z)
	{
		this.x = x;
		this.z = z;
	}
}
[Serializable]
public class RoadLine
{
	public string id;

	public int kind;

	public List<RoadPoint> points = new List<RoadPoint>();
}
[Serializable]
public class RoadErase
{
	public string id;

	public string stroke;

	public string line;

	public double from;

	public double to;
}
[Serializable]
public class RoadPaint
{
	public string id;

	public string line;

	public double from;

	public double to;

	public long time;

	public int kind;
}
[Serializable]
public class RoadData
{
	public int version = 3;

	public long world;

	public List<RoadLine> lines = new List<RoadLine>();

	public List<RoadErase> erasures = new List<RoadErase>();

	public List<string> restored = new List<string>();

	public List<RoadPaint> paints = new List<RoadPaint>();
}
public static class RoadModel
{
	public static double Distance(RoadPoint a, RoadPoint b)
	{
		double num = a.x - b.x;
		double num2 = a.z - b.z;
		return Math.Sqrt(num * num + num2 * num2);
	}

	public static RoadLine Add(RoadData data, RoadLine active, RoadPoint point, int kind, double maxGap)
	{
		if (active == null || active.kind != kind || active.points.Count == 0 || Distance(active.points[active.points.Count - 1], point) > maxGap)
		{
			RoadLine roadLine = new RoadLine();
			roadLine.kind = kind;
			roadLine.id = Guid.NewGuid().ToString("N");
			active = roadLine;
			data.lines.Add(active);
		}
		if (active.points.Count == 0 || Distance(active.points[active.points.Count - 1], point) >= 0.5)
		{
			active.points.Add(point);
		}
		return active;
	}

	public static bool DashVisible(double distance, double dash, double gap)
	{
		return distance % (dash + gap) < dash;
	}
}
public sealed class RoadPaintIndex
{
	private readonly Dictionary<string, List<RoadPaint>> paints = new Dictionary<string, List<RoadPaint>>();

	public RoadPaintIndex(RoadData data)
	{
		foreach (RoadPaint paint in data.paints)
		{
			if (!paints.TryGetValue(paint.line, out var value))
			{
				paints.Add(paint.line, value = new List<RoadPaint>());
			}
			value.Add(paint);
		}
	}

	public static int Compare(RoadPaint a, RoadPaint b)
	{
		if (a == null)
		{
			if (b != null)
			{
				return -1;
			}
			return 0;
		}
		if (b == null)
		{
			return 1;
		}
		int num = a.time.CompareTo(b.time);
		if (num == 0)
		{
			return StringComparer.Ordinal.Compare(a.id, b.id);
		}
		return num;
	}

	public RoadPaint Latest(string line, double parameter)
	{
		RoadPaint roadPaint = null;
		if (line != null && paints.TryGetValue(line, out var value))
		{
			foreach (RoadPaint item in value)
			{
				if (item.from <= parameter && item.to >= parameter && Compare(item, roadPaint) > 0)
				{
					roadPaint = item;
				}
			}
		}
		return roadPaint;
	}

	public int Kind(RoadLine line, double parameter)
	{
		return Latest(line.id, parameter)?.kind ?? line.kind;
	}

	public List<RoadInterval> Different(RoadLine line, double from, double to, int kind)
	{
		List<double> list = new List<double>();
		list.Add(from);
		list.Add(to);
		List<double> list2 = list;
		if (paints.TryGetValue(line.id, out var value))
		{
			foreach (RoadPaint item in value)
			{
				if (item.from > from && item.from < to)
				{
					list2.Add(item.from);
				}
				if (item.to > from && item.to < to)
				{
					list2.Add(item.to);
				}
			}
		}
		list2.Sort();
		List<RoadInterval> list3 = new List<RoadInterval>();
		if (from == to && Kind(line, from) != kind)
		{
			list3.Add(new RoadInterval(from, to));
		}
		for (int i = 1; i < list2.Count; i++)
		{
			if (list2[i] > list2[i - 1] && Kind(line, (list2[i] + list2[i - 1]) * 0.5) != kind)
			{
				list3.Add(new RoadInterval(list2[i - 1], list2[i]));
			}
		}
		return list3;
	}
}
public sealed class RoadNear
{
	public RoadLine line;

	public RoadPoint point;

	public double parameter;

	public double distance;

	public double dx;

	public double dz;
}
public sealed class RoadRenderPart
{
	public RoadPoint a;

	public RoadPoint b;

	public int kind;

	public double distance;

	public bool point;
}
public sealed class RoadNetwork
{
	private sealed class Section
	{
		public RoadLine line;

		public RoadPoint a;

		public RoadPoint b;

		public double from;

		public double to;
	}

	private struct ResolutionKey : IEquatable<ResolutionKey>
	{
		public string line;

		public double parameter;

		public double dx;

		public double dz;

		public float x;

		public float z;

		public bool Equals(ResolutionKey other)
		{
			if (line == other.line && parameter == other.parameter && dx == other.dx && dz == other.dz && x == other.x)
			{
				return z == other.z;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is ResolutionKey)
			{
				return Equals((ResolutionKey)obj);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (((((((((line.GetHashCode() * 397) ^ parameter.GetHashCode()) * 397) ^ x.GetHashCode()) * 397) ^ z.GetHashCode()) * 397) ^ dx.GetHashCode()) * 397) ^ dz.GetHashCode();
		}
	}

	private struct Resolution
	{
		public int kind;

		public bool canonical;
	}

	private readonly Dictionary<long, List<Section>> cells = new Dictionary<long, List<Section>>();

	private readonly Dictionary<string, int> ranks = new Dictionary<string, int>();

	private readonly double radius;

	private readonly RoadEraseIndex erased;

	private readonly RoadPaintIndex painted;

	private readonly RoadData data;

	private List<RoadRenderPart> renderParts;

	private readonly Dictionary<ResolutionKey, Resolution> resolutions = new Dictionary<ResolutionKey, Resolution>();

	public int ResolutionCount { get; private set; }

	public RoadNetwork(RoadData data, double radius)
	{
		this.data = data;
		this.radius = Math.Max(0.25, radius);
		RoadMerge.EnsureIds(data);
		erased = new RoadEraseIndex(data);
		painted = new RoadPaintIndex(data);
		List<RoadLine> list = new List<RoadLine>(data.lines);
		Dictionary<string, double> lengths = new Dictionary<string, double>();
		foreach (RoadLine item in list)
		{
			double num = 0.0;
			for (int i = 1; i < item.points.Count; i++)
			{
				num += RoadModel.Distance(item.points[i - 1], item.points[i]);
			}
			lengths[item.id] = num;
		}
		list.Sort(delegate(RoadLine roadLine2, RoadLine b)
		{
			int num6 = lengths[b.id].CompareTo(lengths[roadLine2.id]);
			return (num6 == 0) ? StringComparer.Ordinal.Compare(roadLine2.id, b.id) : num6;
		});
		for (int num2 = 0; num2 < list.Count; num2++)
		{
			RoadLine roadLine = list[num2];
			ranks[roadLine.id] = num2;
			if (roadLine.points.Count == 1)
			{
				Add(new Section
				{
					line = roadLine,
					a = roadLine.points[0],
					b = roadLine.points[0]
				});
			}
			for (int num3 = 0; num3 + 1 < roadLine.points.Count; num3++)
			{
				RoadPoint a = roadLine.points[Math.Max(0, num3 - 1)];
				RoadPoint roadPoint = roadLine.points[num3];
				RoadPoint roadPoint2 = roadLine.points[num3 + 1];
				RoadPoint d = roadLine.points[Math.Min(roadLine.points.Count - 1, num3 + 2)];
				int num4 = Math.Max(4, Math.Min(256, (int)Math.Ceiling(RoadModel.Distance(roadPoint, roadPoint2))));
				RoadPoint a2 = roadPoint;
				for (int num5 = 1; num5 <= num4; num5++)
				{
					RoadPoint roadPoint3 = RoadCurve.Sample(a, roadPoint, roadPoint2, d, (float)num5 / (float)num4);
					Add(new Section
					{
						line = roadLine,
						a = a2,
						b = roadPoint3,
						from = (double)num3 + ((double)num5 - 1.0) / (double)num4,
						to = (double)num3 + (double)num5 / (double)num4
					});
					a2 = roadPoint3;
				}
			}
		}
	}

	private static long Key(int x, int z)
	{
		return ((long)x << 32) ^ (uint)z;
	}

	private int Cell(double value)
	{
		return (int)Math.Floor(value / radius);
	}

	private void Add(Section section)
	{
		for (int i = Cell(Math.Min(section.a.x, section.b.x)); i <= Cell(Math.Max(section.a.x, section.b.x)); i++)
		{
			for (int j = Cell(Math.Min(section.a.z, section.b.z)); j <= Cell(Math.Max(section.a.z, section.b.z)); j++)
			{
				long key = Key(i, j);
				if (!cells.TryGetValue(key, out var value))
				{
					cells.Add(key, value = new List<Section>());
				}
				value.Add(section);
			}
		}
	}

	private IEnumerable<Section> Around(RoadPoint point, double distance)
	{
		HashSet<Section> seen = new HashSet<Section>();
		for (int x = Cell((double)point.x - distance); x <= Cell((double)point.x + distance); x++)
		{
			for (int z = Cell((double)point.z - distance); z <= Cell((double)point.z + distance); z++)
			{
				if (!cells.TryGetValue(Key(x, z), out var list))
				{
					continue;
				}
				foreach (Section section in list)
				{
					if (seen.Add(section))
					{
						yield return section;
					}
				}
			}
		}
	}

	private static RoadNear Project(Section section, RoadPoint point)
	{
		double num = section.b.x - section.a.x;
		double num2 = section.b.z - section.a.z;
		double num3 = num * num + num2 * num2;
		double num4 = ((num3 < 1E-12) ? 0.0 : Math.Max(0.0, Math.Min(1.0, ((double)(point.x - section.a.x) * num + (double)(point.z - section.a.z) * num2) / num3)));
		RoadPoint roadPoint = new RoadPoint((float)((double)section.a.x + num * num4), (float)((double)section.a.z + num2 * num4));
		RoadNear roadNear = new RoadNear();
		roadNear.line = section.line;
		roadNear.point = roadPoint;
		roadNear.parameter = section.from + (section.to - section.from) * num4;
		roadNear.distance = RoadModel.Distance(roadPoint, point);
		roadNear.dx = num;
		roadNear.dz = num2;
		return roadNear;
	}

	public RoadNear Nearest(RoadPoint point)
	{
		RoadNear roadNear = null;
		foreach (Section item in Around(point, radius))
		{
			RoadNear roadNear2 = Project(item, point);
			if (!(roadNear2.distance > radius) && (roadNear == null || roadNear2.distance < roadNear.distance - 1E-06 || (Math.Abs(roadNear2.distance - roadNear.distance) <= 1E-06 && ranks[roadNear2.line.id] < ranks[roadNear.line.id])))
			{
				roadNear = roadNear2;
			}
		}
		if (roadNear == null || erased.IsErased(roadNear.line.id, roadNear.parameter))
		{
			return null;
		}
		return roadNear;
	}

	public bool Resolve(RoadLine line, double parameter, RoadPoint point, double dx, double dz, out int kind)
	{
		ResolutionKey key = new ResolutionKey
		{
			line = line.id,
			parameter = parameter,
			x = point.x,
			z = point.z,
			dx = dx,
			dz = dz
		};
		if (resolutions.TryGetValue(key, out var value))
		{
			kind = value.kind;
			return value.canonical;
		}
		bool flag = ResolveUncached(line, parameter, point, dx, dz, out kind);
		if (resolutions.Count < 32768)
		{
			resolutions[key] = new Resolution
			{
				kind = kind,
				canonical = flag
			};
		}
		return flag;
	}

	private bool ResolveUncached(RoadLine line, double parameter, RoadPoint point, double dx, double dz, out int kind)
	{
		ResolutionCount++;
		kind = line.kind;
		RoadPaint roadPaint = painted.Latest(line.id, parameter);
		bool flag = true;
		Dictionary<string, RoadNear> dictionary = new Dictionary<string, RoadNear>();
		foreach (Section item in Around(point, radius))
		{
			if (item.line.id == line.id)
			{
				continue;
			}
			RoadNear roadNear = Project(item, point);
			if (!(roadNear.distance > radius) && !erased.IsErased(roadNear.line.id, roadNear.parameter))
			{
				double num = dx * dx + dz * dz;
				double num2 = roadNear.dx * roadNear.dx + roadNear.dz * roadNear.dz;
				if ((!(num > 1E-10) || !(num2 > 1E-10) || !(Math.Abs(dx * roadNear.dx + dz * roadNear.dz) < 0.95 * Math.Sqrt(num * num2))) && (!dictionary.TryGetValue(roadNear.line.id, out var value) || roadNear.distance < value.distance))
				{
					dictionary[roadNear.line.id] = roadNear;
				}
			}
		}
		foreach (RoadNear value2 in dictionary.Values)
		{
			double num3 = Math.Sqrt(value2.dx * value2.dx + value2.dz * value2.dz);
			double num4 = ((num3 < 1E-08) ? 0.0 : (((double)(point.x - value2.point.x) * value2.dx + (double)(point.z - value2.point.z) * value2.dz) / num3));
			if ((!(value2.parameter < 1E-08) || !(num4 < -0.05)) && (!(value2.parameter > (double)(value2.line.points.Count - 1) - 1E-08) || !(num4 > 0.05)))
			{
				if (flag && ranks[value2.line.id] < ranks[line.id] && Resolve(value2.line, value2.parameter, value2.point, value2.dx, value2.dz, out var _))
				{
					flag = false;
				}
				kind = Math.Max(kind, value2.line.kind);
				RoadPaint roadPaint2 = painted.Latest(value2.line.id, value2.parameter);
				if (RoadPaintIndex.Compare(roadPaint2, roadPaint) > 0)
				{
					roadPaint = roadPaint2;
				}
			}
		}
		if (roadPaint != null)
		{
			kind = roadPaint.kind;
		}
		return flag;
	}

	public IList<RoadRenderPart> GetRenderParts()
	{
		if (renderParts != null)
		{
			return renderParts;
		}
		renderParts = new List<RoadRenderPart>();
		foreach (RoadLine line in data.lines)
		{
			double num = 0.0;
			if (line.points.Count == 1 && !erased.IsErased(line.id, 0.0) && Resolve(line, 0.0, line.points[0], 0.0, 0.0, out var kind))
			{
				renderParts.Add(new RoadRenderPart
				{
					a = line.points[0],
					b = line.points[0],
					kind = kind,
					point = true
				});
			}
			for (int i = 0; i + 1 < line.points.Count; i++)
			{
				RoadPoint a = line.points[Math.Max(0, i - 1)];
				RoadPoint roadPoint = line.points[i];
				RoadPoint roadPoint2 = line.points[i + 1];
				RoadPoint d = line.points[Math.Min(line.points.Count - 1, i + 2)];
				int num2 = Math.Max(4, Math.Min(256, (int)Math.Ceiling(RoadModel.Distance(roadPoint, roadPoint2) * 2.0)));
				RoadPoint roadPoint3 = roadPoint;
				for (int j = 1; j <= num2; j++)
				{
					RoadPoint roadPoint4 = RoadCurve.Sample(a, roadPoint, roadPoint2, d, (float)j / (float)num2);
					double num3 = RoadModel.Distance(roadPoint3, roadPoint4);
					RoadPoint point = new RoadPoint((roadPoint3.x + roadPoint4.x) * 0.5f, (roadPoint3.z + roadPoint4.z) * 0.5f);
					if (Resolve(line, (double)i + ((double)j - 0.5) / (double)num2, point, roadPoint4.x - roadPoint3.x, roadPoint4.z - roadPoint3.z, out var _))
					{
						double num4 = (double)i + ((double)j - 1.0) / (double)num2;
						double num5 = (double)i + (double)j / (double)num2;
						foreach (RoadInterval item in erased.Visible(line.id, num4, num5))
						{
							List<double> list = new List<double>();
							list.Add(item.from);
							list.Add(item.to);
							List<double> list2 = list;
							foreach (RoadPaint paint in data.paints)
							{
								if (paint.line == line.id)
								{
									if (paint.from > item.from && paint.from < item.to)
									{
										list2.Add(paint.from);
									}
									if (paint.to > item.from && paint.to < item.to)
									{
										list2.Add(paint.to);
									}
								}
							}
							list2.Sort();
							for (int k = 1; k < list2.Count; k++)
							{
								if (!(list2[k] <= list2[k - 1]))
								{
									double num6 = (list2[k - 1] - num4) / (num5 - num4);
									double num7 = (list2[k] - num4) / (num5 - num4);
									RoadPoint roadPoint5 = new RoadPoint((float)((double)roadPoint3.x + (double)(roadPoint4.x - roadPoint3.x) * num6), (float)((double)roadPoint3.z + (double)(roadPoint4.z - roadPoint3.z) * num6));
									RoadPoint roadPoint6 = new RoadPoint((float)((double)roadPoint3.x + (double)(roadPoint4.x - roadPoint3.x) * num7), (float)((double)roadPoint3.z + (double)(roadPoint4.z - roadPoint3.z) * num7));
									RoadPoint point2 = new RoadPoint((roadPoint5.x + roadPoint6.x) * 0.5f, (roadPoint5.z + roadPoint6.z) * 0.5f);
									if (Resolve(line, (list2[k - 1] + list2[k]) * 0.5, point2, roadPoint4.x - roadPoint3.x, roadPoint4.z - roadPoint3.z, out var kind3))
									{
										renderParts.Add(new RoadRenderPart
										{
											a = roadPoint5,
											b = roadPoint6,
											kind = kind3,
											distance = num + num3 * num6
										});
									}
								}
							}
						}
					}
					num += num3;
					roadPoint3 = roadPoint4;
				}
			}
		}
		return renderParts;
	}

	public bool Paint(RoadPoint center, double brushRadius, int kind)
	{
		Dictionary<RoadLine, List<RoadInterval>> dictionary = new Dictionary<RoadLine, List<RoadInterval>>();
		foreach (Section item in Around(center, brushRadius))
		{
			if (!RoadEditing.CircleHit(item.a, item.b, center, brushRadius, out var from, out var to))
			{
				continue;
			}
			double num = item.from + (item.to - item.from) * from;
			double num2 = item.from + (item.to - item.from) * to;
			if (!dictionary.TryGetValue(item.line, out var value))
			{
				dictionary.Add(item.line, value = new List<RoadInterval>());
			}
			if (num == num2 && item.from == item.to && !erased.IsErased(item.line.id, num))
			{
				value.AddRange(painted.Different(item.line, num, num2, kind));
				continue;
			}
			foreach (RoadInterval item2 in erased.Visible(item.line.id, num, num2))
			{
				value.AddRange(painted.Different(item.line, item2.from, item2.to, kind));
			}
		}
		long num3 = DateTime.UtcNow.Ticks;
		foreach (RoadPaint paint in data.paints)
		{
			num3 = Math.Max(num3, paint.time + 1);
		}
		bool result = false;
		foreach (KeyValuePair<RoadLine, List<RoadInterval>> item3 in dictionary)
		{
			RoadEraseIndex.Combine(item3.Value);
			foreach (RoadInterval item4 in item3.Value)
			{
				data.paints.Add(new RoadPaint
				{
					id = Guid.NewGuid().ToString("N"),
					line = item3.Key.id,
					from = item4.from,
					to = item4.to,
					kind = kind,
					time = num3
				});
				result = true;
			}
		}
		return result;
	}
}
public sealed class RoadRecorder
{
	private RoadLine active;

	private RoadPoint anchor;

	private int lastKind;

	public void Reset()
	{
		active = null;
		anchor = null;
	}

	public bool Record(RoadData data, RoadPoint point, int kind, double maxGap, double radius, RoadNetwork cachedNetwork = null)
	{
		RoadNetwork roadNetwork = cachedNetwork ?? new RoadNetwork(data, radius);
		RoadNear roadNear = roadNetwork.Nearest(point);
		if (roadNear != null)
		{
			bool result = roadNetwork.Paint(roadNear.point, radius, kind);
			if (active != roadNear.line || active.kind != kind)
			{
				active = null;
			}
			anchor = roadNear.point;
			lastKind = kind;
			return result;
		}
		if (active == null || active.kind != kind || RoadModel.Distance(active.points[active.points.Count - 1], point) > maxGap)
		{
			active = null;
			if (anchor != null && lastKind == kind && RoadModel.Distance(anchor, point) <= maxGap)
			{
				active = RoadModel.Add(data, null, new RoadPoint(anchor.x, anchor.z), kind, maxGap);
			}
		}
		active = RoadModel.Add(data, active, point, kind, maxGap);
		anchor = null;
		lastKind = kind;
		return true;
	}
}
public static class RoadStore
{
	public static RoadData Read(string path, long world, out bool legacy)
	{
		JObject val = JObject.Parse(File.ReadAllText(path));
		legacy = val["lines"] == null;
		if (val["world"] == null || Extensions.Value<long>((IEnumerable<JToken>)val["world"]) != world || val["version"] == null || Extensions.Value<int>((IEnumerable<JToken>)val["version"]) < 1 || Extensions.Value<int>((IEnumerable<JToken>)val["version"]) > 3)
		{
			throw new InvalidDataException("Unsupported road data or wrong world.");
		}
		RoadData roadData = ((JToken)val).ToObject<RoadData>();
		if (legacy)
		{
			roadData.lines = new List<RoadLine>();
		}
		if (roadData.lines == null)
		{
			throw new InvalidDataException("Missing road list.");
		}
		foreach (RoadLine line in roadData.lines)
		{
			if (line == null || line.points == null || (line.kind != 0 && line.kind != 1))
			{
				throw new InvalidDataException("Invalid road line.");
			}
			foreach (RoadPoint point in line.points)
			{
				if (point == null || float.IsNaN(point.x) || float.IsNaN(point.z) || float.IsInfinity(point.x) || float.IsInfinity(point.z) || Math.Abs(point.x) > 20000f || Math.Abs(point.z) > 20000f)
				{
					throw new InvalidDataException("Invalid road point.");
				}
			}
		}
		RoadMerge.Validate(roadData, world);
		roadData.version = 3;
		return roadData;
	}

	public static void Save(string path, RoadData data)
	{
		RoadMerge.Validate(data, data.world);
		WriteJson(path, JsonConvert.SerializeObject((object)data, (Formatting)1));
	}

	public static void WriteJson(string path, string json)
	{
		Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
		byte[] bytes = Encoding.UTF8.GetBytes(json);
		using (FileStream fileStream = new FileStream(path + ".tmp", FileMode.Create, FileAccess.Write, FileShare.None))
		{
			fileStream.Write(bytes, 0, bytes.Length);
			fileStream.Flush(flushToDisk: true);
		}
		if (File.Exists(path))
		{
			File.Replace(path + ".t