Decompiled source of FehuRoads v420.2.0

FehuRoads.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Forteca.FehuRoads.Commands;
using Forteca.FehuRoads.Core;
using Forteca.FehuRoads.Detection;
using Forteca.FehuRoads.Integration;
using Forteca.FehuRoads.Networking;
using Forteca.FehuRoads.Persistence;
using Forteca.FehuRoads.Plugin;
using Forteca.FehuRoads.Rendering;
using Forteca.FehuRoadsGrid;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("FehuRoads")]
[assembly: AssemblyFileVersion("420.2.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = "")]
[assembly: AssemblyVersion("420.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Forteca.FehuRoadsGrid
{
	public struct RoadClanAffiliation
	{
		public string TerritoryId;

		public int TerritoryGridX;

		public int TerritoryGridY;

		public bool IsClaimed;

		public int ClanId;

		public string ClanName;

		public Color ClanColor;
	}
	public static class ClanAffiliationService
	{
		private static object Get(object value, string name)
		{
			FieldInfo field = value.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (!(field != null))
			{
				return value.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(value, null);
			}
			return field.GetValue(value);
		}

		public static bool TryGetAffiliation(Vector3 worldPosition, out RoadClanAffiliation affiliation)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			affiliation = default(RoadClanAffiliation);
			if (!Chainloader.PluginInfos.TryGetValue("com.forteca.clanwarfare", out var value) || (Object)(object)value.Instance == (Object)null)
			{
				return false;
			}
			try
			{
				Assembly assembly = ((object)value.Instance).GetType().Assembly;
				Type type = assembly.GetType("FortecaClanWarfare.Core.WarfareManager", throwOnError: true);
				FieldInfo field = type.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				object obj = ((field != null) ? field.GetValue(null) : type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null, null));
				object obj2 = ((obj == null) ? null : Get(obj, "Data"));
				if (obj2 == null)
				{
					return false;
				}
				object obj3 = assembly.GetType("FortecaClanWarfare.Core.GridExtensions", throwOnError: true).GetMethod("WorldToGrid", new Type[1] { typeof(Vector3) }).Invoke(null, new object[1] { worldPosition });
				object obj4 = obj2.GetType().GetMethod("GetTerritory", new Type[1] { obj3.GetType() }).Invoke(obj2, new object[1] { obj3 });
				if (obj4 == null)
				{
					return false;
				}
				object obj5 = Get(obj4, "GridPosition");
				affiliation.TerritoryId = (string)obj2.GetType().GetMethod("GridToKey", new Type[1] { obj5.GetType() }).Invoke(null, new object[1] { obj5 });
				affiliation.TerritoryGridX = (int)Get(obj4, "GridX");
				affiliation.TerritoryGridY = (int)Get(obj4, "GridY");
				affiliation.ClanId = (int)Get(obj4, "OwnerClanId");
				affiliation.IsClaimed = affiliation.ClanId != 0;
				affiliation.ClanName = "";
				affiliation.ClanColor = Color.clear;
				if (!affiliation.IsClaimed)
				{
					return true;
				}
				object obj6 = obj2.GetType().GetMethod("GetClan", new Type[1] { typeof(int) }).Invoke(obj2, new object[1] { affiliation.ClanId });
				if (obj6 == null)
				{
					return true;
				}
				affiliation.ClanId = (int)Get(obj6, "ClanId");
				affiliation.ClanName = ((string)Get(obj6, "Name")) ?? "";
				affiliation.ClanColor = (Color)Get(obj6, "Color");
				return true;
			}
			catch (Exception ex)
			{
				if (GridPlugin.Instance != null)
				{
					GridPlugin.Instance.LogWarning("FCW affiliation unavailable: " + ex.GetBaseException().Message);
				}
				return false;
			}
		}
	}
	internal sealed class GridNetworkManager
	{
		private sealed class RateState
		{
			internal float WindowStart;

			internal int Cells;
		}

		private readonly GridPlugin _plugin;

		private readonly HashSet<RoadChunkCoord> _dirty = new HashSet<RoadChunkCoord>();

		private readonly HashSet<long> _compatiblePeers = new HashSet<long>();

		private readonly Dictionary<long, RateState> _rates = new Dictionary<long, RateState>();

		private readonly RpcBindings _bindings = new RpcBindings();

		private bool _registered;

		private float _nextDelta;

		internal GridNetworkManager(GridPlugin plugin)
		{
			_plugin = plugin;
			plugin.Roads.ChunkChanged += OnChunkChanged;
		}

		private void OnChunkChanged(RoadChunkCoord coord, uint revision)
		{
			if (_plugin.WorldReady)
			{
				_dirty.Add(coord);
			}
		}

		internal void Update()
		{
			if (!_bindings.IsCurrent(ZRoutedRpc.instance))
			{
				Reset();
			}
			if (!_registered && ZRoutedRpc.instance != null)
			{
				_bindings.Register(ZRoutedRpc.instance, "FehuRoads_Request", OnSnapshotRequest);
				_bindings.Register(ZRoutedRpc.instance, "FehuRoads_Update", OnRoadUpdate);
				_registered = true;
				_plugin.LogInfo("[FehuRoadsGrid] Protocol registered version=" + 1);
			}
			if (!_registered || !_plugin.WorldReady || _dirty.Count == 0 || Time.time < _nextDelta)
			{
				return;
			}
			_compatiblePeers.RemoveWhere((long id) => ZNet.instance.GetPeer(id) == null);
			List<long> list = new List<long>();
			foreach (long key in _rates.Keys)
			{
				if (key != 0L && ZNet.instance.GetPeer(key) == null)
				{
					list.Add(key);
				}
			}
			foreach (long item in list)
			{
				_rates.Remove(item);
			}
			_nextDelta = Time.time + 0.25f;
			int num = 0;
			foreach (long compatiblePeer in _compatiblePeers)
			{
				foreach (RoadChunkCoord item2 in _dirty)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(compatiblePeer, "FehuRoads_Chunk", new object[1] { RoadProtocol.EncodeChunk(_plugin.WorldUid, _plugin.Roads.GetChunk(item2)) });
					num++;
				}
			}
			_plugin.LogInfo("[FehuRoadsGrid] Delta broadcast chunks=" + _dirty.Count + " clients=" + _compatiblePeers.Count + " packets=" + num);
			_dirty.Clear();
		}

		private void OnSnapshotRequest(long sender, ZPackage package)
		{
			if (_plugin.WorldReady && ZNet.instance.GetPeer(sender) != null && RoadProtocol.ReadAndValidateHeader(package, _plugin.WorldUid))
			{
				_compatiblePeers.Add(sender);
				SendSnapshot(sender);
			}
		}

		private void OnRoadUpdate(long sender, ZPackage package)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (_plugin.WorldReady && RoadProtocol.TryDecodeUpdate(package, _plugin.WorldUid, out var cells) && TryGetConnectedPlayerPosition(sender, out var position) && ConsumeRate(sender, cells.Length))
			{
				ApplyValidated(sender, cells, position);
			}
		}

		internal void ReceiveLocal(IList<KeyValuePair<long, RoadType>> cells)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (_plugin.WorldReady && !ZNet.instance.IsDedicated() && !((Object)(object)Player.m_localPlayer == (Object)null) && cells != null && cells.Count >= 1 && cells.Count <= 512 && ConsumeRate(0L, cells.Count))
			{
				ApplyValidated(0L, cells, ((Component)Player.m_localPlayer).transform.position);
			}
		}

		private void ApplyValidated(long sender, IList<KeyValuePair<long, RoadType>> cells, Vector3 playerPosition)
		{
			//IL_0064: 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)
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			foreach (KeyValuePair<long, RoadType> cell in cells)
			{
				RoadDatabase.Decode(cell.Key, out var x, out var z);
				if (x < -12000 || x > 12000 || z < -12000 || z > 12000)
				{
					num3++;
					continue;
				}
				float num7 = (float)x - playerPosition.x;
				float num8 = (float)z - playerPosition.z;
				if (num7 * num7 + num8 * num8 > 1600f)
				{
					num4++;
				}
				else if (cell.Value != RoadType.None && cell.Value != RoadType.Dirt && cell.Value != RoadType.Paved)
				{
					num5++;
				}
				else if ((cell.Value == RoadType.Paved && !_plugin.StoneRoadsEnabled) || (cell.Value == RoadType.Dirt && !_plugin.DirtRoadsEnabled))
				{
					num6++;
				}
				else if (_plugin.Roads.Set(x, z, cell.Value))
				{
					num++;
				}
				else
				{
					num2++;
				}
			}
			_plugin.LogInfo("[FehuRoadsGrid] Road update applied peer=" + sender + " requested=" + cells.Count + " changed=" + num + " duplicate=" + num2 + " outsideWorld=" + num3 + " outsideRange=" + num4 + " invalidType=" + num5 + " disabledType=" + num6);
		}

		internal void Reset()
		{
			_bindings.Clear();
			_registered = false;
			_dirty.Clear();
			_compatiblePeers.Clear();
			_rates.Clear();
			_nextDelta = 0f;
		}

		internal void Dispose()
		{
			Reset();
			_plugin.Roads.ChunkChanged -= OnChunkChanged;
		}

		private bool ConsumeRate(long sender, int count)
		{
			if (!_rates.TryGetValue(sender, out var value))
			{
				value = new RateState
				{
					WindowStart = Time.time
				};
				_rates[sender] = value;
			}
			if (Time.time - value.WindowStart >= 1f)
			{
				value.WindowStart = Time.time;
				value.Cells = 0;
			}
			if (value.Cells + count > 2048)
			{
				_plugin.LogWarning("[FehuRoadsGrid] Road update rate rejected peer=" + sender);
				return false;
			}
			value.Cells += count;
			return true;
		}

		private static bool TryGetConnectedPlayerPosition(long sender, out Vector3 position)
		{
			//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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			position = Vector3.zero;
			if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null)
			{
				return false;
			}
			ZNetPeer peer = ZNet.instance.GetPeer(sender);
			if (peer == null)
			{
				return false;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID);
			if (zDO == null)
			{
				return false;
			}
			position = zDO.GetPosition();
			return true;
		}

		private void SendSnapshot(long peerId)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "FehuRoads_Begin", new object[1] { RoadProtocol.Header(_plugin.WorldUid) });
			foreach (RoadChunkData chunk in _plugin.Roads.Chunks)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "FehuRoads_Chunk", new object[1] { RoadProtocol.EncodeChunk(_plugin.WorldUid, chunk) });
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "FehuRoads_End", new object[1] { RoadProtocol.Header(_plugin.WorldUid) });
			_plugin.LogInfo("[FehuRoadsGrid] Snapshot sent peer=" + peerId + " chunks=" + _plugin.Roads.ChunkCount + " cells=" + _plugin.Roads.Count);
		}
	}
	public sealed class GridPlugin
	{
		private sealed class PendingTerrainScan
		{
			internal TerrainComp Comp;

			internal float DueTime;

			internal int DueFrame;

			internal string Reason;
		}

		private sealed class PendingTerrainHint
		{
			internal int X;

			internal int Z;

			internal float DueTime;

			internal int Attempts;
		}

		internal static GridPlugin Instance;

		private readonly ManualLogSource _logger;

		private ZNet _session;

		private bool _loadFailed;

		private RoadDatabase _roads;

		private TerrainRoadDetector _detector;

		private RoadPersistence _store;

		private GridNetworkManager _network;

		private RoadConnectivityService _connectivity;

		private ConfigEntry<bool> _stoneRoadsEnabled;

		private ConfigEntry<bool> _dirtRoadsEnabled;

		private ConfigEntry<bool> _legacyStoneBackfill;

		private ConfigEntry<bool> _legacyDirtBackfill;

		private readonly Queue<TerrainComp> _scanQueue = new Queue<TerrainComp>();

		private readonly HashSet<int> _queuedTerrain = new HashSet<int>();

		private readonly Dictionary<int, PendingTerrainScan> _pendingScans = new Dictionary<int, PendingTerrainScan>();

		private readonly Dictionary<long, PendingTerrainHint> _pendingHints = new Dictionary<long, PendingTerrainHint>();

		private bool _dirty;

		private float _nextSave;

		private string _worldKey;

		internal RoadDatabase Roads => _roads;

		internal bool WorldReady
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null && _session == ZNet.instance && ZNet.instance.IsServer() && ZNet.World != null)
				{
					return _worldKey == ZNet.instance.GetWorldUID().ToString("X");
				}
				return false;
			}
		}

		internal long WorldUid
		{
			get
			{
				if (!WorldReady)
				{
					return 0L;
				}
				return ZNet.instance.GetWorldUID();
			}
		}

		internal bool StoneRoadsEnabled
		{
			get
			{
				if (_stoneRoadsEnabled != null)
				{
					return _stoneRoadsEnabled.Value;
				}
				return true;
			}
		}

		internal bool DirtRoadsEnabled
		{
			get
			{
				if (_dirtRoadsEnabled != null)
				{
					return _dirtRoadsEnabled.Value;
				}
				return false;
			}
		}

		internal bool LegacyStoneBackfill
		{
			get
			{
				if (_legacyStoneBackfill != null)
				{
					return _legacyStoneBackfill.Value;
				}
				return true;
			}
		}

		internal bool LegacyDirtBackfill
		{
			get
			{
				if (_legacyDirtBackfill != null)
				{
					return _legacyDirtBackfill.Value;
				}
				return false;
			}
		}

		internal GridPlugin(ConfigFile config, ManualLogSource logger)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			_logger = logger;
			ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "forteca.fehuroads.grid.cfg"), false);
			val.SaveOnConfigSet = false;
			Instance = this;
			_roads = new RoadDatabase();
			_roads.Changed += OnRoadChanged;
			_stoneRoadsEnabled = BindLegacy(config, val, "Road Types", "StoneRoadsEnabled", fallback: true, "Track PAVED stone roads.");
			_dirtRoadsEnabled = BindLegacy(config, val, "Road Types", "DirtRoadsEnabled", fallback: false, "Track DIRT roads created while FehuRoads is active.");
			_legacyStoneBackfill = BindLegacy(config, val, "Legacy Backfill", "LegacyStoneBackfill", fallback: true, "Discover existing PAVED terrain when a server TerrainComp loads.");
			_legacyDirtBackfill = BindLegacy(config, val, "Legacy Backfill", "LegacyDirtBackfill", fallback: false, "Discover existing DIRT terrain when a server TerrainComp loads. Disabled by default to prevent clutter.");
			_detector = new TerrainRoadDetector(_roads);
			_network = new GridNetworkManager(this);
			_connectivity = new RoadConnectivityService(_roads);
			_logger.LogInfo((object)"[FehuRoads] Server module initialized version=420.2.0");
			_logger.LogInfo((object)"[FehuRoadsGrid] Terrain hooks installed methods=TerrainComp.DoOperation,TerrainComp.Awake");
		}

		internal void Update()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZNet.World == null)
			{
				EndWorld();
				return;
			}
			EnsureWorld();
			ProcessPendingHints();
			ProcessPendingScans();
			ProcessOneBackfill();
			_network.Update();
			if (_dirty && _store != null && Time.time >= _nextSave)
			{
				Save();
			}
		}

		internal static ConfigEntry<bool> BindLegacy(ConfigFile current, ConfigFile legacy, string section, string key, bool fallback, string description)
		{
			return current.Bind<bool>(section, key, legacy.Bind<bool>(section, key, fallback, (ConfigDescription)null).Value, description);
		}

		private void EnsureWorld()
		{
			string text = ZNet.instance.GetWorldUID().ToString("X");
			if (!(text == _worldKey) || _session != ZNet.instance)
			{
				EndWorld();
				_session = ZNet.instance;
				_worldKey = text;
				_roads.Clear();
				_pendingScans.Clear();
				_pendingHints.Clear();
				_store = new RoadPersistence(Path.Combine(Paths.ConfigPath, "FehuRoads"), text);
				try
				{
					_store.Load(_roads);
				}
				catch (Exception ex)
				{
					_loadFailed = true;
					_logger.LogError((object)("Road database load failed; writes blocked to preserve original: " + ex));
				}
				_dirty = false;
				_logger.LogInfo((object)("[FehuRoadsGrid] World initialized uid=" + text));
				_logger.LogInfo((object)("[FehuRoadsGrid] Loaded chunks=" + _roads.ChunkCount + " cells=" + _roads.Count));
				TerrainComp[] array = Object.FindObjectsOfType<TerrainComp>();
				foreach (TerrainComp comp in array)
				{
					QueueScan(comp);
				}
			}
		}

		private void OnRoadChanged(RoadCell cell, RoadType type)
		{
			_dirty = true;
			_nextSave = Time.time + 5f;
		}

		private void Save()
		{
			if (_loadFailed)
			{
				return;
			}
			try
			{
				_store.Save(_roads);
				_dirty = false;
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Road database save failed: " + ex));
				_nextSave = Time.time + 30f;
			}
		}

		internal void EndWorld()
		{
			if (_dirty && _store != null)
			{
				Save();
			}
			_worldKey = null;
			_session = null;
			_store = null;
			_dirty = false;
			_loadFailed = false;
			_pendingScans.Clear();
			_pendingHints.Clear();
			_scanQueue.Clear();
			_queuedTerrain.Clear();
			_network.Reset();
			_roads.Clear();
		}

		internal void Dispose()
		{
			EndWorld();
			_roads.Changed -= OnRoadChanged;
			_network.Dispose();
			Instance = null;
		}

		internal void ReceiveLocal(IList<KeyValuePair<long, RoadType>> cells)
		{
			_network.ReceiveLocal(cells);
		}

		internal void ScheduleAuthoritativeScan(TerrainComp comp, float delay, string reason)
		{
			if (!WorldReady || (Object)(object)comp == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)comp).GetInstanceID();
			float num = Time.time + Mathf.Max(0f, delay);
			int num2 = Time.frameCount + 1;
			if (_pendingScans.TryGetValue(instanceID, out var value))
			{
				value.DueTime = Mathf.Max(value.DueTime, num);
				value.DueFrame = Math.Max(value.DueFrame, num2);
				if (reason == "server-operation")
				{
					value.Reason = reason;
				}
			}
			else
			{
				_pendingScans[instanceID] = new PendingTerrainScan
				{
					Comp = comp,
					DueTime = num,
					DueFrame = num2,
					Reason = reason
				};
			}
		}

		internal bool QueueTerrainHint(int x, int z)
		{
			if (!WorldReady)
			{
				return false;
			}
			long key = RoadDatabase.Key(x, z);
			if (_pendingHints.TryGetValue(key, out var value))
			{
				value.DueTime = Time.time + 0.08f;
				return false;
			}
			_pendingHints[key] = new PendingTerrainHint
			{
				X = x,
				Z = z,
				DueTime = Time.time + 0.08f
			};
			return true;
		}

		private void ProcessPendingHints()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			if (!WorldReady || _pendingHints.Count == 0)
			{
				return;
			}
			List<long> list = new List<long>();
			foreach (KeyValuePair<long, PendingTerrainHint> pendingHint in _pendingHints)
			{
				if (pendingHint.Value.DueTime <= Time.time)
				{
					list.Add(pendingHint.Key);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			HashSet<TerrainComp> hashSet = new HashSet<TerrainComp>();
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			foreach (long item in list)
			{
				PendingTerrainHint pendingTerrainHint = _pendingHints[item];
				TerrainComp val = TerrainComp.FindTerrainCompiler(new Vector3((float)pendingTerrainHint.X, 0f, (float)pendingTerrainHint.Z));
				if ((Object)(object)val != (Object)null)
				{
					hashSet.Add(val);
					_pendingHints.Remove(item);
					num++;
				}
				else if (++pendingTerrainHint.Attempts >= 3)
				{
					_pendingHints.Remove(item);
					num3++;
				}
				else
				{
					pendingTerrainHint.DueTime = Time.time + 0.08f;
					num2++;
				}
				if (++num4 >= 512)
				{
					break;
				}
			}
			foreach (TerrainComp item2 in hashSet)
			{
				ScheduleAuthoritativeScan(item2, 0f, "client-hint-fallback");
			}
			_logger.LogInfo((object)("[FehuRoadsGrid] Terrain hint resolve positions=" + num4 + " resolved=" + num + " terrainComps=" + hashSet.Count + " retry=" + num2 + " dropped=" + num3));
		}

		private void ProcessPendingScans()
		{
			if (!WorldReady || _pendingScans.Count == 0)
			{
				return;
			}
			List<int> list = new List<int>();
			foreach (KeyValuePair<int, PendingTerrainScan> pendingScan in _pendingScans)
			{
				if (pendingScan.Value.DueTime <= Time.time && pendingScan.Value.DueFrame <= Time.frameCount)
				{
					list.Add(pendingScan.Key);
				}
			}
			int num = 0;
			foreach (int item in list)
			{
				PendingTerrainScan pendingTerrainScan = _pendingScans[item];
				_pendingScans.Remove(item);
				if ((Object)(object)pendingTerrainScan.Comp == (Object)null)
				{
					continue;
				}
				int logged = 0;
				TerrainScanResult terrainScanResult = _detector.Scan(pendingTerrainScan.Comp, StoneRoadsEnabled, DirtRoadsEnabled, delegate(int x, int z, RoadType oldType, RoadType newType)
				{
					if (logged++ < 6)
					{
						_logger.LogInfo((object)("[FehuRoadsGrid] Cell changed cell=(" + x + "," + z + ") old=" + oldType.ToString() + " new=" + newType));
					}
				});
				_logger.LogInfo((object)("[FehuRoadsGrid] Authoritative rescan reason=" + pendingTerrainScan.Reason + " changed=" + terrainScanResult.Changed + " dirt=" + terrainScanResult.Dirt + " paved=" + terrainScanResult.Paved + " none=" + terrainScanResult.None));
				if (++num >= 2)
				{
					break;
				}
			}
		}

		internal void QueueScan(TerrainComp comp)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && !((Object)(object)comp == (Object)null))
			{
				int instanceID = ((Object)comp).GetInstanceID();
				if (_queuedTerrain.Add(instanceID))
				{
					_scanQueue.Enqueue(comp);
				}
			}
		}

		private void ProcessOneBackfill()
		{
			if (WorldReady && _scanQueue.Count != 0)
			{
				TerrainComp val = _scanQueue.Dequeue();
				if (!((Object)(object)val == (Object)null))
				{
					_queuedTerrain.Remove(((Object)val).GetInstanceID());
					LegacyScanResult legacyScanResult = _detector.ScanLegacy(val, StoneRoadsEnabled && LegacyStoneBackfill, DirtRoadsEnabled && LegacyDirtBackfill);
					_logger.LogInfo((object)("[FehuRoadsGrid] Legacy scan terrainComp=" + ((Object)val).GetInstanceID() + " pavedFound=" + legacyScanResult.PavedFound + " newRoadCells=" + legacyScanResult.NewRoadCells + " alreadyKnown=" + legacyScanResult.AlreadyKnown));
				}
			}
		}

		public RoadType GetRoadType(Vector3 position)
		{
			//IL_0006: 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)
			return _roads.Get(Mathf.RoundToInt(position.x), Mathf.RoundToInt(position.z));
		}

		public bool IsConnectedByRoad(Vector3 from, Vector3 to)
		{
			//IL_0006: 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)
			return _connectivity.IsConnectedByRoad(from, to);
		}

		public bool IsConnectedByPavedRoad(Vector3 from, Vector3 to)
		{
			//IL_0006: 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)
			return _connectivity.IsConnectedByPavedRoad(from, to);
		}

		public bool FindRoadConnection(Vector3 from, Vector3 to, out RoadConnectionStatus status)
		{
			//IL_0006: 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)
			return _connectivity.FindRoadConnection(from, to, out status);
		}

		public RoadConnectionStatus GetConnectionStatus(Vector3 from, Vector3 to)
		{
			//IL_0006: 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)
			return _connectivity.GetConnectionStatus(from, to);
		}

		public bool TryGetClanAffiliation(Vector3 position, out RoadClanAffiliation affiliation)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ClanAffiliationService.TryGetAffiliation(position, out affiliation);
		}

		internal void LogInfo(string message)
		{
			_logger.LogInfo((object)message);
		}

		internal void LogWarning(string message)
		{
			_logger.LogWarning((object)message);
		}
	}
	[HarmonyPatch(typeof(TerrainComp), "DoOperation")]
	internal static class TerrainOperationPatch
	{
		private static void Postfix(TerrainComp __instance)
		{
			if (GridPlugin.Instance != null)
			{
				GridPlugin.Instance.ScheduleAuthoritativeScan(__instance, 0f, "server-operation");
			}
		}
	}
	[HarmonyPatch(typeof(TerrainComp), "Awake")]
	internal static class TerrainLoadPatch
	{
		private static void Postfix(TerrainComp __instance)
		{
			if (GridPlugin.Instance != null)
			{
				GridPlugin.Instance.QueueScan(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Shutdown")]
	internal static class RoadShutdownPatch
	{
		private static void Prefix()
		{
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.EndSession();
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnDestroy")]
	internal static class RoadNetDestroyPatch
	{
		private static void Prefix()
		{
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.EndSession();
			}
		}
	}
	internal static class LegacyRoadBackfill
	{
		internal static bool TryAddMissing(RoadDatabase roads, int worldX, int worldZ, RoadType detected, bool stoneRoadsEnabled, bool dirtRoadsEnabled, out bool alreadyKnown)
		{
			alreadyKnown = false;
			if ((detected != RoadType.Paved || !stoneRoadsEnabled) && (detected != RoadType.Dirt || !dirtRoadsEnabled))
			{
				return false;
			}
			if (roads.Get(worldX, worldZ) != RoadType.None)
			{
				alreadyKnown = true;
				return false;
			}
			return roads.Set(worldX, worldZ, detected);
		}
	}
	public enum RoadConnectionStatus
	{
		None,
		Connected,
		Disconnected
	}
	public sealed class RoadConnectivityService
	{
		private readonly RoadDatabase _roads;

		public RoadConnectivityService(RoadDatabase roads)
		{
			_roads = roads;
		}

		public RoadConnectionStatus GetConnectionStatus(Vector3 from, Vector3 to, bool pavedOnly = false, int snapRadius = 2, int maxCells = 4096)
		{
			//IL_0001: 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)
			if (!TrySnap(from, pavedOnly, snapRadius, out var x, out var z) || !TrySnap(to, pavedOnly, snapRadius, out var x2, out var z2))
			{
				return RoadConnectionStatus.None;
			}
			if (x == x2 && z == z2)
			{
				return RoadConnectionStatus.Connected;
			}
			Queue<long> queue = new Queue<long>();
			HashSet<long> hashSet = new HashSet<long>();
			queue.Enqueue(RoadDatabase.Key(x, z));
			hashSet.Add(RoadDatabase.Key(x, z));
			int num = 0;
			while (queue.Count > 0 && num++ < maxCells)
			{
				RoadDatabase.Decode(queue.Dequeue(), out var x3, out var z3);
				for (int i = 0; i < 4; i++)
				{
					int num2 = x3 + i switch
					{
						1 => -1, 
						0 => 1, 
						_ => 0, 
					};
					int num3 = z3 + i switch
					{
						3 => -1, 
						2 => 1, 
						_ => 0, 
					};
					if (num2 == x2 && num3 == z2)
					{
						return RoadConnectionStatus.Connected;
					}
					long item = RoadDatabase.Key(num2, num3);
					if (!hashSet.Contains(item) && Matches(num2, num3, pavedOnly))
					{
						hashSet.Add(item);
						queue.Enqueue(item);
					}
				}
			}
			return RoadConnectionStatus.Disconnected;
		}

		public bool IsConnectedByRoad(Vector3 from, Vector3 to)
		{
			//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)
			return GetConnectionStatus(from, to) == RoadConnectionStatus.Connected;
		}

		public bool IsConnectedByPavedRoad(Vector3 from, Vector3 to)
		{
			//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)
			return GetConnectionStatus(from, to, pavedOnly: true) == RoadConnectionStatus.Connected;
		}

		public bool FindRoadConnection(Vector3 from, Vector3 to, out RoadConnectionStatus status)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			status = GetConnectionStatus(from, to);
			return status == RoadConnectionStatus.Connected;
		}

		private bool Matches(int x, int z, bool pavedOnly)
		{
			RoadType roadType = _roads.Get(x, z);
			if (!pavedOnly)
			{
				if (roadType != RoadType.Paved)
				{
					return roadType == RoadType.Dirt;
				}
				return true;
			}
			return roadType == RoadType.Paved;
		}

		private bool TrySnap(Vector3 p, bool pavedOnly, int radius, out int x, out int z)
		{
			//IL_0000: 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)
			int num = Mathf.RoundToInt(p.x);
			int num2 = Mathf.RoundToInt(p.z);
			int num3 = int.MaxValue;
			x = (z = 0);
			for (int i = -radius; i <= radius; i++)
			{
				for (int j = -radius; j <= radius; j++)
				{
					if (Matches(num + j, num2 + i, pavedOnly))
					{
						int num4 = j * j + i * i;
						if (num4 < num3)
						{
							num3 = num4;
							x = num + j;
							z = num2 + i;
						}
					}
				}
			}
			return num3 != int.MaxValue;
		}
	}
}
namespace Forteca.FehuRoads.Persistence
{
	public sealed class RoadPersistence
	{
		private const int Version = 1;

		private readonly string _path;

		private readonly string _world;

		public RoadPersistence(string root, string world)
		{
			_world = world;
			Directory.CreateDirectory(root);
			_path = Path.Combine(root, "roads_" + world + ".bin");
		}

		public void Save(RoadDatabase db)
		{
			string text = _path + ".tmp";
			using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.Write, FileShare.None))
			{
				using BinaryWriter binaryWriter = new BinaryWriter(fileStream);
				binaryWriter.Write(1);
				binaryWriter.Write(_world);
				db.Write(binaryWriter);
				fileStream.Flush(flushToDisk: true);
			}
			if (File.Exists(_path))
			{
				File.Replace(text, _path, null);
			}
			else
			{
				File.Move(text, _path);
			}
		}

		public bool Load(RoadDatabase db)
		{
			if (!File.Exists(_path))
			{
				return false;
			}
			using BinaryReader binaryReader = new BinaryReader(File.OpenRead(_path));
			if (binaryReader.ReadInt32() != 1 || binaryReader.ReadString() != _world)
			{
				return false;
			}
			db.Read(binaryReader);
			return true;
		}
	}
}
namespace Forteca.FehuRoads.Plugin
{
	[BepInPlugin("forteca.fehuroads", "Fehu Roads", "420.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class FehuRoadsPlugin : BaseUnityPlugin, IRoadDataProvider
	{
		internal static FehuRoadsPlugin Instance;

		private bool _commandsRegistered;

		private RoadDatabase _roads;

		private ClientRoadNetwork _network;

		private RoadMapOverlay _overlay;

		private Harmony _harmony;

		private long _worldUid;

		private bool _snapshotComplete;

		internal ConfigEntry<bool> Enabled;

		internal ConfigEntry<bool> LargeMap;

		internal ConfigEntry<bool> MiniMap;

		internal ConfigEntry<bool> KingdomsMap;

		internal ConfigEntry<bool> RespectFog;

		internal ConfigEntry<bool> DirtEnabled;

		internal ConfigEntry<bool> PavedEnabled;

		internal ConfigEntry<bool> NetworkEnabled;

		internal ConfigEntry<bool> DebugLogging;

		internal ConfigEntry<string> DirtColorHex;

		internal ConfigEntry<string> PavedColorHex;

		internal ConfigEntry<float> DirtWidth;

		internal ConfigEntry<float> PavedWidth;

		internal GridPlugin Server { get; private set; }

		internal RoadDatabase Roads
		{
			get
			{
				if (Server == null || !Server.WorldReady)
				{
					return _roads;
				}
				return Server.Roads;
			}
		}

		internal long WorldUid => _worldUid;

		internal bool SnapshotComplete => _snapshotComplete;

		internal RoadMapOverlay Overlay => _overlay;

		internal bool FcwTacticalAttached { get; private set; }

		internal Color DirtColor
		{
			get
			{
				//IL_002e: 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)
				Color result = default(Color);
				if (!ColorUtility.TryParseHtmlString(DirtColorHex.Value, ref result))
				{
					return new Color(0.85f, 0.7f, 0.49f, 0.82f);
				}
				return result;
			}
		}

		internal Color PavedColor
		{
			get
			{
				//IL_002e: 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)
				Color result = default(Color);
				if (!ColorUtility.TryParseHtmlString(PavedColorHex.Value, ref result))
				{
					return new Color(0.7f, 0.71f, 0.73f, 0.82f);
				}
				return result;
			}
		}

		public event Action<RoadCell, RoadType> RoadDataChanged;

		private void Awake()
		{
			if (Chainloader.PluginInfos.ContainsKey("forteca.fehuroads.grid"))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"[FehuRoads] Unified mod DISABLED: legacy FehuRoadsGrid is installed. Stop Valheim and manually remove FehuRoadsGrid.dll; keep both configuration files and config/FehuRoads data.");
				((Behaviour)this).enabled = false;
				return;
			}
			Instance = this;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable road display.");
			LargeMap = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowOnLargeMap", true, "Show roads on the M map.");
			MiniMap = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowOnMinimap", true, "Show roads on the HUD minimap.");
			KingdomsMap = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowOnKingdomsMap", true, "Show roads with the Clan Warfare map.");
			RespectFog = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "RespectFogOfWar", true, "Do not draw in unexplored map areas.");
			DirtEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("DirtRoad", "Enabled", false, "Show dirt roads.");
			PavedEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("PavedRoad", "Enabled", true, "Show paved roads.");
			DirtColorHex = ((BaseUnityPlugin)this).Config.Bind<string>("DirtRoad", "Color", "#D8B27DD0", "Warm packed-earth color and opacity.");
			PavedColorHex = ((BaseUnityPlugin)this).Config.Bind<string>("PavedRoad", "Color", "#B2B6BBD0", "Cool stone color and opacity.");
			DirtWidth = ((BaseUnityPlugin)this).Config.Bind<float>("DirtRoad", "WidthMultiplier", 2f, "Minimum display pixels.");
			PavedWidth = ((BaseUnityPlugin)this).Config.Bind<float>("PavedRoad", "WidthMultiplier", 2f, "Minimum display pixels.");
			NetworkEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Network", "EnableSynchronization", true, "Receive authoritative server road chunks.");
			DebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "EnableDebugLogging", false, "Enable diagnostic logging.");
			_roads = new RoadDatabase();
			_roads.Changed += ForwardChange;
			_network = new ClientRoadNetwork(this);
			Server = new GridPlugin(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger);
			Server.Roads.Changed += ForwardChange;
			Server.Roads.ChunkChanged += ServerChunkChanged;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[FehuRoads] Unified plugin loaded version=420.2.0");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[FehuRoads] RPC/network initialized");
			InstallTerrainHook();
			_harmony.PatchAll(typeof(FehuRoadsPlugin).Assembly);
			try
			{
				FcwCompatibility.Install(_harmony, this);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("[FehuRoads] FCW road access integration unavailable: " + ex));
			}
			FehuRoadsCommands.Register(this);
			_commandsRegistered = true;
		}

		private void InstallFcwTacticalBridge()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			if (FcwTacticalAttached)
			{
				return;
			}
			if (!Chainloader.PluginInfos.TryGetValue("com.forteca.clanwarfare", out var value) || value == null || (Object)(object)value.Instance == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[FehuRoads] FCW map bridge not present; vanilla maps remain enabled");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[FehuRoads] FCW map bridge detected");
			try
			{
				Type type = ((object)value.Instance).GetType().Assembly.GetType("FortecaClanWarfare.UI.ClanMapDrawingUi", throwOnError: false);
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "Render", (Type[])null, (Type[])null));
				MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(FcwTacticalMapBridge), "BeforeClanMapDrawings", (Type[])null, (Type[])null);
				if (methodInfo == null || methodInfo2 == null)
				{
					throw new MissingMethodException("FortecaClanWarfare.UI.ClanMapDrawingUi.Render");
				}
				_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				FcwTacticalAttached = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[FehuRoads] FCW ClanMap bridge installed; waiting for actual ClanWorldMapPanel canvas");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("[FehuRoads] FCW tactical road layer unavailable; vanilla maps remain active: " + ex.Message));
			}
		}

		private void InstallTerrainHook()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			_harmony = new Harmony("forteca.fehuroads");
			try
			{
				MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(TerrainOp), "Awake", (Type[])null, (Type[])null);
				MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(TerrainPaintClient), "TerrainOpPostfix", (Type[])null, (Type[])null);
				if (methodInfo == null || methodInfo2 == null)
				{
					throw new MissingMethodException("TerrainOp.Awake()");
				}
				_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[FehuRoads] Terrain change hint hook installed: TerrainOp.Awake()");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("[FehuRoads] Terrain change hook failed; client networking and rendering remain active: " + ex));
			}
		}

		private void Update()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			Server.Update();
			int num;
			if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsDedicated())
			{
				num = (((int)SystemInfo.graphicsDeviceType != 4) ? 1 : 0);
				if (num != 0 && (Object)(object)_overlay == (Object)null)
				{
					_overlay = ((Component)this).gameObject.AddComponent<RoadMapOverlay>();
					InstallFcwTacticalBridge();
				}
			}
			else
			{
				num = 0;
			}
			if (num == 0 && (Object)(object)_overlay != (Object)null)
			{
				Object.Destroy((Object)(object)_overlay);
				_overlay = null;
			}
			_network.Update();
		}

		private void ServerChunkChanged(RoadChunkCoord coord, uint revision)
		{
			InvalidateRender();
		}

		internal void EndSession()
		{
			if (Server != null)
			{
				Server.EndWorld();
			}
			if (_network != null)
			{
				_network.ResetSession();
			}
			EndWorld();
		}

		private void ForwardChange(RoadCell cell, RoadType type)
		{
			this.RoadDataChanged?.Invoke(cell, type);
		}

		internal void BeginWorld(long uid)
		{
			if (_worldUid != uid)
			{
				_worldUid = uid;
				_snapshotComplete = false;
				_roads.Clear();
				InvalidateRender();
			}
		}

		internal void EndWorld()
		{
			if (_worldUid != 0L)
			{
				_worldUid = 0L;
				_snapshotComplete = false;
				_roads.Clear();
				InvalidateRender();
			}
		}

		internal void BeginSnapshot()
		{
			_snapshotComplete = false;
			_roads.Clear();
			InvalidateRender();
		}

		internal void ApplyChunk(RoadChunkData chunk)
		{
			if (_roads.ReplaceChunk(chunk))
			{
				InvalidateRender();
			}
		}

		internal void CompleteSnapshot()
		{
			if (!_snapshotComplete)
			{
				_snapshotComplete = true;
				InvalidateRender();
			}
		}

		public RoadType GetRoadType(Vector3 p)
		{
			//IL_0006: 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)
			return Roads.Get(Mathf.RoundToInt(p.x), Mathf.RoundToInt(p.z));
		}

		internal string Stats()
		{
			int num = 0;
			int num2 = 0;
			foreach (KeyValuePair<long, RoadType> entry in Roads.Entries)
			{
				if (entry.Value == RoadType.Dirt)
				{
					num++;
				}
				else if (entry.Value == RoadType.Paved)
				{
					num2++;
				}
			}
			int num3;
			object obj;
			if (Server != null)
			{
				num3 = (Server.WorldReady ? 1 : 0);
				if (num3 != 0)
				{
					obj = (ZNet.instance.IsDedicated() ? "dedicated" : "host");
					goto IL_008e;
				}
			}
			else
			{
				num3 = 0;
			}
			obj = "client";
			goto IL_008e;
			IL_008e:
			string text = (string)obj;
			long num4 = ((num3 != 0) ? Server.WorldUid : _worldUid);
			return "FehuRoads role=" + text + " protocol=" + 1 + " world=" + num4.ToString("X") + " snapshot=" + _snapshotComplete + " chunks=" + Roads.ChunkCount + " dirt=" + num + " paved=" + num2;
		}

		internal void InvalidateRender()
		{
			if ((Object)(object)_overlay != (Object)null)
			{
				_overlay.Invalidate();
			}
		}

		internal void SendRoadUpdate(IList<KeyValuePair<long, RoadType>> cells)
		{
			_network.SendRoadUpdate(cells);
		}

		internal void LogInfo(string message)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)message);
		}

		internal void LogWarning(string message)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)message);
		}

		public bool IsConnectedByRoad(Vector3 from, Vector3 to)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (Server != null && Server.WorldReady)
			{
				return Server.IsConnectedByRoad(from, to);
			}
			return false;
		}

		public bool IsConnectedByPavedRoad(Vector3 from, Vector3 to)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (Server != null && Server.WorldReady)
			{
				return Server.IsConnectedByPavedRoad(from, to);
			}
			return false;
		}

		public bool FindRoadConnection(Vector3 from, Vector3 to, out RoadConnectionStatus status)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			status = GetConnectionStatus(from, to);
			return status == RoadConnectionStatus.Connected;
		}

		public RoadConnectionStatus GetConnectionStatus(Vector3 from, Vector3 to)
		{
			//IL_001d: 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)
			if (Server == null || !Server.WorldReady)
			{
				return RoadConnectionStatus.None;
			}
			return Server.GetConnectionStatus(from, to);
		}

		public bool TryGetClanAffiliation(Vector3 position, out RoadClanAffiliation affiliation)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ClanAffiliationService.TryGetAffiliation(position, out affiliation);
		}

		private void OnDestroy()
		{
			if (!((Object)(object)Instance != (Object)(object)this))
			{
				EndSession();
				if ((Object)(object)_overlay != (Object)null)
				{
					Object.Destroy((Object)(object)_overlay);
				}
				if (_commandsRegistered)
				{
					FehuRoadsCommands.Unregister();
				}
				if (Server != null)
				{
					Server.Roads.Changed -= ForwardChange;
					Server.Roads.ChunkChanged -= ServerChunkChanged;
					Server.Dispose();
				}
				if (_roads != null)
				{
					_roads.Changed -= ForwardChange;
				}
				FcwCompatibility.Clear(this);
				if (_harmony != null)
				{
					_harmony.UnpatchSelf();
				}
				Instance = null;
			}
		}
	}
}
namespace Forteca.FehuRoads.Commands
{
	internal static class FehuRoadsCommands
	{
		private static ConsoleCommand _command;

		internal static void Unregister()
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(Terminal), "commands");
			IDictionary dictionary = ((fieldInfo == null) ? null : (fieldInfo.GetValue(null) as IDictionary));
			if (dictionary != null && dictionary["fehuroads"] == _command)
			{
				dictionary.Remove("fehuroads");
			}
			_command = null;
		}

		internal static void Register(FehuRoadsPlugin plugin)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			_command = new ConsoleCommand("fehuroads", "fehuroads stats | rebuild-render", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				if (args.Length < 2)
				{
					args.Context.AddString("fehuroads stats | rebuild-render");
				}
				else if (args[1] == "stats")
				{
					args.Context.AddString(plugin.Stats());
				}
				else if (args[1] == "rebuild-render")
				{
					plugin.InvalidateRender();
					args.Context.AddString("FehuRoads renderer invalidated.");
				}
			}, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}
	}
}
namespace Forteca.FehuRoads.Rendering
{
	internal sealed class RoadMapOverlay : MonoBehaviour
	{
		private const float ClanMapWorldRadius = 10500f;

		private readonly List<KeyValuePair<long, RoadType>> _visible = new List<KeyValuePair<long, RoadType>>();

		private readonly List<KeyValuePair<long, RoadType>> _clanMapRoads = new List<KeyValuePair<long, RoadType>>();

		private Rect _lastUv;

		private int _lastMode = -1;

		private int _lastClanMapCount = -1;

		private int _clanMapLastFrame = -100;

		private bool _dirty = true;

		private bool _clanMapDirty = true;

		private bool _clanMapOpen;

		private static readonly FieldInfo Explored = typeof(Minimap).GetField("m_explored", BindingFlags.Instance | BindingFlags.NonPublic);

		private FehuRoadsPlugin _plugin;

		private void RoadChanged(RoadCell cell, RoadType type)
		{
			Invalidate();
		}

		private void OnDestroy()
		{
			if ((Object)(object)_plugin != (Object)null)
			{
				_plugin.RoadDataChanged -= RoadChanged;
			}
		}

		private void Awake()
		{
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				_plugin = instance;
				instance.RoadDataChanged += RoadChanged;
				instance.LogInfo("[FehuRoads] Minimap hook installed");
				instance.LogInfo("[FehuRoads] Large map overlay initialized");
			}
		}

		internal void Invalidate()
		{
			_dirty = true;
			_clanMapDirty = true;
		}

		private void Update()
		{
			if (_clanMapOpen && Time.frameCount - _clanMapLastFrame > 2)
			{
				_clanMapOpen = false;
				_lastClanMapCount = -1;
			}
		}

		private void Rebuild(Minimap minimap, RawImage image)
		{
			//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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected I4, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between I4 and Unknown
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Rect uvRect = image.uvRect;
			if (_dirty || _lastMode != (int)minimap.m_mode || !(uvRect == _lastUv))
			{
				_lastMode = (int)minimap.m_mode;
				_lastUv = uvRect;
				_dirty = false;
				float num = (float)minimap.m_textureSize * minimap.m_pixelSize;
				FehuRoadsPlugin.Instance.Roads.Query(Mathf.FloorToInt((((Rect)(ref uvRect)).xMin - 0.5f) * num), Mathf.FloorToInt((((Rect)(ref uvRect)).yMin - 0.5f) * num), Mathf.CeilToInt((((Rect)(ref uvRect)).xMax - 0.5f) * num), Mathf.CeilToInt((((Rect)(ref uvRect)).yMax - 0.5f) * num), _visible);
			}
		}

		private void OnGUI()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Invalid comparison between Unknown and I4
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			Minimap instance2 = Minimap.instance;
			if (!((Object)(object)instance == (Object)null) && instance.Enabled.Value && !((Object)(object)instance2 == (Object)null) && (int)Event.current.type == 7)
			{
				bool flag = (int)instance2.m_mode == 2;
				bool flag2 = (int)instance2.m_mode == 1;
				if ((!flag || instance.LargeMap.Value) && (!flag2 || instance.MiniMap.Value) && (flag || flag2))
				{
					DrawVanillaMap(instance2, flag ? instance2.m_mapImageLarge : instance2.m_mapImageSmall);
				}
			}
		}

		private void DrawVanillaMap(Minimap minimap, RawImage image)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: 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_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)image == (Object)null)
			{
				return;
			}
			Rebuild(minimap, image);
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			((Graphic)image).rectTransform.GetWorldCorners(array);
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(array[0].x, (float)Screen.height - array[2].y, array[2].x - array[0].x, array[2].y - array[0].y);
			Rect uvRect = image.uvRect;
			float num = (float)minimap.m_textureSize * minimap.m_pixelSize;
			float num2 = ((Rect)(ref val)).width / (num * ((Rect)(ref uvRect)).width);
			float num3 = ((Rect)(ref val)).height / (num * ((Rect)(ref uvRect)).height);
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			GUI.BeginGroup(val);
			foreach (KeyValuePair<long, RoadType> item in _visible)
			{
				RoadDatabase.Decode(item.Key, out var x, out var z);
				RoadType value = item.Value;
				if (TypeEnabled(instance, value))
				{
					float num4 = ((float)x / minimap.m_pixelSize + (float)minimap.m_textureSize / 2f) / (float)minimap.m_textureSize;
					float num5 = ((float)z / minimap.m_pixelSize + (float)minimap.m_textureSize / 2f) / (float)minimap.m_textureSize;
					if (IsExplored(minimap, num4, num5, instance.RespectFog.Value))
					{
						float num6 = (num4 - ((Rect)(ref uvRect)).x) / ((Rect)(ref uvRect)).width * ((Rect)(ref val)).width;
						float num7 = (1f - (num5 - ((Rect)(ref uvRect)).y) / ((Rect)(ref uvRect)).height) * ((Rect)(ref val)).height;
						float num8 = ((value == RoadType.Paved) ? instance.PavedWidth.Value : instance.DirtWidth.Value);
						float num9 = Mathf.Max(num8, num2 + 0.35f);
						float num10 = Mathf.Max(num8, num3 + 0.35f);
						GUI.color = ((value == RoadType.Paved) ? instance.PavedColor : instance.DirtColor);
						GUI.DrawTexture(new Rect(num6 - num9 * 0.5f, num7 - num10 * 0.5f, num9, num10), (Texture)(object)Texture2D.whiteTexture);
					}
				}
			}
			GUI.EndGroup();
			GUI.color = Color.white;
		}

		internal void DrawClanMapLayer(Rect local, Vector2 center, float baseDiameter, float zoom)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			if ((Object)(object)instance == (Object)null || !instance.Enabled.Value || !instance.KingdomsMap.Value || (int)Event.current.type != 7)
			{
				return;
			}
			_clanMapLastFrame = Time.frameCount;
			if (!_clanMapOpen)
			{
				_clanMapOpen = true;
				_clanMapDirty = true;
				instance.LogInfo("[FehuRoads] FCW tactical UI OPEN");
				instance.LogInfo("[FehuRoads] FCW tactical root path=IMGUI/FortecaClanWarfare.UI.ClanWorldMapPanel/DrawCanvas");
				instance.LogInfo("[FehuRoads] FCW tactical parent path=GUI.BeginGroup(canvas) instance=static");
				instance.LogInfo("[FehuRoads] FCW tactical layer attached after=DrawPolygons before=ClanMapDrawingUi.Render");
			}
			if (_clanMapDirty)
			{
				instance.Roads.Query(-10500, -10500, 10500, 10500, _clanMapRoads);
				_clanMapDirty = false;
			}
			float num = baseDiameter * 0.5f * zoom;
			float num2 = baseDiameter * zoom / 21000f;
			int num3 = 0;
			foreach (KeyValuePair<long, RoadType> clanMapRoad in _clanMapRoads)
			{
				RoadDatabase.Decode(clanMapRoad.Key, out var x, out var z);
				RoadType value = clanMapRoad.Value;
				if (!TypeEnabled(instance, value) || (double)x * (double)x + (double)z * (double)z > 110250000.0)
				{
					continue;
				}
				Minimap instance2 = Minimap.instance;
				if (!instance.RespectFog.Value || (!((Object)(object)instance2 == (Object)null) && IsExplored(instance2, ((float)x / instance2.m_pixelSize + (float)instance2.m_textureSize / 2f) / (float)instance2.m_textureSize, ((float)z / instance2.m_pixelSize + (float)instance2.m_textureSize / 2f) / (float)instance2.m_textureSize, required: true)))
				{
					float num4 = center.x + (float)x / 10500f * num;
					float num5 = center.y - (float)z / 10500f * num;
					if (!(num4 < 0f) && !(num5 < 0f) && !(num4 > ((Rect)(ref local)).width) && !(num5 > ((Rect)(ref local)).height))
					{
						float num6 = Mathf.Max((value == RoadType.Paved) ? instance.PavedWidth.Value : instance.DirtWidth.Value, num2 + 0.35f);
						GUI.color = ((value == RoadType.Paved) ? instance.PavedColor : instance.DirtColor);
						GUI.DrawTexture(new Rect(num4 - num6 * 0.5f, num5 - num6 * 0.5f, num6, num6), (Texture)(object)Texture2D.whiteTexture);
						num3++;
					}
				}
			}
			GUI.color = Color.white;
			if (num3 != _lastClanMapCount)
			{
				_lastClanMapCount = num3;
				instance.LogInfo("[FehuRoads] FCW tactical renderer roadCells=" + _clanMapRoads.Count + " rendered=" + num3 + " canvas=" + ((Rect)(ref local)).width.ToString("F0") + "x" + ((Rect)(ref local)).height.ToString("F0") + " zoom=" + zoom.ToString("F2"));
			}
		}

		private static bool TypeEnabled(FehuRoadsPlugin plugin, RoadType type)
		{
			if (type != RoadType.Dirt || plugin.DirtEnabled.Value)
			{
				if (type == RoadType.Paved)
				{
					return plugin.PavedEnabled.Value;
				}
				return true;
			}
			return false;
		}

		private static bool IsExplored(Minimap minimap, float mapX, float mapY, bool required)
		{
			if (!required)
			{
				return true;
			}
			bool[] array = ((Explored == null) ? null : (Explored.GetValue(minimap) as bool[]));
			int num = Mathf.RoundToInt(mapX * (float)minimap.m_textureSize);
			int num2 = Mathf.RoundToInt(mapY * (float)minimap.m_textureSize);
			if (array != null && num >= 0 && num2 >= 0 && num < minimap.m_textureSize && num2 < minimap.m_textureSize)
			{
				return array[num2 * minimap.m_textureSize + num];
			}
			return false;
		}
	}
	internal static class FcwTacticalMapBridge
	{
		internal static void BeforeClanMapDrawings(Rect __0, Vector2 __1, float __2, float __3)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.Overlay != (Object)null)
			{
				instance.Overlay.DrawClanMapLayer(__0, __1, __2, __3);
			}
		}
	}
}
namespace Forteca.FehuRoads.Networking
{
	internal sealed class ClientRoadNetwork
	{
		private readonly RpcBindings _bindings = new RpcBindings();

		private readonly FehuRoadsPlugin _plugin;

		private bool _registered;

		private bool _snapshotRequested;

		private long _requestedWorld;

		private ZRoutedRpc _routedRpc;

		private float _retrySnapshot;

		internal ClientRoadNetwork(FehuRoadsPlugin plugin)
		{
			_plugin = plugin;
		}

		internal void Update()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Invalid comparison between Unknown and I4
			if (!_plugin.NetworkEnabled.Value)
			{
				ResetSession();
				return;
			}
			ZNet instance = ZNet.instance;
			ZRoutedRpc instance2 = ZRoutedRpc.instance;
			if ((Object)(object)instance == (Object)null || instance2 == null)
			{
				ResetSession();
				return;
			}
			if (_routedRpc != instance2)
			{
				ResetSession();
				_routedRpc = instance2;
			}
			if (instance.IsServer())
			{
				if (!instance.IsDedicated() && _plugin.Server.WorldReady)
				{
					_plugin.BeginWorld(instance.GetWorldUID());
					_plugin.CompleteSnapshot();
				}
				return;
			}
			if ((int)ZNet.GetConnectionStatus() != 2)
			{
				ResetWorld();
				return;
			}
			if (instance.GetServerPeer() == null || ZNet.World == null)
			{
				ResetWorld();
				return;
			}
			if (!_registered)
			{
				_bindings.Register(instance2, "FehuRoads_Begin", OnBegin);
				_bindings.Register(instance2, "FehuRoads_Chunk", OnChunk);
				_bindings.Register(instance2, "FehuRoads_End", OnEnd);
				_registered = true;
				_plugin.LogInfo("[FehuRoads] Protocol registered version=" + 1);
			}
			long worldUID = instance.GetWorldUID();
			if (worldUID != 0L)
			{
				if (worldUID != _requestedWorld)
				{
					_requestedWorld = worldUID;
					_snapshotRequested = false;
					_plugin.BeginWorld(worldUID);
				}
				if (!_plugin.SnapshotComplete && (!_snapshotRequested || !(Time.time < _retrySnapshot)))
				{
					_snapshotRequested = true;
					_retrySnapshot = Time.time + 10f;
					instance2.InvokeRoutedRPC("FehuRoads_Request", new object[1] { RoadProtocol.Header(worldUID) });
					_plugin.LogInfo("[FehuRoads] Snapshot requested world=" + worldUID.ToString("X"));
				}
			}
		}

		private void ResetWorld()
		{
			if (_requestedWorld != 0L)
			{
				_plugin.EndWorld();
			}
			_requestedWorld = 0L;
			_snapshotRequested = false;
		}

		internal void ResetSession()
		{
			_plugin.EndWorld();
			_bindings.Clear();
			ResetWorld();
			_registered = false;
			_routedRpc = null;
		}

		internal void SendRoadUpdate(IList<KeyValuePair<long, RoadType>> cells)
		{
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Invalid comparison between Unknown and I4
			ZNet instance = ZNet.instance;
			ZRoutedRpc instance2 = ZRoutedRpc.instance;
			if (!_plugin.NetworkEnabled.Value)
			{
				return;
			}
			if ((Object)(object)instance != (Object)null && instance.IsServer())
			{
				if (cells == null)
				{
					return;
				}
				for (int i = 0; i < cells.Count; i += 512)
				{
					List<KeyValuePair<long, RoadType>> list = new List<KeyValuePair<long, RoadType>>();
					for (int j = i; j < cells.Count && j < i + 512; j++)
					{
						list.Add(cells[j]);
					}
					_plugin.Server.ReceiveLocal(list);
				}
			}
			else
			{
				if (!_registered || cells == null || cells.Count == 0 || _plugin.WorldUid == 0L || (Object)(object)instance == (Object)null || instance2 == null || ZNet.World == null || instance.GetServerPeer() == null || (int)ZNet.GetConnectionStatus() != 2)
				{
					return;
				}
				for (int k = 0; k < cells.Count; k += 512)
				{
					List<KeyValuePair<long, RoadType>> list2 = new List<KeyValuePair<long, RoadType>>();
					for (int l = k; l < cells.Count && l < k + 512; l++)
					{
						list2.Add(cells[l]);
					}
					instance2.InvokeRoutedRPC("FehuRoads_Update", new object[1] { RoadProtocol.EncodeUpdate(_plugin.WorldUid, list2) });
				}
				_plugin.LogInfo("[FehuRoads] Sending road update cells=" + cells.Count);
			}
		}

		private bool IsServer(long sender)
		{
			ZNetPeer val = (((Object)(object)ZNet.instance == (Object)null) ? null : ZNet.instance.GetServerPeer());
			if (val != null)
			{
				return val.m_uid == sender;
			}
			return false;
		}

		private void OnBegin(long sender, ZPackage package)
		{
			if (IsServer(sender) && RoadProtocol.ReadAndValidateHeader(package, _plugin.WorldUid))
			{
				_plugin.BeginSnapshot();
			}
		}

		private void OnChunk(long sender, ZPackage package)
		{
			if (IsServer(sender) && RoadProtocol.TryDecodeChunk(package, _plugin.WorldUid, out var chunk))
			{
				_plugin.ApplyChunk(chunk);
				_plugin.LogInfo("[FehuRoads] Delta received world=" + _plugin.WorldUid.ToString("X") + " cells=" + chunk.Cells.Length);
			}
		}

		private void OnEnd(long sender, ZPackage package)
		{
			if (IsServer(sender) && RoadProtocol.ReadAndValidateHeader(package, _plugin.WorldUid))
			{
				_plugin.CompleteSnapshot();
				_plugin.LogInfo("[FehuRoads] Snapshot received chunks=" + _plugin.Roads.ChunkCount + " cells=" + _plugin.Roads.Count);
			}
		}
	}
	internal sealed class RpcBindings
	{
		private ZRoutedRpc _rpc;

		private readonly Dictionary<int, object> _owned = new Dictionary<int, object>();

		private static readonly FieldInfo Functions = AccessTools.Field(typeof(ZRoutedRpc), "m_functions");

		internal bool IsCurrent(ZRoutedRpc rpc)
		{
			return _rpc == rpc;
		}

		internal void Register(ZRoutedRpc rpc, string name, Action<long, ZPackage> handler)
		{
			if (!IsCurrent(rpc))
			{
				Clear();
				_rpc = rpc;
			}
			IDictionary dictionary = (IDictionary)Functions.GetValue(rpc);
			int stableHashCode = StringExtensionMethods.GetStableHashCode(name);
			if (dictionary.Contains(stableHashCode))
			{
				throw new InvalidOperationException("FehuRoads RPC already registered: " + name);
			}
			rpc.Register<ZPackage>(name, handler);
			_owned.Add(stableHashCode, dictionary[stableHashCode]);
		}

		internal void Clear()
		{
			if (_rpc != null)
			{
				IDictionary dictionary = (IDictionary)Functions.GetValue(_rpc);
				foreach (KeyValuePair<int, object> item in _owned)
				{
					if (dictionary[item.Key] == item.Value)
					{
						dictionary.Remove(item.Key);
					}
				}
			}
			_owned.Clear();
			_rpc = null;
		}
	}
}
namespace Forteca.FehuRoads.Detection
{
	internal static class TerrainPaintClient
	{
		internal unsafe static void TerrainOpPostfix(TerrainOp __instance)
		{
			//IL_0010: 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_004d: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected I4, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: 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)
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Vector3 position = ((Component)__instance).transform.position;
			Settings settings = __instance.m_settings;
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)instance == (Object)null || (Object)(object)localPlayer == (Object)null || settings == null || !settings.m_paintCleared || Vector3.Distance(((Component)localPlayer).transform.position, position) > 32f)
			{
				return;
			}
			PaintType paintType = settings.m_paintType;
			RoadType value;
			switch ((int)paintType)
			{
			default:
				return;
			case 0:
				value = RoadType.Dirt;
				break;
			case 2:
				value = RoadType.Paved;
				break;
			case 1:
			case 3:
				value = RoadType.None;
				break;
			}
			float num = Mathf.Clamp(settings.m_paintRadius, 0.5f, 12f);
			int num2 = Mathf.FloorToInt(position.x - num);
			int num3 = Mathf.CeilToInt(position.x + num);
			int num4 = Mathf.FloorToInt(position.z - num);
			int num5 = Mathf.CeilToInt(position.z + num);
			List<KeyValuePair<long, RoadType>> list = new List<KeyValuePair<long, RoadType>>();
			float num6 = num * num;
			for (int i = num4; i <= num5; i++)
			{
				for (int j = num2; j <= num3; j++)
				{
					Vector2 val = new Vector2((float)j - position.x, (float)i - position.z);
					if (((Vector2)(ref val)).sqrMagnitude <= num6)
					{
						list.Add(new KeyValuePair<long, RoadType>(RoadDatabase.Key(j, i), value));
					}
				}
			}
			string[] obj = new string[6] { "[FehuRoads] Terrain hint pos=", null, null, null, null, null };
			Vector3 val2 = position;
			obj[1] = ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString();
			obj[2] = " tool=";
			obj[3] = value.ToString().ToUpperInvariant();
			obj[4] = " cells=";
			obj[5] = list.Count.ToString();
			instance.LogInfo(string.Concat(obj));
			instance.SendRoadUpdate(list);
		}
	}
	internal struct TerrainScanResult
	{
		internal int Changed;

		internal int Dirt;

		internal int Paved;

		internal int None;
	}
	internal struct LegacyScanResult
	{
		internal int PavedFound;

		internal int DirtFound;

		internal int NewRoadCells;

		internal int AlreadyKnown;
	}
	public sealed class TerrainRoadDetector
	{
		private static readonly FieldInfo Modified = typeof(TerrainComp).GetField("m_modifiedPaint", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo Mask = typeof(TerrainComp).GetField("m_paintMask", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo Map = typeof(TerrainComp).GetField("m_hmap", BindingFlags.Instance | BindingFlags.NonPublic);

		private readonly RoadDatabase _roads;

		public TerrainRoadDetector(RoadDatabase roads)
		{
			_roads = roads;
		}

		internal TerrainScanResult Scan(TerrainComp comp, bool stoneRoadsEnabled, bool dirtRoadsEnabled, Action<int, int, RoadType, RoadType> changed = null)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			TerrainScanResult result = default(TerrainScanResult);
			if ((Object)(object)comp == (Object)null || Modified == null || Mask == null || Map == null)
			{
				return result;
			}
			bool[] array = Modified.GetValue(comp) as bool[];
			Color[] array2 = Mask.GetValue(comp) as Color[];
			object? value = Map.GetValue(comp);
			Heightmap val = (Heightmap)((value is Heightmap) ? value : null);
			if (array == null || array2 == null || (Object)(object)val == (Object)null)
			{
				return result;
			}
			int num = val.m_width + 1;
			Vector3 position = ((Component)val).transform.position;
			float num2 = (float)val.m_width * val.m_scale * 0.5f;
			int num3 = Math.Min(array.Length, array2.Length);
			for (int i = 0; i < num3; i++)
			{
				int num4 = i % num;
				int num5 = i / num;
				int num6 = Mathf.RoundToInt(position.x - num2 + (float)num4 * val.m_scale);
				int num7 = Mathf.RoundToInt(position.z - num2 + (float)num5 * val.m_scale);
				RoadType roadType = Classify(array[i], array2[i]);
				switch (roadType)
				{
				case RoadType.Dirt:
					result.Dirt++;
					break;
				case RoadType.Paved:
					result.Paved++;
					break;
				default:
					result.None++;
					break;
				}
				if ((roadType != RoadType.Paved || stoneRoadsEnabled) && (roadType != RoadType.Dirt || dirtRoadsEnabled))
				{
					RoadType arg = _roads.Get(num6, num7);
					if (_roads.Set(num6, num7, roadType))
					{
						result.Changed++;
						changed?.Invoke(num6, num7, arg, roadType);
					}
				}
			}
			return result;
		}

		internal LegacyScanResult ScanLegacy(TerrainComp comp, bool stoneRoadsEnabled, bool dirtRoadsEnabled)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			LegacyScanResult result = default(LegacyScanResult);
			if ((Object)(object)comp == (Object)null || Modified == null || Mask == null || Map == null)
			{
				return result;
			}
			bool[] array = Modified.GetValue(comp) as bool[];
			Color[] array2 = Mask.GetValue(comp) as Color[];
			object? value = Map.GetValue(comp);
			Heightmap val = (Heightmap)((value is Heightmap) ? value : null);
			if (array == null || array2 == null || (Object)(object)val == (Object)null)
			{
				return result;
			}
			int num = val.m_width + 1;
			Vector3 position = ((Component)val).transform.position;
			float num2 = (float)val.m_width * val.m_scale * 0.5f;
			int num3 = Math.Min(array.Length, array2.Length);
			for (int i = 0; i < num3; i++)
			{
				RoadType roadType = Classify(array[i], array2[i]);
				if (roadType == RoadType.Paved)
				{
					result.PavedFound++;
				}
				else
				{
					if (roadType != RoadType.Dirt)
					{
						continue;
					}
					result.DirtFound++;
				}
				int num4 = i % num;
				int num5 = i / num;
				int worldX = Mathf.RoundToInt(position.x - num2 + (float)num4 * val.m_scale);
				int worldZ = Mathf.RoundToInt(position.z - num2 + (float)num5 * val.m_scale);
				if (LegacyRoadBackfill.TryAddMissing(_roads, worldX, worldZ, roadType, stoneRoadsEnabled, dirtRoadsEnabled, out var alreadyKnown))
				{
					result.NewRoadCells++;
				}
				else if (alreadyKnown)
				{
					result.AlreadyKnown++;
				}
			}
			return result;
		}

		private static RoadType Classify(bool modified, Color paint)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0044: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			if (!modified)
			{
				return RoadType.None;
			}
			if (paint.b > paint.r && paint.b > paint.g && paint.b > 0.5f)
			{
				return RoadType.Paved;
			}
			if (paint.r > paint.g && paint.r > paint.b && paint.r > 0.5f)
			{
				return RoadType.Dirt;
			}
			return RoadType.None;
		}
	}
}
namespace Forteca.FehuRoads.Integration
{
	public interface IRoadDataProvider
	{
		event Action<RoadCell, RoadType> RoadDataChanged;

		RoadType GetRoadType(Vector3 worldPosition);
	}
	internal static class FcwCompatibility
	{
		private static Type _bridge;

		internal static void Install(Harmony harmony, FehuRoadsPlugin plugin)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("com.forteca.clanwarfare", out var value) || (Object)(object)value.Instance == (Object)null)
			{
				return;
			}
			Type type = ((object)value.Instance).GetType().Assembly.GetType("FortecaClanWarfare.Core.FehuRoadsBridge", throwOnError: false);
			if (type == null)
			{
				plugin.LogInfo("[FehuRoads] FCW has no legacy resolver; unified public API available.");
				return;
			}
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "TryResolve", (Type[])null, (Type[])null);
			if (methodInfo == null || AccessTools.Field(type, "_gridPlugin") == null || AccessTools.Field(type, "_isConnectedByPavedRoad") == null)
			{
				throw new MissingMemberException("Unsupported FCW road resolver; cannot preserve road access integration.");
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FcwCompatibility), "Resolve", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_bridge = type;
			plugin.LogInfo("[FehuRoads] FCW legacy GUID resolver adapted to forteca.fehuroads.");
		}

		internal static void Clear(FehuRoadsPlugin plugin)
		{
			if (!(_bridge == null))
			{
				FieldInfo fieldInfo = AccessTools.Field(_bridge, "_gridPlugin");
				if (fieldInfo.GetValue(null) == plugin)
				{
					fieldInfo.SetValue(null, null);
					AccessTools.Field(_bridge, "_isConnectedByPavedRoad").SetValue(null, null);
				}
				_bridge = null;
			}
		}

		private static bool Resolve(ref bool __result, ref object ____gridPlugin, ref MethodInfo ____isConnectedByPavedRoad)
		{
			FehuRoadsPlugin instance = FehuRoadsPlugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return true;
			}
			____gridPlugin = instance;
			____isConnectedByPavedRoad = typeof(FehuRoadsPlugin).GetMethod("IsConnectedByPavedRoad");
			__result = true;
			return false;
		}
	}
}
namespace Forteca.FehuRoads.Core
{
	public enum RoadType : byte
	{
		None,
		Dirt,
		Paved
	}
	public struct RoadCell
	{
		public readonly int X;

		public readonly int Z;

		public RoadCell(int x, int z)
		{
			X = x;
			Z = z;
		}
	}
	public struct RoadChunkCoord : IEquatable<RoadChunkCoord>
	{
		public readonly int X;

		public readonly int Z;

		public RoadChunkCoord(int x, int z)
		{
			X = x;
			Z = z;
		}

		public bool Equals(RoadChunkCoord o)
		{
			if (X == o.X)
			{
				return Z == o.Z;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (X * 486187739) ^ Z;
		}
	}
	public sealed class RoadChunkData
	{
		public readonly RoadChunkCoord Coord;

		public readonly uint Revision;

		public readonly KeyValuePair<long, RoadType>[] Cells;

		public RoadChunkData(RoadChunkCoord c, uint r, KeyValuePair<long, RoadType>[] a)
		{
			Coord = c;
			Revision = r;
			Cells = a;
		}
	}
	public sealed class RoadDatabase
	{
		public const int ChunkSize = 32;

		private readonly Dictionary<long, RoadType> _cells = new Dictionary<long, RoadType>();

		private readonly Dictionary<RoadChunkCoord, HashSet<long>> _chunks = new Dictionary<RoadChunkCoord, HashSet<long>>();

		private readonly Dictionary<RoadChunkCoord, uint> _revisions = new Dictionary<RoadChunkCoord, uint>();

		public int Count => _cells.Count;

		public int ChunkCount => _chunks.Count;

		public IEnumerable<KeyValuePair<long, RoadType>> Entries => _cells;

		public IEnumerable<RoadChunkData> Chunks
		{
			get
			{
				foreach (RoadChunkCoord key in _chunks.Keys)
				{
					yield return GetChunk(key);
				}
			}
		}

		public event Action<RoadCell, RoadType> Changed;

		public event Action<RoadChunkCoord, uint> ChunkChanged;

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

		public static void Decode(long k, out int x, out int z)
		{
			x = (int)(k >> 32);
			z = (int)k;
		}

		private static int FloorDiv(int n, int d)
		{
			int num = n / d;
			if (n % d >= 0)
			{
				return num;
			}
			return num - 1;
		}

		public static RoadChunkCoord ChunkOf(int x, int z)
		{
			return new RoadChunkCoord(FloorDiv(x, 32), FloorDiv(z, 32));
		}

		public RoadType Get(int x, int z)
		{
			if (!_cells.TryGetValue(Key(x, z), out var value))
			{
				return RoadType.None;
			}
			return value;
		}

		public bool Set(int x, int z, RoadType t)
		{
			long num = Key(x, z);
			if (Get(x, z) == t)
			{
				return false;
			}
			RoadChunkCoord roadChunkCoord = ChunkOf(x, z);
			if (t == RoadType.None)
			{
				_cells.Remove(num);
				if (_chunks.TryGetValue(roadChunkCoord, out var value))
				{
					value.Remove(num);
					if (value.Count == 0)
					{
						_chunks.Remove(roadChunkCoord);
					}
				}
			}
			else
			{
				_cells[num] = t;
				if (!_chunks.TryGetValue(roadChunkCoord, out var value2))
				{
					value2 = new HashSet<long>();
					_chunks[roadChunkCoord] = value2;
				}
				value2.Add(num);
			}
			Touch(roadChunkCoord);
			this.Changed?.Invoke(new RoadCell(x, z), t);
			return true;
		}

		private void Touch(RoadChunkCoord c)
		{
			_revisions.TryGetValue(c, out var value);
			value++;
			_revisions[c] = value;
			this.ChunkChanged?.Invoke(c, value);
		}

		public void Query(int minX, int minZ, int maxX, int maxZ, List<KeyValuePair<long, RoadType>> dst)
		{
			dst.Clear();
			RoadChunkCoord roadChunkCoord = ChunkOf(minX, minZ);
			RoadChunkCoord roadChunkCoord2 = ChunkOf(maxX, maxZ);
			for (int i = roadChunkCoord.Z; i <= roadChunkCoord2.Z; i++)
			{
				for (int j = roadChunkCoord.X; j <= roadChunkCoord2.X; j++)
				{
					if (!_chunks.TryGetValue(new RoadChunkCoord(j, i), out var value))
					{
						continue;
					}
					foreach (long item in value)
					{
						Decode(item, out var x, out var z);
						if (x >= minX && x <= maxX && z >= minZ && z <= maxZ)
						{
							dst.Add(new KeyValuePair<long, RoadType>(item, _cells[item]));
						}
					}
				}
			}
		}

		public RoadChunkData GetChunk(RoadChunkCoord c)
		{
			_revisions.TryGetValue(c, out var value);
			if (!_chunks.TryGetValue(c, out var value2))
			{
				return new RoadChunkData(c, value, new KeyValuePair<long, RoadType>[0]);
			}
			KeyValuePair<long, RoadType>[] array = new KeyValuePair<long, RoadType>[value2.Count];
			int num = 0;
			foreach (long item in value2)
			{
				array[num++] = new KeyValuePair<long, RoadType>(item, _cells[item]);
			}
			return new RoadChunkData(c, value, array);
		}

		public bool ReplaceChunk(RoadChunkData d)
		{
			_revisions.TryGetValue(d.Coord, out var value);
			if (d.Revision <= value)
			{
				return false;
			}
			if (_chunks.TryGetValue(d.Coord, out var value2))
			{
				foreach (long item in value2)
				{
					_cells.Remove(item);
				}
				_chunks.Remove(d.Coord);
			}
			if (d.Cells.Length != 0)
			{
				HashSet<long> hashSet = new HashSet<long>();
				KeyValuePair<long, RoadType>[] cells = d.Cells;
				for (int i = 0; i < cells.Length; i++)
				{
					KeyValuePair<long, RoadType> keyValuePair = cells[i];
					if (keyValuePair.Value == RoadType.Dirt || keyValuePair.Value == RoadType.Paved)
					{
						_cells[keyValuePair.Key] = keyValuePair.Value;
						hashSet.Add(keyValuePair.Key);
					}
				}
				if (hashSet.Count > 0)
				{
					_chunks[d.Coord] = hashSet;
				}
			}
			_revisions[d.Coord] = d.Revision;
			this.ChunkChanged?.Invoke(d.Coord, d.Revision);
			return true;
		}

		public void Clear()
		{
			_cells.Clear();
			_chunks.Clear();
			_revisions.Clear();
		}

		public void Write(BinaryWriter w)
		{
			w.Write(_cells.Count);
			foreach (KeyValuePair<long, RoadType> cell in _cells)
			{
				w.Write(cell.Key);
				w.Write((byte)cell.Value);
			}
		}

		public void Read(BinaryReader r)
		{
			Clear();
			int num = r.ReadInt32();
			if (num < 0 || num > 20000000)
			{
				throw new InvalidDataException("Invalid road-cell count");
			}
			for (int i = 0; i < num; i++)
			{
				long k = r.ReadInt64();
				RoadType roadType = (RoadType)r.ReadByte();
				if (roadType == RoadType.Dirt || roadType == RoadType.Paved)
				{
					Decode(k, out var x, out var z);
					Set(x, z, roadType);
				}
			}
		}
	}
	public static class RoadProtocol
	{
		public const int Version = 1;

		public const int MaxCellsPerChunk = 2048;

		public const string RequestRpc = "FehuRoads_Request";

		public const string UpdateRpc = "FehuRoads_Update";

		public const string BeginRpc = "FehuRoads_Begin";

		public const string ChunkRpc = "FehuRoads_Chunk";

		public const string EndRpc = "FehuRoads_End";

		public const int MaxUpdateCells = 512;

		public static ZPackage Header(long worldUid)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0014: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(1);
			val.Write(worldUid);
			return val;
		}

		public static bool ReadAndValidateHeader(ZPackage package, long expectedWorldUid)
		{
			try
			{
				return package.ReadInt() == 1 && package.ReadLong() == expectedWorldUid;
			}
			catch
			{
				return false;
			}
		}

		public static ZPackage EncodeUpdate(long worldUid, IList<KeyValuePair<long, RoadType>> cells)
		{
			ZPackage val = Header(worldUid);
			val.Write(cells.Count);
			for (int i = 0; i < cells.Count; i++)
			{
				val.Write(cells[i].Key);
				val.Write((byte)cells[i].Value);
			}
			return val;
		}

		public static bool TryDecodeUpdate(ZPackage package, long expectedWorldUid, out KeyValuePair<long, RoadType>[] cells)
		{
			cells = null;
			if (!ReadAndValidateHeader(package, expectedWorldUid))
			{
				return false;
			}
			try
			{
				int num = package.ReadInt();
				if (num < 1 || num > 512)
				{
					return false;
				}
				cells = new KeyValuePair<long, RoadType>[num];
				for (int i = 0; i < num; i++)
				{
					long key = package.ReadLong();
					RoadType roadType = (RoadType)package.ReadByte();
					if (roadType != RoadType.None && roadType != RoadType.Dirt && roadType != RoadType.Paved)
					{
						return false;
					}
					cells[i] = new KeyValuePair<long, RoadType>(key, roadType);
				}
				return true;
			}
			catch
			{
				cells = null;
				return false;
			}
		}

		public static ZPackage EncodeChunk(long worldUid, RoadChunkData chunk)
		{
			ZPackage val = Header(worldUid);
			val.Write(chunk.Coord.X);
			val.Write(chunk.Coord.Z);
			val.Write(chunk.Revision);
			val.Write(chunk.Cells.Length);
			KeyValuePair<long, RoadType>[] cells = chunk.Cells;
			for (int i = 0; i < cells.Length; i++)
			{
				KeyValuePair<long, RoadType> keyValuePair = cells[i];
				val.Write(keyValuePair.Key);
				val.Write((byte)keyValuePair.Value);
			}
			return val;
		}

		public static bool TryDecodeChunk(ZPackage package, long expectedWorldUid, out RoadChunkData chunk)
		{
			chunk = null;
			if (!ReadAndValidateHeader(package, expectedWorldUid))
			{
				return false;
			}
			try
			{
				int x = package.ReadInt();
				int z = package.ReadInt();
				uint r = package.ReadUInt();
				int num = package.ReadInt();
				if (num < 0 || num > 2048)
				{
					return false;
				}
				KeyValuePair<long, RoadType>[] array = new KeyValuePair<long, RoadType>[num];
				for (int i = 0; i < num; i++)
				{
					long key = package.ReadLong();
					RoadType roadType = (RoadType)package.ReadByte();
					if (roadType != RoadType.Dirt && roadType != RoadType.Paved)
					{
						return false;
					}
					array[i] = new KeyValuePair<long, RoadType>(key, roadType);
				}
				chunk = new RoadChunkData(new RoadChunkCoord(x, z), r, array);
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
}