Decompiled source of TooManyLags Standalone v1.1.3

TooManyLagsStandalone.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Steamworks;
using UnityEngine;

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

internal sealed class AuthorityController
{
	private sealed class Node : AuthorityNode
	{
		private readonly AuthorityController owner;

		internal readonly ZDO Data;

		internal readonly Kinds Kind;

		internal Cell Sector;

		internal long SeenOwner;

		internal ushort SeenRevision;

		internal bool SeenUse;

		internal long RejectedOwner;

		internal ushort RejectedRevision;

		internal bool TextWait;

		internal Cell TextCell;

		internal RecipientRequirement Recipient;

		internal override long CurrentOwner => Data.GetOwner();

		internal Node(AuthorityController owner, ZDO data, Kinds kind, Cell cell, Cell sector)
		{
			this.owner = owner;
			Data = data;
			Kind = kind;
			Cell = cell;
			Sector = sector;
			SeenOwner = data.GetOwner();
			SeenRevision = data.OwnerRevision;
		}

		internal override ApplyResult Apply(long target)
		{
			//IL_0018: 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)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			if (!Data.IsValid() || !object.ReferenceEquals(ZDOMan.instance.GetZDO(Data.m_uid), Data))
			{
				return ApplyResult.Dropped;
			}
			if (TextWait || (TextEditLocked != null && TextEditLocked(Data)))
			{
				Managed = false;
				return ApplyResult.Done;
			}
			long num = ((TextEditTarget == null) ? 0 : TextEditTarget(Data));
			if (num != 0)
			{
				target = num;
			}
			if (target == 0)
			{
				return ApplyResult.Done;
			}
			if ((Kind == Kinds.Signs || Kind == Kinds.Portals) && (!Plugin.Network.TextCapable(Data.GetOwner()) || !Plugin.Network.TextCapable(target)))
			{
				return ApplyResult.Done;
			}
			if (Data.OwnerRevision == ushort.MaxValue || (RejectedOwner == Data.GetOwner() && RejectedRevision == Data.OwnerRevision))
			{
				return ApplyResult.Dropped;
			}
			if (!owner.Available(target, Data.GetPosition()))
			{
				return ApplyResult.Done;
			}
			if (Data.GetOwner() == target && !owner.Handoffs.Pending(Data.m_uid))
			{
				Managed = true;
				ManagedOwner = target;
				return ApplyResult.Done;
			}
			if (!owner.Available(Data.GetOwner(), Data.GetPosition()))
			{
				return ApplyResult.Done;
			}
			if (Data.GetLong(ZDOVars.s_user, 0L) != 0 || Data.GetBool(ZDOVars.s_attachJointHash, false) || (Kind == Kinds.TamedAnimals && (!Data.GetBool(ZDOVars.s_tamed, false) || !string.IsNullOrEmpty(Data.GetString(ZDOVars.s_follow, "")))))
			{
				return ApplyResult.Done;
			}
			if ((!Plugin.Network.Capable(Data.GetOwner()) || !Plugin.Network.Capable(target)) && !owner.NativeTransferSafe(Data))
			{
				return ApplyResult.Done;
			}
			owner.Handoffs.Request(Data, target, Kind, ZDOID.None);
			return ApplyResult.Pending;
		}
	}

	internal static Func<ZDO, long> TextEditTarget;

	internal static Func<ZDO, bool> TextEditLocked;

	internal static Action<long, ZDO, Vector3> TextEditMovement;

	private readonly Dictionary<Cell, HashSet<Node>> textWaiting = new Dictionary<Cell, HashSet<Node>>();

	private readonly Settings settings;

	private readonly OwnershipCadence cadence;

	private readonly CameraWake cameras = new CameraWake();

	private readonly ObjectCatalog catalog;

	private readonly AuthorityWorld index;

	private readonly RegionContentionGate regions = new RegionContentionGate();

	private readonly List<GridPeer> gridPeers = new List<GridPeer>(12);

	private readonly List<RegionPeer> regionPeers = new List<RegionPeer>(12);

	internal readonly List<PlayerPeer> Players = new List<PlayerPeer>(12);

	private readonly Dictionary<ZDOID, Node> nodes = new Dictionary<ZDOID, Node>();

	private readonly Dictionary<Cell, HashSet<Node>> sectors = new Dictionary<Cell, HashSet<Node>>();

	private readonly HashSet<Cell> interest = new HashSet<Cell>();

	private readonly List<Cell> retiring = new List<Cell>();

	private readonly List<ZDO> scan = new List<ZDO>();

	private readonly HashSet<SectorIndex> visited = new HashSet<SectorIndex>();

	private readonly Action<ZDOMan, Vector2s, List<ZDO>, HashSet<SectorIndex>> find;

	internal readonly Handoffs Handoffs;

	internal readonly RecipientReadiness Recipients;

	internal readonly MobPolicy Mobs;

	private int ranks;

	private int mobPeers;

	private bool failed;

	private bool interestDirty;

	internal bool Active
	{
		get
		{
			if (!failed && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
			{
				return ZDOMan.instance != null;
			}
			return false;
		}
	}

	internal bool ManagesText(ZDO data)
	{
		Kinds kinds = catalog.Prefab(data.GetPrefab());
		if (kinds != Kinds.Signs)
		{
			return kinds == Kinds.Portals;
		}
		return true;
	}

	internal bool PrepareTextEdit(ZDO data)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: 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_0047: 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)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		if (!Active || data == null || !data.IsValid())
		{
			return false;
		}
		if (!nodes.TryGetValue(data.m_uid, out var value))
		{
			Kinds kinds = catalog.Prefab(data.GetPrefab());
			Vector3 position = data.GetPosition();
			Vector2s sector = data.GetSector();
			if ((kinds != Kinds.Signs && kinds != Kinds.Portals) || !Cell.At(position.x, position.z, settings.CellSize, out var cell))
			{
				return false;
			}
			value = new Node(this, data, kinds, cell, new Cell(sector.x, sector.y));
			nodes.Add(data.m_uid, value);
			AddSector(value);
			index.Add(value, Time.unscaledTime);
		}
		if (!object.ReferenceEquals(value.Data, data) || (value.Kind != Kinds.Signs && value.Kind != Kinds.Portals))
		{
			return false;
		}
		ForgetTextWait(value);
		value.RejectedOwner = 0L;
		index.Received(value, Time.unscaledTime);
		cadence.Request();
		return true;
	}

	internal void EndTextEdit(ZDO data)
	{
		//IL_000a: 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)
		if (data == null || !nodes.TryGetValue(data.m_uid, out var value) || !object.ReferenceEquals(value.Data, data))
		{
			return;
		}
		if (!interest.Contains(value.Sector) && (TextEditTarget == null || TextEditTarget(data) == 0) && (TextEditLocked == null || !TextEditLocked(data)))
		{
			Remove(value);
			return;
		}
		Handoffs.Cancel(data.m_uid);
		index.Dismiss(value);
		if (!value.TextWait)
		{
			value.TextWait = true;
			value.TextCell = value.Cell;
			if (!textWaiting.TryGetValue(value.Cell, out var value2))
			{
				value2 = new HashSet<Node>();
				textWaiting.Add(value.Cell, value2);
			}
			value2.Add(value);
			index.Grid.Renewed = RenewTextWait;
		}
	}

	private void ForgetTextWait(Node node)
	{
		if (!node.TextWait)
		{
			return;
		}
		node.TextWait = false;
		if (textWaiting.TryGetValue(node.TextCell, out var value))
		{
			value.Remove(node);
			if (value.Count == 0)
			{
				textWaiting.Remove(node.TextCell);
			}
		}
		if (textWaiting.Count == 0)
		{
			index.Grid.Renewed = null;
		}
	}

	private void RenewTextWait(Cell cell)
	{
		if (!textWaiting.TryGetValue(cell, out var value))
		{
			return;
		}
		textWaiting.Remove(cell);
		foreach (Node item in value)
		{
			item.TextWait = false;
			index.Received(item, Time.unscaledTime);
		}
		if (textWaiting.Count == 0)
		{
			index.Grid.Renewed = null;
		}
	}

	internal AuthorityController(Settings settings)
	{
		this.settings = settings;
		cadence = new OwnershipCadence(settings.Interval);
		catalog = new ObjectCatalog(settings.Categories);
		index = new AuthorityWorld(0L, settings.Full, settings.Pattern, settings.Keep, settings.Directional, settings.Inner, settings.Outer, settings.CellSize == 4f, settings.Forward, Plugin.Network.Latency, settings.Margin, settings.OverlapCooldown);
		find = AccessTools.MethodDelegate<Action<ZDOMan, Vector2s, List<ZDO>, HashSet<SectorIndex>>>(AccessTools.Method(typeof(ZDOMan), "FindObjects", (Type[])null, (Type[])null), (object)null, true);
		Handoffs = new Handoffs(this);
		Recipients = new RecipientReadiness(this);
		Mobs = new MobPolicy(this);
		index.AfterGridUpdate = SyncInterest;
	}

	internal void Configure(string key)
	{
		if (key == "MovementRotationCheckIntervalSeconds")
		{
			cadence.Configure(settings.Interval);
		}
		index.Grid.ConfigureDelays(settings.Full, settings.Inner, settings.Forward, settings.Outer);
		index.Grid.ConfigureOverlapCooldown(settings.OverlapCooldown);
		if (key == "HighTargetPingMs" || key == "NearbyAlternativeOwnerRadiusMeters")
		{
			Mobs.RanksChanged();
		}
	}

	internal bool Shared(long uid)
	{
		if (Active)
		{
			return regions.Shared(uid);
		}
		return false;
	}

	internal bool WatchMobs(long uid)
	{
		if (mobPeers > 1)
		{
			return Shared(uid);
		}
		return false;
	}

	internal bool NativeTransferSafe(ZDO data)
	{
		return catalog.NativeTransferSafe(data.GetPrefab());
	}

	internal bool Available(long uid, Vector3 point)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		if (!Active || uid == 0 || !Plugin.Network.Present(uid) || !Finite(point))
		{
			return false;
		}
		foreach (PlayerPeer player in Players)
		{
			if (player.Uid == uid && player.Character != null && player.Character.IsValid() && player.Character.GetFloat(ZDOVars.s_health, 1f) > 0f && Finite(player.Reference) && ZNetScene.InActiveArea(point, player.Reference))
			{
				return true;
			}
		}
		return false;
	}

	internal void Poll(float now)
	{
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: 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_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		if (!Active || !cadence.Due(now) || !Object.op_Implicit((Object)(object)ZoneSystem.instance) || !Object.op_Implicit((Object)(object)ZNetScene.instance))
		{
			return;
		}
		try
		{
			Plugin.Network.Players(Players);
			Players.Sort((PlayerPeer a, PlayerPeer b) => a.Uid.CompareTo(b.Uid));
			regionPeers.Clear();
			gridPeers.Clear();
			cameras.Clear();
			mobPeers = 0;
			foreach (PlayerPeer player in Players)
			{
				if (settings.Mobs && Plugin.Network.MobCapable(player.Uid))
				{
					mobPeers++;
				}
				Vector3 position = player.Character.GetPosition();
				Vector2s zone = ZoneSystem.GetZone(player.Reference);
				Vector2s zone2 = ZoneSystem.GetZone(position);
				if (TextEditMovement != null)
				{
					TextEditMovement(player.Uid, player.Character, position);
				}
				regionPeers.Add(new RegionPeer(player.Uid, new Cell(zone.x, zone.y), Finite(player.Reference), new Cell(zone2.x, zone2.y), Finite(position)));
			}
			if (regions.Update(regionPeers))
			{
				interestDirty = true;
				Mobs.RanksChanged();
			}
			foreach (PlayerPeer player2 in Players)
			{
				if (regions.Shared(player2.Uid))
				{
					Vector3 position2 = player2.Character.GetPosition();
					if (Cell.At(position2.x, position2.z, settings.CellSize, out var cell))
					{
						gridPeers.Add(GridPeer.Covered(player2.Uid, cell, settings.Directional ? CameraHeading.Read(player2.Character, player2.Uid, Plugin.Network.Capable(player2.Uid), cameras) : 0));
					}
				}
			}
			if (ranks != Plugin.Network.RankVersion)
			{
				ranks = Plugin.Network.RankVersion;
				index.Grid.RanksChanged();
				Mobs.RanksChanged();
			}
			index.Tick(gridPeers, now);
			Mobs.Tick(now);
			Handoffs.Tick(now);
			RequestRouter.Flush(now);
			if (Plugin.Local != null && !ZNet.instance.IsDedicated())
			{
				Plugin.Local.SetMobWatch(settings.Mobs && WatchMobs(ZDOMan.GetSessionID()));
			}
			Plugin.Network.FlushAll();
		}
		catch (Exception error)
		{
			Stop();
			Plugin.Fault(error);
		}
	}

	private void SyncInterest()
	{
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		if (!interestDirty)
		{
			return;
		}
		interestDirty = false;
		retiring.Clear();
		foreach (Cell item in interest)
		{
			if (!regions.ZoneKeys.Contains(item))
			{
				retiring.Add(item);
			}
		}
		foreach (Cell item2 in retiring)
		{
			interest.Remove(item2);
			if (!sectors.TryGetValue(item2, out var value))
			{
				continue;
			}
			List<Node> list = new List<Node>(value);
			foreach (Node item3 in list)
			{
				if ((TextEditTarget == null || TextEditTarget(item3.Data) == 0) && (TextEditLocked == null || !TextEditLocked(item3.Data)))
				{
					Remove(item3);
				}
			}
		}
		foreach (Cell zoneKey in regions.ZoneKeys)
		{
			if (!interest.Add(zoneKey))
			{
				continue;
			}
			scan.Clear();
			visited.Clear();
			find(ZDOMan.instance, new Vector2s((short)zoneKey.X, (short)zoneKey.Z), scan, visited);
			foreach (ZDO item4 in scan)
			{
				Changed(item4);
			}
		}
		scan.Clear();
		visited.Clear();
		retiring.Clear();
	}

	internal void CapabilityChanged(long uid)
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		if (!Active || !Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ZoneSystem.instance))
		{
			return;
		}
		foreach (Cell item in interest)
		{
			scan.Clear();
			visited.Clear();
			find(ZDOMan.instance, new Vector2s((short)item.X, (short)item.Z), scan, visited);
			foreach (ZDO item2 in scan)
			{
				if (item2.GetOwner() == uid)
				{
					Changed(item2);
				}
			}
		}
		scan.Clear();
		visited.Clear();
		foreach (Node value in nodes.Values)
		{
			if (value.Data.GetOwner() == uid || index.Grid.Owner(value.Cell) == uid)
			{
				index.Received(value, Time.unscaledTime);
			}
		}
	}

	internal void Changed(ZDO data)
	{
		//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_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: 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_0164: 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_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
		if (!Active || data == null || !data.IsValid())
		{
			return;
		}
		if (cameras.Changed(data))
		{
			cadence.Request();
		}
		Handoffs.Observe(data);
		Mobs.Changed(data);
		Vector2s sector = data.GetSector();
		Cell cell = new Cell(sector.x, sector.y);
		Node value;
		if (!interest.Contains(cell) && (TextEditTarget == null || TextEditTarget(data) == 0) && (TextEditLocked == null || !TextEditLocked(data)))
		{
			if (nodes.TryGetValue(data.m_uid, out value))
			{
				Remove(value);
			}
			return;
		}
		Kinds kinds = catalog.Prefab(data.GetPrefab());
		if (kinds == Kinds.None || (kinds == Kinds.Incinerators && !IncineratorProtection.Supported) || (kinds == Kinds.TamedAnimals && (!data.GetBool(ZDOVars.s_tamed, false) || MobPolicy.FriendlyPrefab(data.GetPrefab()))))
		{
			if (nodes.TryGetValue(data.m_uid, out value))
			{
				Remove(value);
			}
			return;
		}
		if (!Plugin.Network.Capable(data.GetOwner()) && !catalog.NativeTransferSafe(data.GetPrefab()))
		{
			if (nodes.TryGetValue(data.m_uid, out value))
			{
				Remove(value);
			}
			return;
		}
		Vector3 position = data.GetPosition();
		if (!Finite(position) || !Cell.At(position.x, position.z, settings.CellSize, out var cell2))
		{
			return;
		}
		if (!nodes.TryGetValue(data.m_uid, out value))
		{
			value = new Node(this, data, kinds, cell2, cell);
			nodes.Add(data.m_uid, value);
			AddSector(value);
			index.Add(value, Time.unscaledTime);
			return;
		}
		if (!object.ReferenceEquals(value.Data, data) || value.Kind != kinds)
		{
			Remove(value);
			Changed(data);
			return;
		}
		if (!value.Sector.Equals(cell))
		{
			RemoveSector(value);
			value.Sector = cell;
			AddSector(value);
		}
		if (!value.Cell.Equals(cell2))
		{
			index.Move(value, cell2, Time.unscaledTime);
		}
		long owner = data.GetOwner();
		ushort ownerRevision = data.OwnerRevision;
		if (owner != value.SeenOwner || ownerRevision != value.SeenRevision)
		{
			value.SeenOwner = owner;
			value.SeenRevision = ownerRevision;
			index.Received(value, Time.unscaledTime);
		}
		bool flag = data.GetLong(ZDOVars.s_user, 0L) != 0 || data.GetBool(ZDOVars.s_attachJointHash, false) || (kinds == Kinds.TamedAnimals && !string.IsNullOrEmpty(data.GetString(ZDOVars.s_follow, "")));
		if (flag != value.SeenUse)
		{
			value.SeenUse = flag;
			index.Received(value, Time.unscaledTime);
		}
	}

	internal void Destroyed(ZDOID id)
	{
		//IL_0006: 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_0029: Unknown result type (might be due to invalid IL or missing references)
		if (nodes.TryGetValue(id, out var value))
		{
			Remove(value);
		}
		Handoffs.Forget(id);
		Mobs.Forget(id);
	}

	private void AddSector(Node node)
	{
		if (!sectors.TryGetValue(node.Sector, out var value))
		{
			value = new HashSet<Node>();
			sectors.Add(node.Sector, value);
		}
		value.Add(node);
	}

	private void RemoveSector(Node node)
	{
		if (sectors.TryGetValue(node.Sector, out var value))
		{
			value.Remove(node);
			if (value.Count == 0)
			{
				sectors.Remove(node.Sector);
			}
		}
	}

	private void Remove(Node node)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		ForgetTextWait(node);
		index.Remove(node);
		nodes.Remove(node.Data.m_uid);
		RemoveSector(node);
		Handoffs.Cancel(node.Data.m_uid);
		Recipients.Forget(node.Data.m_uid);
	}

	internal void RecordRecipient(ZDO data, long owner, ushort revision, uint state)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		if (nodes.TryGetValue(data.m_uid, out var value) && object.ReferenceEquals(value.Data, data))
		{
			value.Recipient.Include(owner, revision, state);
		}
		else
		{
			Mobs.RecordRecipient(data, owner, revision, state);
		}
	}

	internal bool TryRecipientState(ZDO data, long owner, out uint state)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		state = 0u;
		if (nodes.TryGetValue(data.m_uid, out var value) && object.ReferenceEquals(value.Data, data))
		{
			if (!value.Recipient.Matches(owner, data.OwnerRevision))
			{
				return false;
			}
			state = value.Recipient.State;
			return true;
		}
		return Mobs.TryRecipientState(data, owner, out state);
	}

	internal long Desired(ZDO data, Kinds kind, ZDOID target)
	{
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		if (!Active || data == null || !data.IsValid())
		{
			return 0L;
		}
		long num = ((TextEditTarget == null) ? 0 : TextEditTarget(data));
		if (num != 0)
		{
			return num;
		}
		if (TextEditLocked != null && TextEditLocked(data))
		{
			return data.GetOwner();
		}
		if (kind == Kinds.None)
		{
			return Mobs.Desired(data, target);
		}
		if (!nodes.TryGetValue(data.m_uid, out var value) || !object.ReferenceEquals(value.Data, data))
		{
			return 0L;
		}
		return index.Grid.Owner(value.Cell);
	}

	internal bool IsManaged(ZDO data, int method)
	{
		//IL_0014: 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)
		if (!Active || data == null)
		{
			return false;
		}
		if (!nodes.TryGetValue(data.m_uid, out var value) || !ObjectCatalog.OwnerRequest(value.Kind, method))
		{
			return Mobs.Managed(data.m_uid, method);
		}
		return true;
	}

	internal void Wake(ZDOID id)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		if (nodes.TryGetValue(id, out var value))
		{
			index.Received(value, Time.unscaledTime);
		}
		Mobs.Wake(id);
	}

	internal void Rejected(ZDOID id)
	{
		//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)
		if (nodes.TryGetValue(id, out var value))
		{
			value.RejectedOwner = value.Data.GetOwner();
			value.RejectedRevision = value.Data.OwnerRevision;
		}
		Mobs.Forget(id);
	}

	internal void CameraChanged(ZDO data)
	{
		if (Active && cameras.Changed(data))
		{
			cadence.Request();
		}
	}

	internal void Stop()
	{
		failed = true;
		Handoffs.Clear();
		Recipients.Reset();
		Mobs.Clear();
		nodes.Clear();
		textWaiting.Clear();
		index.Grid.Renewed = null;
		sectors.Clear();
		interest.Clear();
		regions.Clear();
		cameras.Clear();
		Players.Clear();
		gridPeers.Clear();
		regionPeers.Clear();
	}

	internal static bool Finite(Vector3 value)
	{
		if (!float.IsNaN(value.x) && !float.IsNaN(value.y) && !float.IsNaN(value.z) && !float.IsInfinity(value.x) && !float.IsInfinity(value.y))
		{
			return !float.IsInfinity(value.z);
		}
		return false;
	}
}
internal abstract class AuthorityNode
{
	internal Cell Cell;

	internal bool Managed;

	internal bool Removed;

	internal long ManagedOwner;

	internal long ConfirmedFieldOwner;

	internal AuthorityWorld.ObjectBucket IndexedBucket;

	internal float NotBefore;

	internal abstract long CurrentOwner { get; }

	internal abstract ApplyResult Apply(long target);

	internal virtual bool CanRemember(long fieldOwner)
	{
		if (Managed && ManagedOwner == fieldOwner)
		{
			return CurrentOwner == fieldOwner;
		}
		return false;
	}
}
internal enum GridCoveragePattern
{
	Square3x3,
	Rounded5x5,
	Rounded7x7
}
internal enum FieldTier : byte
{
	Outer,
	Inner,
	Forward
}
internal struct Cell : IEquatable<Cell>
{
	internal int X;

	internal int Z;

	internal Cell(int x, int z)
	{
		X = x;
		Z = z;
	}

	internal static bool At(float x, float z, out Cell cell)
	{
		return At(x, z, 8f, out cell);
	}

	internal static bool At(float x, float z, float size, out Cell cell)
	{
		cell = default(Cell);
		int num = Subdivisions(size);
		if (num == 0)
		{
			return false;
		}
		if (float.IsNaN(x) || float.IsNaN(z) || float.IsInfinity(x) || float.IsInfinity(z))
		{
			return false;
		}
		double num2 = (double)num / 64.0;
		double num3 = Math.Floor(((double)x + 32.0) * num2);
		double num4 = Math.Floor(((double)z + 32.0) * num2);
		int num5 = 256 * num;
		if (num3 < (double)(-num5) || num3 >= (double)num5 || num4 < (double)(-num5) || num4 >= (double)num5)
		{
			return false;
		}
		cell = new Cell((int)num3, (int)num4);
		return true;
	}

	internal static int Subdivisions(float size)
	{
		if (size != 4f)
		{
			if (size != 6.4f)
			{
				if (size != 8f)
				{
					if (size != 16f)
					{
						return 0;
					}
					return 4;
				}
				return 8;
			}
			return 10;
		}
		return 16;
	}

	internal static double Edge(int coordinate, int subdivisions)
	{
		return (double)coordinate * 64.0 / (double)subdivisions - 32.0;
	}

	internal static Cell Zone(Cell fine, float size)
	{
		if (size == 6.4f)
		{
			return new Cell(Floor10(fine.X), Floor10(fine.Z));
		}
		int num = ((size == 4f) ? 4 : ((size == 16f) ? 2 : 3));
		return new Cell(fine.X >> num, fine.Z >> num);
	}

	private static int Floor10(int value)
	{
		if (value < 0)
		{
			return (value + 1) / 10 - 1;
		}
		return value / 10;
	}

	public bool Equals(Cell other)
	{
		if (X == other.X)
		{
			return Z == other.Z;
		}
		return false;
	}

	public override bool Equals(object other)
	{
		if (other is Cell)
		{
			return Equals((Cell)other);
		}
		return false;
	}

	public override int GetHashCode()
	{
		return (X * 397) ^ Z;
	}
}
internal struct GridPeer
{
	internal long Uid;

	internal Cell Cell;

	internal float Yaw;

	internal int Coverage;

	internal GridPeer(long uid, Cell cell, float yaw = 0f, int coverage = -1)
	{
		Uid = uid;
		Cell = cell;
		Yaw = yaw;
		Coverage = coverage;
	}

	internal static GridPeer Covered(long uid, Cell cell, int coverage)
	{
		return new GridPeer(uid, cell, float.NaN, coverage);
	}
}
internal sealed class AuthorityGrid
{
	private sealed class Policy
	{
		internal long Candidate;

		internal long Owner;

		internal long Uids;

		internal int Count;

		internal int FastCount;

		internal int ForwardCount;

		internal bool Shared;

		internal float Since;

		internal float Wait;

		internal float Deadline;

		internal float OverlapUntil;

		internal bool Deferred;

		internal Request First;

		internal List<Request> Others;
	}

	private struct Request
	{
		internal long Uid;

		internal float Since;

		internal FieldTier Tier;

		internal Request(long uid, float since, FieldTier tier)
		{
			Uid = uid;
			Since = since;
			Tier = tier;
		}
	}

	private sealed class PeerState
	{
		internal Cell Cell;

		internal float Yaw;

		internal int Heading;

		internal bool Refreshed;
	}

	private struct Offset
	{
		internal Cell Cell;

		internal FieldTier Tier;

		internal Offset(int x, int z, FieldTier tier)
		{
			Cell = new Cell(x, z);
			Tier = tier;
		}
	}

	internal const int CoverageCount = 56;

	private readonly Dictionary<Cell, Policy> policies = new Dictionary<Cell, Policy>();

	private readonly Stack<Policy> reusable = new Stack<Policy>();

	private readonly Dictionary<long, PeerState> previous = new Dictionary<long, PeerState>();

	private readonly Dictionary<Cell, long> remembered = new Dictionary<Cell, long>();

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

	private readonly List<long> departed = new List<long>();

	private readonly HashSet<Cell> dirty = new HashSet<Cell>();

	private readonly HashSet<Cell> pending = new HashSet<Cell>();

	private readonly List<Cell> due = new List<Cell>();

	internal readonly List<Cell> Changes = new List<Cell>();

	private readonly long server;

	private readonly Offset[][] footprints = new Offset[56][];

	private readonly Dictionary<Cell, FieldTier>[] maskTypes = new Dictionary<Cell, FieldTier>[56];

	internal readonly HashSet<Cell> Accelerations = new HashSet<Cell>();

	internal Action<Cell> Renewed;

	private readonly bool directional;

	private readonly bool discardVacant;

	private float innerDelay;

	private float outerDelay;

	private float forwardDelay;

	private float overlapCooldown;

	internal float Delay;

	private float lastTime;

	private float nextDue = float.PositiveInfinity;

	private int deferredCells;

	private int coolingCells;

	private readonly Func<long, float> latency;

	private readonly float margin;

	private bool ranksDirty;

	internal int Rebuilds;

	internal int NeighborReads;

	internal int PlayerUpdates;

	internal int TimerVisits;

	internal int PolicyAllocations;

	internal int RememberedCells => remembered.Count;

	internal IEnumerable<Cell> CoveredCells
	{
		get
		{
			foreach (KeyValuePair<Cell, Policy> item in policies)
			{
				KeyValuePair<Cell, Policy> keyValuePair = item;
				if (keyValuePair.Value.Count != 0)
				{
					KeyValuePair<Cell, Policy> keyValuePair2 = item;
					yield return keyValuePair2.Key;
				}
			}
		}
	}

	internal bool Directional => directional;

	internal bool HasPeers => previous.Count != 0;

	internal int CachedCells => policies.Count;

	internal int ReusablePolicies => reusable.Count;

	internal int DeferredCells => deferredCells;

	internal int CoolingCells => coolingCells;

	internal AuthorityGrid(long server, float delay, GridCoveragePattern pattern = GridCoveragePattern.Square3x3, bool directional = false, float innerDelay = 0f, float outerDelay = 3f, bool discardVacant = false, bool forward = false, float forwardDelay = 0.2f, Func<long, float> latency = null, float margin = 30f, float overlapCooldown = 0f, bool fullRear = false)
	{
		this.latency = latency;
		this.margin = margin;
		this.server = server;
		Delay = delay;
		this.directional = directional;
		this.discardVacant = discardVacant;
		this.innerDelay = SafeDelay(innerDelay, 0f);
		this.outerDelay = SafeDelay(outerDelay, 3f);
		this.forwardDelay = SafeDelay(forwardDelay, 0.2f);
		this.overlapCooldown = SafeDelay(overlapCooldown, 1f);
		int num = pattern switch
		{
			GridCoveragePattern.Rounded5x5 => 2, 
			GridCoveragePattern.Rounded7x7 => 3, 
			_ => 1, 
		};
		forward = directional && forward && num > 1;
		int[] array = new int[8] { 0, 1, 1, 1, 0, -1, -1, -1 };
		int[] array2 = new int[8] { 1, 1, 0, -1, -1, -1, 0, 1 };
		for (int i = 0; i < 8; i++)
		{
			List<Offset> list = new List<Offset>(37);
			for (int j = -num; j <= num; j++)
			{
				for (int k = -num; k <= num; k++)
				{
					int num2 = j * array[i] + k * array2[i];
					int value = -j * array2[i] + k * array[i];
					bool flag = array[i] != 0 && array2[i] != 0;
					bool flag2 = forward && ((!flag) ? (num2 == 2 && Math.Abs(value) <= 1) : ((j == 2 * array[i] && (k == array2[i] || k == 2 * array2[i])) || (j == array[i] && k == 2 * array2[i])));
					if ((num == 1 || j * j + k * k <= num * (num + 1) || flag2) && (!directional || fullRear || num2 >= 0 || (num2 >= -1 && Math.Abs(value) > 1)))
					{
						bool flag3 = false;
						if (directional)
						{
							flag3 = (fullRear ? (Math.Abs(j) <= 1 && Math.Abs(k) <= 1) : ((array[i] != 0 && array2[i] != 0) ? ((j == 0 && k == 0) || (num2 == 0 && Math.Abs(j) == 1 && Math.Abs(k) == 1) || (j == array[i] && k == array2[i]) || (j == array[i] && k == 0) || (j == 0 && k == array2[i])) : (num2 >= 0 && num2 <= 1 && Math.Abs(value) <= 1)));
						}
						list.Add(new Offset(j, k, flag3 ? FieldTier.Inner : (flag2 ? FieldTier.Forward : FieldTier.Outer)));
					}
				}
			}
			footprints[i] = list.ToArray();
			Dictionary<Cell, FieldTier> dictionary = new Dictionary<Cell, FieldTier>(list.Count);
			foreach (Offset item in list)
			{
				dictionary.Add(item.Cell, item.Tier);
			}
			maskTypes[i] = dictionary;
		}
		for (int l = 2; l <= 3; l++)
		{
			for (int m = 0; m < 8; m++)
			{
				int num3 = (l - 1) * 8 + m;
				int num4 = (l - 2) * 8 + m;
				if (!directional)
				{
					footprints[num3] = footprints[m];
					maskTypes[num3] = maskTypes[m];
					continue;
				}
				Dictionary<Cell, FieldTier> dictionary2 = new Dictionary<Cell, FieldTier>(maskTypes[num4]);
				Offset[] array3 = footprints[(m + l - 1) & 7];
				for (int n = 0; n < array3.Length; n++)
				{
					Offset offset = array3[n];
					if (!dictionary2.TryGetValue(offset.Cell, out var value2) || offset.Tier == FieldTier.Inner || (value2 == FieldTier.Outer && offset.Tier == FieldTier.Forward))
					{
						dictionary2[offset.Cell] = offset.Tier;
					}
				}
				List<Offset> list2 = new List<Offset>(dictionary2.Count);
				foreach (KeyValuePair<Cell, FieldTier> item2 in dictionary2)
				{
					list2.Add(new Offset(item2.Key.X, item2.Key.Z, item2.Value));
				}
				footprints[num3] = list2.ToArray();
				maskTypes[num3] = dictionary2;
			}
		}
		for (int num5 = 0; num5 < 16; num5++)
		{
			for (int num6 = 0; num6 < 2; num6++)
			{
				int num7 = 24 + num6 * 16 + num5;
				if (!directional)
				{
					footprints[num7] = footprints[num5];
					maskTypes[num7] = maskTypes[num5];
					continue;
				}
				int num8 = num5 & 7;
				int num9 = ((num6 == 0) ? ((num8 + ((num5 < 8) ? 1 : 2)) & 7) : ((num8 + 7) & 7));
				Dictionary<Cell, FieldTier> dictionary3 = new Dictionary<Cell, FieldTier>(maskTypes[num5]);
				Offset[] array4 = footprints[num9];
				for (int num10 = 0; num10 < array4.Length; num10++)
				{
					Offset offset2 = array4[num10];
					if (!dictionary3.ContainsKey(offset2.Cell))
					{
						dictionary3.Add(offset2.Cell, FieldTier.Inner);
					}
				}
				List<Offset> list3 = new List<Offset>(dictionary3.Count);
				foreach (KeyValuePair<Cell, FieldTier> item3 in dictionary3)
				{
					list3.Add(new Offset(item3.Key.X, item3.Key.Z, item3.Value));
				}
				footprints[num7] = list3.ToArray();
				maskTypes[num7] = dictionary3;
			}
		}
	}

	internal static int HeadingCoverage(float yaw, float overlapDegrees = 30f)
	{
		if (float.IsNaN(yaw) || float.IsInfinity(yaw))
		{
			return -1;
		}
		yaw %= 360f;
		if (yaw < 0f)
		{
			yaw += 360f;
		}
		int num = (int)(yaw / 45f);
		float num2 = yaw - (float)num * 45f;
		if (float.IsNaN(overlapDegrees) || float.IsInfinity(overlapDegrees))
		{
			overlapDegrees = 30f;
		}
		overlapDegrees = Math.Max(0f, Math.Min(45f, overlapDegrees));
		if (overlapDegrees == 0f)
		{
			if (!(num2 < 22.5f))
			{
				return (num + 1) & 7;
			}
			return num;
		}
		float num3 = (45f - overlapDegrees) * 0.5f;
		float num4 = (45f + overlapDegrees) * 0.5f;
		if (!(num2 < num3))
		{
			if (!(num2 <= num4))
			{
				return (num + 1) & 7;
			}
			return 8 + num;
		}
		return num;
	}

	internal void ConfigureDelays(float full, float inner, float forward, float outer)
	{
		Delay = SafeDelay(full, 2f);
		innerDelay = SafeDelay(inner, 0f);
		forwardDelay = SafeDelay(forward, 0.2f);
		outerDelay = SafeDelay(outer, 3f);
	}

	internal void ConfigureOverlapCooldown(float seconds)
	{
		overlapCooldown = SafeDelay(seconds, 1f);
	}

	private static float SafeDelay(float value, float fallback)
	{
		if (!float.IsNaN(value) && !float.IsInfinity(value))
		{
			return Math.Max(0f, Math.Min(30f, value));
		}
		return fallback;
	}

	private static float Yaw(float value, float fallback)
	{
		if (float.IsNaN(value) || float.IsInfinity(value))
		{
			return fallback;
		}
		value %= 360f;
		if (!(value < 0f))
		{
			return value;
		}
		return value + 360f;
	}

	internal long Owner(Cell cell)
	{
		if (!policies.TryGetValue(cell, out var value))
		{
			return 0L;
		}
		return value.Owner;
	}

	internal long Candidate(Cell cell)
	{
		if (!policies.TryGetValue(cell, out var value))
		{
			return 0L;
		}
		return value.Candidate;
	}

	internal int WorkPriority(Cell cell)
	{
		if (!policies.TryGetValue(cell, out var value) || value.Count == 0)
		{
			return 3;
		}
		if (directional)
		{
			if (value.FastCount == 0)
			{
				if (value.ForwardCount == 0)
				{
					return 2;
				}
				return 1;
			}
			return 0;
		}
		return 2;
	}

	private float FieldWait(Policy policy)
	{
		if (!directional)
		{
			return Delay;
		}
		if (policy.ForwardCount != 0)
		{
			float num = forwardDelay;
			if (policy.FastCount != 0)
			{
				num = Math.Min(num, innerDelay);
			}
			if (policy.Count > policy.FastCount + policy.ForwardCount)
			{
				num = Math.Min(num, outerDelay);
			}
			return num;
		}
		if (policy.FastCount == 0)
		{
			return outerDelay;
		}
		if (policy.FastCount != policy.Count)
		{
			return Math.Min(innerDelay, outerDelay);
		}
		return innerDelay;
	}

	internal float Wait(Cell cell)
	{
		if (!policies.TryGetValue(cell, out var value))
		{
			if (!directional)
			{
				return Delay;
			}
			return outerDelay;
		}
		return FieldWait(value);
	}

	internal float Remaining(Cell cell, float now)
	{
		if (!policies.TryGetValue(cell, out var value) || value.Owner == value.Candidate)
		{
			return 0f;
		}
		return Math.Max(0f, value.Deadline - now);
	}

	internal bool IsRemembered(Cell cell, long uid)
	{
		if (uid != 0 && uid != server && remembered.TryGetValue(cell, out var value))
		{
			return value == uid;
		}
		return false;
	}

	internal void Remember(Cell cell, long uid)
	{
		if (uid != 0 && uid != server && Owner(cell) == uid && Candidate(cell) == uid)
		{
			remembered[cell] = uid;
		}
	}

	internal void Forget(Cell cell)
	{
		remembered.Remove(cell);
	}

	private void Contribute(long uid, PeerState peer, bool add, float now)
	{
		Offset[] array = footprints[peer.Heading];
		for (int i = 0; i < array.Length; i++)
		{
			Offset offset = array[i];
			Contribution(uid, new Cell(peer.Cell.X + offset.Cell.X, peer.Cell.Z + offset.Cell.Z), offset.Tier, add, now);
		}
	}

	private void Contribution(long uid, Cell cell, FieldTier tier, bool add, float now)
	{
		NeighborReads++;
		if (!policies.TryGetValue(cell, out var value))
		{
			if (reusable.Count != 0)
			{
				value = reusable.Pop();
			}
			else
			{
				value = new Policy();
				PolicyAllocations++;
			}
			policies.Add(cell, value);
		}
		value.Count += (add ? 1 : (-1));
		value.Uids ^= uid;
		switch (tier)
		{
		case FieldTier.Inner:
			value.FastCount += (add ? 1 : (-1));
			break;
		case FieldTier.Forward:
			value.ForwardCount += (add ? 1 : (-1));
			break;
		}
		if (add)
		{
			Request request = new Request(uid, now, tier);
			if (value.Count == 1)
			{
				value.First = request;
			}
			else
			{
				if (value.Others == null)
				{
					value.Others = new List<Request>(1);
				}
				value.Others.Add(request);
			}
			if (remembered.Count != 0 && remembered.TryGetValue(cell, out var value2) && value2 != uid)
			{
				remembered.Remove(cell);
			}
		}
		else if (value.First.Uid == uid)
		{
			if (value.Others != null && value.Others.Count != 0)
			{
				int index = value.Others.Count - 1;
				value.First = value.Others[index];
				value.Others.RemoveAt(index);
			}
			else
			{
				value.First = default(Request);
			}
		}
		else if (value.Others != null)
		{
			for (int i = 0; i < value.Others.Count; i++)
			{
				if (value.Others[i].Uid == uid)
				{
					value.Others.RemoveAt(i);
					break;
				}
			}
		}
		dirty.Add(cell);
		if (add && Renewed != null)
		{
			Renewed(cell);
		}
	}

	private void Reclassify(long uid, Cell cell, FieldTier before, FieldTier after)
	{
		Policy policy = policies[cell];
		NeighborReads += 2;
		switch (before)
		{
		case FieldTier.Inner:
			policy.FastCount--;
			break;
		case FieldTier.Forward:
			policy.ForwardCount--;
			break;
		}
		switch (after)
		{
		case FieldTier.Inner:
			policy.FastCount++;
			break;
		case FieldTier.Forward:
			policy.ForwardCount++;
			break;
		}
		if (policy.First.Uid == uid)
		{
			policy.First.Tier = after;
		}
		else if (policy.Others != null)
		{
			for (int i = 0; i < policy.Others.Count; i++)
			{
				if (policy.Others[i].Uid == uid)
				{
					Request value = policy.Others[i];
					value.Tier = after;
					policy.Others[i] = value;
					break;
				}
			}
		}
		dirty.Add(cell);
	}

	private void MoveContribution(long uid, PeerState old, Cell next, int heading, float now)
	{
		Offset[] array = footprints[old.Heading];
		for (int i = 0; i < array.Length; i++)
		{
			Offset offset = array[i];
			Cell cell = new Cell(old.Cell.X + offset.Cell.X, old.Cell.Z + offset.Cell.Z);
			if (maskTypes[heading].TryGetValue(new Cell(cell.X - next.X, cell.Z - next.Z), out var value))
			{
				if (Renewed != null)
				{
					Renewed(cell);
				}
				if (value != offset.Tier)
				{
					Reclassify(uid, cell, offset.Tier, value);
				}
				else if ((deferredCells != 0 && policies[cell].Deferred) || (coolingCells != 0 && policies[cell].OverlapUntil != 0f))
				{
					dirty.Add(cell);
				}
			}
			else
			{
				Contribution(uid, cell, offset.Tier, add: false, now);
			}
		}
		Offset[] array2 = footprints[heading];
		for (int j = 0; j < array2.Length; j++)
		{
			Offset offset2 = array2[j];
			Cell cell2 = new Cell(next.X + offset2.Cell.X, next.Z + offset2.Cell.Z);
			if (!maskTypes[old.Heading].ContainsKey(new Cell(cell2.X - old.Cell.X, cell2.Z - old.Cell.Z)))
			{
				Contribution(uid, cell2, offset2.Tier, add: true, now);
			}
		}
	}

	private void Commit(Cell cell, Policy policy)
	{
		pending.Remove(cell);
		if (policy.Owner != policy.Candidate)
		{
			policy.Owner = policy.Candidate;
			Changes.Add(cell);
			if (policy.Count > 1 && policy.Owner != 0 && overlapCooldown > 0f)
			{
				HoldOverlap(policy, lastTime + overlapCooldown);
			}
		}
		if (policy.Count == 0 && policy.Owner == 0 && policies.Remove(cell) && discardVacant && reusable.Count < 1024)
		{
			policy.Candidate = (policy.Owner = (policy.Uids = 0L));
			policy.Count = (policy.FastCount = (policy.ForwardCount = 0));
			policy.Since = (policy.Wait = (policy.Deadline = (policy.OverlapUntil = 0f)));
			policy.Shared = false;
			policy.First = default(Request);
			if (policy.Others != null)
			{
				policy.Others.Clear();
			}
			reusable.Push(policy);
		}
	}

	private void Evaluate(Cell cell, float now)
	{
		Policy policy = policies[cell];
		if (discardVacant && policy.Count == 0)
		{
			SetDeferred(policy, value: false);
			HoldOverlap(policy, 0f);
			policy.Candidate = 0L;
			Commit(cell, policy);
			return;
		}
		if (policy.OverlapUntil != 0f)
		{
			if (seen.Contains(policy.Owner) && policy.Count != 0 && now < policy.OverlapUntil)
			{
				policy.Candidate = policy.Owner;
				policy.Shared = policy.Count > 1;
				pending.Remove(cell);
				return;
			}
			HoldOverlap(policy, 0f);
		}
		if (directional && discardVacant && policy.Count == 1 && policy.First.Tier != FieldTier.Inner && (policy.Deferred || policy.Shared) && previous.TryGetValue(policy.Uids, out var value) && !value.Refreshed)
		{
			SetDeferred(policy, value: true);
			policy.Candidate = policy.Owner;
			policy.Wait = FieldWait(policy);
			pending.Remove(cell);
			return;
		}
		SetDeferred(policy, value: false);
		bool flag = policy.Count > 1 && !policy.Shared;
		long num = Resolve(policy);
		policy.Shared = policy.Count > 1;
		if (flag && policy.Owner != 0 && policy.Owner == num && overlapCooldown > 0f)
		{
			HoldOverlap(policy, now + overlapCooldown);
		}
		if (policy.Candidate != num)
		{
			if (policy.Owner == policy.Candidate || policy.Candidate == 0 || policy.Count <= 1)
			{
				policy.Since = now;
			}
			policy.Candidate = num;
		}
		float num2 = FieldWait(policy);
		if (num2 < policy.Wait && policy.Candidate != 0)
		{
			Accelerations.Add(cell);
		}
		policy.Wait = num2;
		if (policy.Count > 1 && remembered.Count != 0)
		{
			Forget(cell);
		}
		if (policy.Owner == num || (remembered.Count != 0 && IsRemembered(cell, num)))
		{
			Commit(cell, policy);
			return;
		}
		policy.Deadline = policy.Since + num2;
		if (policy.Count != 0)
		{
			policy.Deadline = RequestDeadline(policy.First, policy.Since, now);
			if (policy.Others != null)
			{
				foreach (Request other in policy.Others)
				{
					policy.Deadline = Math.Min(policy.Deadline, RequestDeadline(other, policy.Since, now));
				}
			}
		}
		if (now >= policy.Deadline)
		{
			Commit(cell, policy);
			return;
		}
		pending.Add(cell);
		nextDue = Math.Min(nextDue, policy.Deadline);
	}

	private float RequestDeadline(Request request, float since, float now)
	{
		return Math.Max(Math.Min(request.Since, now), since) + ((!directional) ? Delay : ((request.Tier == FieldTier.Inner) ? innerDelay : ((request.Tier == FieldTier.Forward) ? forwardDelay : outerDelay)));
	}

	private void SetDeferred(Policy policy, bool value)
	{
		if (policy.Deferred != value)
		{
			policy.Deferred = value;
			deferredCells += (value ? 1 : (-1));
		}
	}

	private void HoldOverlap(Policy policy, float until)
	{
		if (policy.OverlapUntil == 0f != (until == 0f))
		{
			coolingCells += ((until != 0f) ? 1 : (-1));
		}
		policy.OverlapUntil = until;
	}

	private long Resolve(Policy policy)
	{
		if (policy.Count == 0)
		{
			return 0L;
		}
		if (policy.Count == 1)
		{
			return policy.Uids;
		}
		if (latency == null)
		{
			return server;
		}
		long uid = policy.First.Uid;
		float num = latency(uid);
		bool flag = policy.First.Uid == policy.Candidate;
		if (policy.Others != null)
		{
			foreach (Request other in policy.Others)
			{
				float num2 = latency(other.Uid);
				if (num2 < num || (num2 == num && other.Uid < uid))
				{
					uid = other.Uid;
					num = num2;
				}
				flag |= other.Uid == policy.Candidate;
			}
		}
		if (flag && latency(policy.Candidate) <= num + margin)
		{
			return policy.Candidate;
		}
		return uid;
	}

	internal void RanksChanged()
	{
		ranksDirty = true;
	}

	internal void Update(List<GridPeer> peers, float now)
	{
		Changes.Clear();
		Accelerations.Clear();
		dirty.Clear();
		seen.Clear();
		departed.Clear();
		bool flag = now < lastTime;
		lastTime = now;
		if (flag)
		{
			if (coolingCells != 0)
			{
				foreach (Policy value4 in policies.Values)
				{
					if (value4.OverlapUntil != 0f)
					{
						value4.OverlapUntil = now + overlapCooldown;
					}
				}
			}
			nextDue = float.PositiveInfinity;
			foreach (Cell item in pending)
			{
				Policy policy = policies[item];
				policy.Since = now;
				policy.Deadline = now + policy.Wait;
				policy.First.Since = now;
				if (policy.Others != null)
				{
					for (int i = 0; i < policy.Others.Count; i++)
					{
						Request value = policy.Others[i];
						value.Since = now;
						policy.Others[i] = value;
					}
				}
				nextDue = Math.Min(nextDue, policy.Deadline);
			}
		}
		bool flag2 = false;
		foreach (GridPeer peer in peers)
		{
			if (peer.Uid == 0 || peer.Uid == server || !seen.Add(peer.Uid))
			{
				continue;
			}
			PeerState value2;
			bool flag3 = previous.TryGetValue(peer.Uid, out value2);
			if (flag3)
			{
				value2.Refreshed = false;
			}
			float num = Yaw(peer.Yaw, flag3 ? value2.Yaw : 0f);
			int num2 = (directional ? ((peer.Coverage >= 0 && peer.Coverage < 56) ? peer.Coverage : ((flag3 && (float.IsNaN(peer.Yaw) || float.IsInfinity(peer.Yaw))) ? value2.Heading : ((int)((num + 22.5f) / 45f) & 7))) : 0);
			if (!flag3 || !value2.Cell.Equals(peer.Cell) || value2.Heading != num2)
			{
				if (flag3)
				{
					MoveContribution(peer.Uid, value2, peer.Cell, num2, now);
				}
				else
				{
					value2 = new PeerState();
					previous.Add(peer.Uid, value2);
				}
				value2.Cell = peer.Cell;
				value2.Yaw = num;
				value2.Heading = num2;
				value2.Refreshed = true;
				if (!flag3)
				{
					Contribute(peer.Uid, value2, add: true, now);
				}
				flag2 = true;
				PlayerUpdates++;
			}
		}
		foreach (KeyValuePair<long, PeerState> previou in previous)
		{
			if (!seen.Contains(previou.Key))
			{
				departed.Add(previou.Key);
			}
		}
		foreach (long item2 in departed)
		{
			Contribute(item2, previous[item2], add: false, now);
			previous.Remove(item2);
			flag2 = true;
		}
		if (ranksDirty)
		{
			foreach (KeyValuePair<Cell, Policy> policy2 in policies)
			{
				if (policy2.Value.Count > 1)
				{
					dirty.Add(policy2.Key);
				}
			}
			ranksDirty = false;
		}
		if (flag2)
		{
			Rebuilds++;
		}
		foreach (Cell item3 in dirty)
		{
			Evaluate(item3, now);
		}
		if (pending.Count == 0)
		{
			nextDue = float.PositiveInfinity;
		}
		else
		{
			if (now < nextDue)
			{
				return;
			}
			due.Clear();
			foreach (Cell item4 in pending)
			{
				due.Add(item4);
			}
			nextDue = float.PositiveInfinity;
			foreach (Cell item5 in due)
			{
				TimerVisits++;
				if (policies.TryGetValue(item5, out var value3))
				{
					if (now >= value3.Deadline)
					{
						Commit(item5, value3);
					}
					else
					{
						nextDue = Math.Min(nextDue, value3.Deadline);
					}
				}
			}
			due.Clear();
		}
	}
}
internal enum ApplyResult
{
	Done,
	Pending,
	Dropped
}
internal sealed class AuthorityWorld
{
	internal sealed class ObjectBucket
	{
		internal readonly HashSet<AuthorityNode> Nodes = new HashSet<AuthorityNode>();

		internal long Target;

		internal int Unconfirmed;

		internal bool PriorityCached;

		internal int Priority;
	}

	internal readonly AuthorityGrid Grid;

	private readonly Dictionary<Cell, ObjectBucket> buckets = new Dictionary<Cell, ObjectBucket>();

	private readonly HashSet<AuthorityNode> pending = new HashSet<AuthorityNode>();

	private readonly List<ObjectBucket> priorityBuckets = new List<ObjectBucket>();

	private readonly List<AuthorityNode>[] work = new List<AuthorityNode>[4]
	{
		new List<AuthorityNode>(),
		new List<AuthorityNode>(),
		new List<AuthorityNode>(),
		new List<AuthorityNode>()
	};

	private readonly bool keepOnExit;

	private readonly long server;

	private float lastTime;

	internal Action AfterGridUpdate;

	internal int Attempts;

	internal int SkippedCells;

	internal int BucketCount => buckets.Count;

	internal int PendingCount => pending.Count;

	internal AuthorityWorld(long server, float delay, GridCoveragePattern pattern = GridCoveragePattern.Square3x3, bool keepOnExit = true, bool directional = false, float innerDelay = 0f, float outerDelay = 3f, bool forward = false, float forwardDelay = 0.2f, Func<long, float> latency = null, float margin = 30f, float overlapCooldown = 0f)
	{
		Grid = new AuthorityGrid(server, delay, pattern, directional, innerDelay, outerDelay, keepOnExit, forward, forwardDelay, latency, margin, overlapCooldown, !keepOnExit);
		this.keepOnExit = keepOnExit;
		this.server = server;
	}

	internal void Add(AuthorityNode node, float now, bool schedule = true)
	{
		node.Removed = false;
		ObjectBucket objectBucket = Bucket(node.Cell);
		if (objectBucket.Nodes.Add(node))
		{
			node.IndexedBucket = objectBucket;
			node.ConfirmedFieldOwner = 0L;
			if (objectBucket.Target != 0)
			{
				objectBucket.Unconfirmed++;
			}
			if (keepOnExit)
			{
				Grid.Forget(node.Cell);
			}
			if (schedule)
			{
				Queue(node, now);
			}
			else
			{
				node.Managed = false;
			}
		}
	}

	internal void Remove(AuthorityNode node)
	{
		Detach(node);
		node.Removed = true;
		node.Managed = false;
		pending.Remove(node);
	}

	internal void Move(AuthorityNode node, Cell next, float now, bool schedule = true)
	{
		if (!node.Removed && !node.Cell.Equals(next))
		{
			Detach(node);
			node.Cell = next;
			ObjectBucket objectBucket = Bucket(next);
			objectBucket.Nodes.Add(node);
			node.IndexedBucket = objectBucket;
			node.ConfirmedFieldOwner = 0L;
			if (objectBucket.Target != 0)
			{
				objectBucket.Unconfirmed++;
			}
			if (keepOnExit)
			{
				Grid.Forget(next);
			}
			if (schedule)
			{
				Queue(node, now + Grid.Wait(next));
				return;
			}
			pending.Remove(node);
			node.Managed = false;
		}
	}

	internal void Changed(AuthorityNode node, float now, bool schedule = true)
	{
		if (!node.Removed)
		{
			Invalidate(node);
			if (schedule)
			{
				Queue(node, now + Grid.Wait(node.Cell));
				return;
			}
			pending.Remove(node);
			node.Managed = false;
		}
	}

	internal void Received(AuthorityNode node, float now)
	{
		if (!node.Removed)
		{
			Invalidate(node);
			Queue(node, Math.Max(now, node.NotBefore));
		}
	}

	internal void Tick(List<GridPeer> peers, float now)
	{
		if (peers.Count == 0 && !Grid.HasPeers && Grid.CachedCells == 0 && pending.Count == 0)
		{
			Grid.Changes.Clear();
			Grid.Accelerations.Clear();
			return;
		}
		if (now < lastTime)
		{
			foreach (AuthorityNode item in pending)
			{
				item.NotBefore = now + Grid.Wait(item.Cell);
			}
		}
		lastTime = now;
		Grid.Update(peers, now);
		if (AfterGridUpdate != null)
		{
			AfterGridUpdate();
		}
		foreach (Cell change in Grid.Changes)
		{
			if ((keepOnExit && Grid.Owner(change) == 0) || !buckets.TryGetValue(change, out var value))
			{
				continue;
			}
			long num = Grid.Owner(change);
			if (keepOnExit && Grid.IsRemembered(change, num) && value.Target == num && value.Unconfirmed == 0)
			{
				SkippedCells++;
				continue;
			}
			value.Target = ((keepOnExit && num != server) ? num : 0);
			value.Unconfirmed = ((value.Target != 0) ? value.Nodes.Count : 0);
			bool flag = false;
			float num2 = 0f;
			foreach (AuthorityNode node in value.Nodes)
			{
				node.ConfirmedFieldOwner = 0L;
				if (pending.Add(node))
				{
					node.NotBefore = now;
				}
				else if (Grid.Directional)
				{
					if (!flag)
					{
						num2 = Grid.Wait(change);
						flag = true;
					}
					node.NotBefore = Math.Min(node.NotBefore, now + num2);
				}
			}
		}
		if (pending.Count == 0)
		{
			return;
		}
		ClearPriorityBatch();
		try
		{
			foreach (AuthorityNode item2 in pending)
			{
				work[BatchPriority(item2)].Add(item2);
			}
		}
		finally
		{
			ClearPriorityBatch();
		}
		try
		{
			List<AuthorityNode>[] array = work;
			foreach (List<AuthorityNode> list in array)
			{
				foreach (AuthorityNode item3 in list)
				{
					if (item3.Removed || !pending.Contains(item3))
					{
						continue;
					}
					if (Grid.Accelerations.Count != 0 && Grid.Accelerations.Contains(item3.Cell))
					{
						item3.NotBefore = Math.Min(item3.NotBefore, now + Grid.Wait(item3.Cell));
					}
					if (now < item3.NotBefore)
					{
						continue;
					}
					Attempts++;
					ApplyResult applyResult = item3.Apply(Grid.Owner(item3.Cell));
					if (applyResult != ApplyResult.Pending)
					{
						pending.Remove(item3);
					}
					switch (applyResult)
					{
					case ApplyResult.Dropped:
						item3.Managed = false;
						break;
					case ApplyResult.Done:
						if (keepOnExit && !item3.Removed)
						{
							Confirm(item3);
						}
						break;
					}
				}
			}
		}
		finally
		{
			List<AuthorityNode>[] array2 = work;
			foreach (List<AuthorityNode> list2 in array2)
			{
				list2.Clear();
			}
		}
	}

	internal void Dismiss(AuthorityNode node)
	{
		Invalidate(node);
		pending.Remove(node);
		node.Managed = false;
	}

	internal int BatchPriority(AuthorityNode node)
	{
		ObjectBucket indexedBucket = node.IndexedBucket;
		if (indexedBucket == null || indexedBucket.Nodes.Count == 1)
		{
			return Grid.WorkPriority(node.Cell);
		}
		if (!indexedBucket.PriorityCached)
		{
			indexedBucket.Priority = Grid.WorkPriority(node.Cell);
			indexedBucket.PriorityCached = true;
			priorityBuckets.Add(indexedBucket);
		}
		return indexedBucket.Priority;
	}

	internal void ClearPriorityBatch()
	{
		foreach (ObjectBucket priorityBucket in priorityBuckets)
		{
			priorityBucket.PriorityCached = false;
		}
		priorityBuckets.Clear();
	}

	private void Queue(AuthorityNode node, float at)
	{
		node.NotBefore = at;
		pending.Add(node);
	}

	private void Invalidate(AuthorityNode node)
	{
		if (keepOnExit)
		{
			Grid.Forget(node.Cell);
			if (buckets.TryGetValue(node.Cell, out var value) && value.Target != 0 && node.ConfirmedFieldOwner == value.Target)
			{
				node.ConfirmedFieldOwner = 0L;
				value.Unconfirmed++;
			}
		}
	}

	private void Confirm(AuthorityNode node)
	{
		if (buckets.TryGetValue(node.Cell, out var value) && value.Target != 0 && node.ConfirmedFieldOwner != value.Target && node.CanRemember(value.Target))
		{
			node.ConfirmedFieldOwner = value.Target;
			value.Unconfirmed--;
			Certify(node.Cell, value);
		}
	}

	private void Certify(Cell cell, ObjectBucket bucket)
	{
		if (keepOnExit && bucket.Target != 0 && bucket.Unconfirmed == 0)
		{
			Grid.Remember(cell, bucket.Target);
		}
	}

	private void Detach(AuthorityNode node)
	{
		if (buckets.TryGetValue(node.Cell, out var value) && value.Nodes.Remove(node))
		{
			node.IndexedBucket = null;
			bool flag = value.Target != 0 && node.ConfirmedFieldOwner != value.Target;
			if (flag)
			{
				value.Unconfirmed--;
			}
			node.ConfirmedFieldOwner = 0L;
			if (value.Nodes.Count == 0)
			{
				buckets.Remove(node.Cell);
				Grid.Forget(node.Cell);
			}
			else if (flag)
			{
				Certify(node.Cell, value);
			}
		}
	}

	private ObjectBucket Bucket(Cell cell)
	{
		if (!buckets.TryGetValue(cell, out var value))
		{
			long num = Grid.Owner(cell);
			ObjectBucket objectBucket = new ObjectBucket();
			objectBucket.Target = ((keepOnExit && num != server) ? num : 0);
			value = objectBucket;
			buckets.Add(cell, value);
		}
		return value;
	}
}
internal static class CameraHeading
{
	internal static readonly int Key = StringExtensionMethods.GetStableHashCode("botanic.toomanylags.standalone.cameraCoverageConfigured");

	private static float overlap = 30f;

	private static float prediction;

	internal static float Overlap => overlap;

	internal static float Prediction => prediction;

	internal static void Configure(float degrees, float seconds = 0f)
	{
		overlap = ((float.IsNaN(degrees) || float.IsInfinity(degrees)) ? 30f : Math.Max(0f, Math.Min(45f, degrees)));
		prediction = ((float.IsNaN(seconds) || float.IsInfinity(seconds)) ? 0f : Math.Max(0f, Math.Min(0.5f, seconds)));
	}

	internal static int Coverage(float yaw)
	{
		return AuthorityGrid.HeadingCoverage(yaw, overlap);
	}

	internal static int Coverage(float x, float z)
	{
		if (float.IsNaN(x) || float.IsNaN(z) || float.IsInfinity(x) || float.IsInfinity(z) || (double)x * (double)x + (double)z * (double)z < 1E-06)
		{
			return -1;
		}
		return Coverage((float)(Math.Atan2(x, z) * (180.0 / Math.PI)));
	}

	internal static int Read(ZDO player, long peer, bool cameraAvailable, CameraWake wake = null)
	{
		//IL_0041: 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_0049: 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)
		bool flag = cameraAvailable && player.GetOwner() == peer;
		int num = (flag ? player.GetInt(Key, -1) : (-1));
		if (wake != null && flag)
		{
			wake.Track(player.m_uid, peer, num);
		}
		if (num < 0 || num >= 56)
		{
			Quaternion rotation = player.GetRotation();
			return Coverage(((Quaternion)(ref rotation)).eulerAngles.y);
		}
		return num;
	}
}
internal sealed class CameraWake
{
	private struct Stamp
	{
		internal long Peer;

		internal int Coverage;
	}

	private readonly Dictionary<ZDOID, Stamp> players = new Dictionary<ZDOID, Stamp>();

	internal int Count => players.Count;

	private static int Valid(int value)
	{
		if (value < 0 || value >= 56)
		{
			return -1;
		}
		return value;
	}

	internal void Clear()
	{
		players.Clear();
	}

	internal void Track(ZDOID id, long peer, int coverage)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		players[id] = new Stamp
		{
			Peer = peer,
			Coverage = Valid(coverage)
		};
	}

	internal bool Changed(ZDO data)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: 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)
		if (data == null || !players.TryGetValue(data.m_uid, out var value) || data.GetOwner() != value.Peer || !data.IsValid() || ZDOMan.instance == null || !object.ReferenceEquals(ZDOMan.instance.GetZDO(data.m_uid), data))
		{
			return false;
		}
		int num = Valid(data.GetInt(CameraHeading.Key, -1));
		if (num == value.Coverage)
		{
			return false;
		}
		value.Coverage = num;
		players[data.m_uid] = value;
		return true;
	}
}
internal sealed class CameraPrediction
{
	private bool sampled;

	private float previousYaw;

	private float previousTime;

	private float previousOverlap;

	private float previousSeconds;

	private float heldUntil;

	private int held = -1;

	internal void Reset()
	{
		sampled = false;
		held = -1;
		heldUntil = 0f;
	}

	internal int Sample(float x, float z, float now, float overlap, float seconds)
	{
		if (float.IsNaN(x) || float.IsNaN(z) || float.IsInfinity(x) || float.IsInfinity(z) || (double)x * (double)x + (double)z * (double)z < 1E-06)
		{
			Reset();
			return -1;
		}
		return Sample((float)(Math.Atan2(x, z) * (180.0 / Math.PI)), now, overlap, seconds);
	}

	internal int Sample(float yaw, float now, float overlap, float seconds)
	{
		int num = AuthorityGrid.HeadingCoverage(yaw, overlap);
		if (num < 0 || float.IsNaN(now) || float.IsInfinity(now) || float.IsNaN(seconds) || float.IsInfinity(seconds) || seconds <= 0f)
		{
			Reset();
			return num;
		}
		seconds = Math.Min(0.5f, seconds);
		overlap = ((float.IsNaN(overlap) || float.IsInfinity(overlap)) ? 30f : Math.Max(0f, Math.Min(45f, overlap)));
		yaw %= 360f;
		float num2 = now - previousTime;
		bool flag = !sampled || num2 <= 0f || num2 > 0.5f || overlap != previousOverlap || seconds != previousSeconds;
		float num3 = yaw - previousYaw;
		if (num3 > 180f)
		{
			num3 -= 360f;
		}
		else if (num3 < -180f)
		{
			num3 += 360f;
		}
		previousYaw = yaw;
		previousTime = now;
		previousOverlap = overlap;
		previousSeconds = seconds;
		sampled = true;
		if (flag)
		{
			held = -1;
			return num;
		}
		int num4 = -1;
		if (Math.Abs(num3) > 0.001f && Math.Abs(num3) < 179.999f)
		{
			int num5 = ((num < 8) ? num : (num - 8));
			int num6 = ((num3 > 0f) ? ((num5 + ((num < 8) ? 1 : 2)) & 7) : ((num5 + 7) & 7));
			float num7 = Math.Min(45f, Math.Abs(num3 / num2 * seconds));
			int coverage = AuthorityGrid.HeadingCoverage(yaw + ((num3 > 0f) ? num7 : (0f - num7)), overlap);
			if ((Bits(coverage) & (1 << num6)) != 0)
			{
				num4 = num6;
			}
		}
		if (held >= 0 && (Join(num, held) == num || now >= heldUntil))
		{
			held = -1;
		}
		if (num4 >= 0 && (held < 0 || held == num4))
		{
			held = num4;
			heldUntil = now + Math.Min(seconds, 0.1f);
		}
		if (held >= 0)
		{
			return Join(num, held);
		}
		return num;
	}

	internal static int Bits(int coverage)
	{
		switch (coverage)
		{
		default:
			return 0;
		case 24:
		case 25:
		case 26:
		case 27:
		case 28:
		case 29:
		case 30:
		case 31:
		case 32:
		case 33:
		case 34:
		case 35:
		case 36:
		case 37:
		case 38:
		case 39:
		case 40:
		case 41:
		case 42:
		case 43:
		case 44:
		case 45:
		case 46:
		case 47:
		case 48:
		case 49:
		case 50:
		case 51:
		case 52:
		case 53:
		case 54:
		case 55:
		{
			int num4 = (coverage - 24) & 0xF;
			int num5 = num4 & 7;
			int num6 = ((coverage < 40) ? ((num5 + ((num4 < 8) ? 1 : 2)) & 7) : ((num5 + 7) & 7));
			return Bits(num4) | (1 << num6);
		}
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
		case 8:
		case 9:
		case 10:
		case 11:
		case 12:
		case 13:
		case 14:
		case 15:
		case 16:
		case 17:
		case 18:
		case 19:
		case 20:
		case 21:
		case 22:
		case 23:
		{
			int num = coverage & 7;
			int num2 = coverage / 8 + 1;
			int num3 = 0;
			for (int i = 0; i < num2; i++)
			{
				num3 |= 1 << ((num + i) & 7);
			}
			return num3;
		}
		}
	}

	internal static int Join(int actual, int extra)
	{
		if (actual < 0 || actual >= 16 || extra < 0 || extra >= 8)
		{
			return actual;
		}
		int num = actual & 7;
		if ((Bits(actual) & (1 << extra)) != 0)
		{
			return actual;
		}
		if (extra == ((num + 7) & 7))
		{
			return 40 + actual;
		}
		if (extra == ((num + ((actual < 8) ? 1 : 2)) & 7))
		{
			return 24 + actual;
		}
		return actual;
	}
}
internal sealed class CameraPublisher
{
	private readonly OwnershipCadence cadence;

	private readonly CameraPrediction prediction = new CameraPrediction();

	private ZDO previous;

	private ZNet network;

	private ZDOMan world;

	private Vector3 previousPosition;

	internal CameraPublisher(float interval)
	{
		cadence = new OwnershipCadence(interval);
	}

	internal void Configure(float interval)
	{
		cadence.Configure(interval);
		prediction.Reset();
	}

	internal void Sample(float now)
	{
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_025d: Unknown result type (might be due to invalid IL or missing references)
		if (!cadence.Due(now))
		{
			return;
		}
		ZNet instance = ZNet.instance;
		if (!Object.op_Implicit((Object)(object)instance) || instance.IsDedicated() || ZNet.IsSinglePlayer || ZDOMan.instance == null)
		{
			Reset();
			return;
		}
		if (!instance.IsServer() && (Plugin.Network == null || !Plugin.Network.Confirmed))
		{
			Reset();
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		if (!Object.op_Implicit((Object)(object)localPlayer) || (!instance.IsServer() && instance.GetServerPeer() == null))
		{
			Reset();
			return;
		}
		ZNetView component = ((Component)localPlayer).GetComponent<ZNetView>();
		if (!Object.op_Implicit((Object)(object)component) || !component.IsValid() || !component.IsOwner())
		{
			Reset();
			return;
		}
		ZDO zDO = component.GetZDO();
		if (zDO == null || !zDO.IsValid() || ((ZDOID)(ref zDO.m_uid)).IsNone() || !object.ReferenceEquals(ZDOMan.instance.GetZDO(zDO.m_uid), zDO))
		{
			Reset();
			return;
		}
		bool flag = !object.ReferenceEquals(previous, zDO) || !object.ReferenceEquals(network, instance) || !object.ReferenceEquals(world, ZDOMan.instance);
		if (flag)
		{
			prediction.Reset();
		}
		if (CameraHeading.Prediction > 0f)
		{
			Vector3 position = zDO.GetPosition();
			float num = position.x - previousPosition.x;
			float num2 = position.y - previousPosition.y;
			float num3 = position.z - previousPosition.z;
			if (num > 16f || num < -16f || num2 > 16f || num2 < -16f || num3 > 16f || num3 < -16f)
			{
				prediction.Reset();
			}
			previousPosition = position;
		}
		GameCamera instance2 = GameCamera.instance;
		int num4 = -1;
		if (Object.op_Implicit((Object)(object)instance2) && !GameCamera.InFreeFly())
		{
			Vector3 forward = ((Component)instance2).transform.forward;
			num4 = prediction.Sample(forward.x, forward.z, now, CameraHeading.Overlap, CameraHeading.Prediction);
		}
		else
		{
			prediction.Reset();
		}
		if (flag)
		{
			ZDOExtraData.AddSessionHash(CameraHeading.Key);
		}
		if (flag || zDO.GetInt(CameraHeading.Key, -1) != num4)
		{
			zDO.Set(CameraHeading.Key, num4, false);
			ZDOMan.instance.ForceSendZDO(zDO.m_uid);
			if (instance.IsServer() && Plugin.Controller != null)
			{
				Plugin.Controller.CameraChanged(zDO);
			}
		}
		previous = zDO;
		network = instance;
		world = ZDOMan.instance;
	}

	internal void Reset(bool invalidate = false)
	{
		//IL_006c: 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)
		if (invalidate && previous != null && object.ReferenceEquals(network, ZNet.instance) && object.ReferenceEquals(world, ZDOMan.instance) && previous.IsValid() && previous.GetOwner() == ZDOMan.GetSessionID() && object.ReferenceEquals(world.GetZDO(previous.m_uid), previous) && previous.GetInt(CameraHeading.Key, -1) != -1)
		{
			previous.Set(CameraHeading.Key, -1, false);
			world.ForceSendZDO(previous.m_uid);
			if (network.IsServer() && Plugin.Controller != null)
			{
				Plugin.Controller.CameraChanged(previous);
			}
		}
		prediction.Reset();
		previous = null;
		network = null;
		world = null;
	}
}
[HarmonyPatch(typeof(GameCamera), "LateUpdate")]
internal static class CameraSamplePatch
{
	[HarmonyPostfix]
	[HarmonyPriority(0)]
	private static void Postfix()
	{
		Plugin.SampleCamera();
	}
}
[HarmonyPatch(typeof(GameCamera), "OnDestroy")]
internal static class CameraLossPatch
{
	[HarmonyPrefix]
	private static void Prefix(GameCamera __instance)
	{
		if ((Object)(object)GameCamera.instance == (Object)(object)__instance)
		{
			Plugin.InvalidateCamera();
		}
	}
}
internal sealed class ConfigCommands
{
	private const string RestartNotice = " Takes effect after restarting the host/server; the current session is unchanged. Clients receive the new mode when reconnecting.";

	private readonly ConfigFile config;

	private readonly Action<string> apply;

	private readonly Dictionary<string, object> active = new Dictionary<string, object>(StringComparer.Ordinal);

	internal ConfigCommands(ConfigFile config, Action<string> apply)
	{
		this.config = config;
		this.apply = apply;
		foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config)
		{
			if (!Live(item.Key.Key))
			{
				active.Add(item.Key.Key, item.Value.BoxedValue);
			}
		}
	}

	internal static bool Local(string key)
	{
		return string.Equals(key, "EnableLogs", StringComparison.OrdinalIgnoreCase);
	}

	internal static bool Live(string key)
	{
		switch (key)
		{
		case "EnableLogs":
		case "CameraHeadingCheckIntervalSeconds":
		case "CameraDirectionOverlapDegrees":
		case "CameraRotationPredictionSeconds":
		case "MovementRotationCheckIntervalSeconds":
		case "InnerTransitionDelaySeconds":
		case "ForwardTransitionDelaySeconds":
		case "OuterTransitionDelaySeconds":
		case "TransitionDelaySeconds":
		case "OverlapOwnershipCooldownSeconds":
		case "HighTargetPingMs":
		case "NearbyAlternativeOwnerRadiusMeters":
			return true;
		default:
			return false;
		}
	}

	internal string Execute(string command, bool server)
	{
		if (command == null || command.Length > 256)
		{
			return "Invalid config command.";
		}
		string[] array = command.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
		if (array.Length == 1 && string.Equals(array[0], "list", StringComparison.OrdinalIgnoreCase))
		{
			StringBuilder stringBuilder = new StringBuilder(server ? "HOST/SERVER settings (live/restart):" : "LOCAL settings (live/restart):");
			foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config)
			{
				if (server != Local(item.Key.Key))
				{
					stringBuilder.Append('\n').Append(Display(item.Value));
				}
			}
			return stringBuilder.ToString();
		}
		if (array.Length < 1 || array.Length > 2)
		{
			return "Usage: tml_config list | <Key> [value].";
		}
		ConfigEntryBase val = null;
		foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item2 in config)
		{
			if (string.Equals(item2.Key.Key, array[0], StringComparison.OrdinalIgnoreCase))
			{
				val = item2.Value;
				break;
			}
		}
		if (val == null)
		{
			return "Unknown setting. Use tml_config list.";
		}
		string key = val.Definition.Key;
		if (server == Local(key))
		{
			return "Wrong setting scope. Only EnableLogs is local; all gameplay and camera settings belong on the host/server.";
		}
		if (array.Length == 1)
		{
			return Display(val) + "\n" + val.Description.Description;
		}
		if (!Parse(val.SettingType, array[1], out var value) || (val.Description.AcceptableValues != null && !val.Description.AcceptableValues.IsValid(value)))
		{
			return "Invalid value for " + key + ".\n" + val.Description.Description + "\n" + ((val.Description.AcceptableValues == null) ? "" : val.Description.AcceptableValues.ToDescriptionString());
		}
		if (InvalidGrid(key, value))
		{
			return "Invalid grid combination: 4-metre cells require Rounded5x5 or Rounded7x7. Change the other setting first.";
		}
		bool flag = Live(key);
		if (object.Equals(val.BoxedValue, value))
		{
			return key + " is already " + Value(value) + "." + (Pending(val) ? " Takes effect after restarting the host/server; the current session is unchanged. Clients receive the new mode when reconnecting." : "");
		}
		object boxedValue = val.BoxedValue;
		bool saveOnConfigSet = config.SaveOnConfigSet;
		config.SaveOnConfigSet = false;
		try
		{
			val.BoxedValue = value;
			config.Save();
			if (flag)
			{
				apply(key);
			}
			string text = (server ? "HOST/SERVER: " : "LOCAL: ") + key + " = " + Value(value);
			return flag ? (text + " (saved and applied; existing handoffs remain protected).") : (text + (Pending(val) ? " (saved). Takes effect after restarting the host/server; the current session is unchanged. Clients receive the new mode when reconnecting." : " (saved; matches the current session, no restart pending)."));
		}
		catch (Exception ex)
		{
			val.BoxedValue = boxedValue;
			try
			{
				if (flag)
				{
					apply(key);
				}
				config.Save();
			}
			catch (Exception)
			{
			}
			return "Change failed: " + ex.GetBaseException().Message;
		}
		finally
		{
			config.SaveOnConfigSet = saveOnConfigSet;
		}
	}

	private bool Pending(ConfigEntryBase entry)
	{
		if (active.TryGetValue(entry.Definition.Key, out var value))
		{
			return !object.Equals(value, entry.BoxedValue);
		}
		return false;
	}

	private string Display(ConfigEntryBase entry)
	{
		string key = entry.Definition.Key;
		string text = key + " = " + Value(entry.BoxedValue);
		if (!Pending(entry))
		{
			return text + (Live(key) ? " [live]" : " [restart]");
		}
		return text + " [restart pending; active: " + Value(active[key]) + "]";
	}

	private bool InvalidGrid(string key, object value)
	{
		if (key != "GridCellSizeMeters" && key != "GridCoveragePattern")
		{
			return false;
		}
		float num = 0f;
		string text = null;
		foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config)
		{
			if (item.Key.Key == "GridCellSizeMeters")
			{
				num = Convert.ToSingle((key == item.Key.Key) ? value : item.Value.BoxedValue, CultureInfo.InvariantCulture);
			}
			else if (item.Key.Key == "GridCoveragePattern")
			{
				text = (string)((key == item.Key.Key) ? value : item.Value.BoxedValue);
			}
		}
		if (num == 4f)
		{
			return text == "Square3x3";
		}
		return false;
	}

	private static string Value(object value)
	{
		return Convert.ToString(value, CultureInfo.InvariantCulture);
	}

	private static bool Parse(Type type, string text, out object value)
	{
		value = null;
		int result2;
		float result3;
		if (type == typeof(bool) && bool.TryParse(text, out var result))
		{
			value = result;
		}
		else if (type == typeof(string))
		{
			value = text;
		}
		else if (type == typeof(int) && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out result2))
		{
			value = result2;
		}
		else if (type == typeof(float) && float.TryParse(text.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out result3) && !float.IsNaN(result3) && !float.IsInfinity(result3))
		{
			value = result3;
		}
		return value != null;
	}
}
internal static class ConfigConsole
{
	private static bool registered;

	private static WeakReference terminal;

	private static ZNet network;

	private static ZNetPeer requestedPeer;

	private static int ticket;

	private static float until;

	internal static void Register()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Expected O, but got Unknown
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		if (!registered)
		{
			new ConsoleCommand("tml_config", "tml_config list | <Key> [value]. Host/server admin only; EnableLogs is local. Restart settings are saved for the next restart.", new ConsoleEvent(Run), false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			registered = true;
		}
	}

	private static void Run(ConsoleEventArgs args)
	{
		if (args == null || !Object.op_Implicit((Object)(object)args.Context))
		{
			return;
		}
		if (args.Args.Length < 2)
		{
			args.Context.AddString("tml_config list | <Key> [value]. Only EnableLogs is local; server changes require admin rights.");
			return;
		}
		string command = string.Join(" ", args.Args, 1, args.Args.Length - 1);
		if (command.Length > 256)
		{
			args.Context.AddString("Config command too long.");
			return;
		}
		if (ConfigCommands.Local(args.Args[1]))
		{
			Print(args.Context, Plugin.ConfigCommand(command, server: false));
			return;
		}
		ZNet instance = ZNet.instance;
		if (Object.op_Implicit((Object)(object)instance) && instance.IsServer())
		{
			Print(args.Context, Plugin.ConfigCommand(command, server: true));
			return;
		}
		ZNetPeer val = (Object.op_Implicit((Object)(object)instance) ? instance.GetServerPeer() : null);
		if (val == null || !val.IsReady() || val.m_rpc == null || Plugin.Network == null || !Plugin.Network.Confirmed)
		{
			args.Context.AddString("Connect to a host/server running a compatible TooManyLags version first.");
			return;
		}
		ticket = ((ticket == int.MaxValue) ? 1 : (ticket + 1));
		terminal = new WeakReference(args.Context);
		network = instance;
		requestedPeer = val;
		until = Time.unscaledTime + 10f;
		int id = ticket;
		Plugin.Network.ToServer(Message.ConfigRequest, delegate(ZPackage p)
		{
			p.Write(id);
			p.Write(command);
		});
		Plugin.Network.FlushAll();
	}

	internal static string Request(ZNetPeer peer, string command)
	{
		ZNet instance = ZNet.instance;
		if (!Object.op_Implicit((Object)(object)instance) || !instance.IsServer() || peer == null || !peer.IsReady() || peer.m_rpc == null || !object.ReferenceEquals(instance.GetPeer(peer.m_uid), peer) || command == null || command.Length > 256)
		{
			return null;
		}
		if (peer.m_socket == null || !instance.IsAdmin(peer.m_socket.GetHostName()))
		{
			return "Host/server configuration requires admin rights (adminlist.txt).";
		}
		return Plugin.ConfigCommand(command, server: true);
	}

	internal static void Reply(ZNetPeer peer, int id, string reply)
	{
		ZNet instance = ZNet.instance;
		if (Object.op_Implicit((Object)(object)instance) && !instance.IsServer() && object.ReferenceEquals(network, instance) && object.ReferenceEquals(requestedPeer, peer) && object.ReferenceEquals(instance.GetServerPeer(), peer) && id == ticket && terminal != null && !(Time.unscaledTime > until) && reply != null && reply.Length <= 12000)
		{
			object? target = terminal.Target;
			Terminal val = (Terminal)((target is Terminal) ? target : null);
			Reset();
			if (Object.op_Implicit((Object)(object)val))
			{
				Print(val, reply);
			}
		}
	}

	private static void Print(Terminal context, string lines)
	{
		string[] array = lines.Split('\n');
		foreach (string text in array)
		{
			context.AddString(text.TrimEnd('\r'));
		}
	}

	internal static void Reset()
	{
		terminal = null;
		network = null;
		requestedPeer = null;
		until = 0f;
	}
}
internal static class ConfigLayout
{
	private sealed class Option
	{
		internal string Section;

		internal string Key;

		internal string Value;
	}

	private const string Marker = "## Configuration layout: 2";

	private static ConfigFile managed;

	private static string version;

	private static bool autoSave;

	internal static bool Migrated { get; private set; }

	internal static void Prepare(ConfigFile config, string pluginVersion)
	{
		managed = config;
		version = pluginVersion;
		autoSave = config.SaveOnConfigSet;
		string text = (File.Exists(config.ConfigFilePath) ? File.ReadAllText(config.ConfigFilePath) : "");
		Dictionary<string, Option> schema = Schema();
		Dictionary<string, string> values = ReadValues(text, schema);
		Migrated = text.Length != 0 && !text.Contains("## Configuration layout: 2");
		if (Migrated)
		{
			string path = config.ConfigFilePath + ".pre-layout.bak";
			if (!File.Exists(path))
			{
				File.WriteAllText(path, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			}
		}
		config.SaveOnConfigSet = false;
		Write(config.ConfigFilePath, Render(values, null));
		config.Reload();
	}

	internal static void Finish(ConfigFile config)
	{
		if (object.ReferenceEquals(managed, config))
		{
			Save(config);
			config.SaveOnConfigSet = autoSave;
		}
	}

	internal static bool BeforeSave(ConfigFile __instance)
	{
		if (!object.ReferenceEquals(managed, __instance))
		{
			return true;
		}
		Save(__instance);
		return false;
	}

	internal static void Save(ConfigFile config)
	{
		List<Option> list = new List<Option>();
		Dictionary<string, Option> dictionary = Schema();
		Dictionary<string, string> dictionary2 = ReadValues(File.Exists(config.ConfigFilePath) ? File.ReadAllText(config.ConfigFilePath) : "", dictionary);
		foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config)
		{
			string serializedValue = item.Value.GetSerializedValue();
			if (dictionary.ContainsKey(item.Key.Key))
			{
				dictionary2[item.Key.Key] = serializedValue;
				continue;
			}
			list.Add(new Option
			{
				Section = item.Key.Section,
				Key = item.Key.Key,
				Value = serializedValue
			});
		}
		Write(config.ConfigFilePath, Render(dictionary2, list));
	}

	internal static void Reset()
	{
		if (managed != null)
		{
			managed.SaveOnConfigSet = autoSave;
		}
		managed = null;
		version = null;
		Migrated = false;
	}

	private static Dictionary<string, Option> Schema()
	{
		Dictionary<string, Option> dictionary = new Dictionary<string, Option>(StringComparer.Ordinal);
		string section = "";
		foreach (string item in Lines("## Settings file was created by plugin TooManyLags - Standalone v@VERSION@\n## Plugin GUID: botanic.toomanylags.standalone\n\n[00 - General]\n\n## Host/server settings control gameplay, camera and mobs. Only EnableLogs is local. Clients are optional with reduced features. Restart unless marked live.\n## Enable TooManyLags for this session. Clients follow the host/server.\nEnabled = true\n\n\n[01 - Simulation Settings]\n\n## Simulation stays on players; there is no server simulation mode.\n## true: retain vacated fields. Only inner fields update automatically when one of several players leaves; outer fields wait for movement/rotation.\n## false: keep the full directional footprint with a red 3x3 centre. Native region ownership release remains active in both modes.\nKeepOwnershipOnCellExit = true\n\n\n[02 - Latency Selection]\n\n## Host/server; restart required. Smoothed ping sampling interval in seconds. Unmodded clients use native connection telemetry without an extra request.\n# Acceptable value range: From 0.5 to 10\nPingMeasurementIntervalSeconds = 2\n\n## Host/server; restart required. Required ping improvement in milliseconds before replacing a candidate; avoids jitter-driven switches.\n# Acceptable value range: From 0 to 500\nOwnershipPingMarginMs = 30\n\n\n[03 - AI Mob Ownership]\n\n## Host/server; restart required. Target-based Hostile Mob ownership requires compatible source/target clients. Friendly player summons and bosses stay vanilla; idle tamed animals use the grid.\nEnableAIOwnership = true\n\n## Live console supported. Above this target ping in milliseconds, prefer a better-connected eligible player close to the Hostile Mob. Does not change its attack target.\n# Acceptable value range: From 50 to 2000\nHighTargetPingMs = 200\n\n## Live console supported. Maximum distance in metres from the mob for a better-ping alternative owner.\n# Acceptable value range: From 1 to 20\nNearbyAlternativeOwnerRadiusMeters = 6\n\n\n[04 - Grid Settings]\n## Defaults should work well. Larger grids prepare ownership earlier for poor connections.\n\n## Cell size in metres: 4, 6.4, 8 or 16. 6.4 divides each vanilla zone into 10x10 cells. 4 requires a rounded grid. Does not change loading distances.\n# Acceptable values: 4, 6.4, 8, 16\nGridCellSizeMeters = 4\n\n## Square3x3 is square; Rounded5x5/Rounded7x7 are rounded. Directional mode omits rear fields with KeepOwnershipOnCellExit=true; false keeps the complete shape. Overlaps prefer the best eligible player ping.\n# Acceptable values: Square3x3, Rounded5x5, Rounded7x7\nGridCoveragePattern = Rounded7x7\n\n## Live console supported. Movement/fallback-heading check interval in seconds. Only changed coverage creates requests; received camera changes wake the next server pass directly. Existing handoffs progress while standing.\n# Acceptable value range: From 0.05 to 5\nMovementRotationCheckIntervalSeconds = 0.1\n\n\n[05 - Directional Grid Mode]\n\n## Recommended: leave enabled. Camera-directed grid with the timers below and camera settings in section 07. Missing camera data uses character heading. false uses the full grid from section 06. Stationary players still count.\nDirectionalGridMode = true\n\n## Live console supported. Red: six inner cells; full 3x3 with KeepOwnershipOnCellExit=false. Delay in seconds; 0 allowed. Safe handoffs can still wait.\n# Acceptable value range: From 0 to 30\nInnerTransitionDelaySeconds = 0\n\n## Live console supported. Orange: one extra three-cell row ahead of red, with 4-metre cells and rounded coverage. Delay in seconds; 0 allowed.\n# Acceptable value range: From 0 to 30\nForwardTransitionDelaySeconds = 0.2\n\n## Live console supported. Yellow: remaining active cells. Delay in seconds. Avoids unnecessary edge handoffs; lower delays can help fast movement on poor connections.\n# Acceptable value range: From 0 to 30\nOuterTransitionDelaySeconds = 3\n\n## Live console supported. Hold an overlap ownership decision for this many seconds. Exclusive fields have no hold; expiry alone causes no transfer. 0 disables.\n# Acceptable value range: From 0 to 30\nOverlapOwnershipCooldownSeconds = 1\n\n\n[06 - Full Grid Mode]\n\n## Live console supported. Only with DirectionalGridMode=false: uniform delay in seconds for new full-grid requests.\n# Acceptable value range: From 0 to 30\nTransitionDelaySeconds = 2\n\n\n[07 - Camera Heading]\n\n## Live console supported; sent to clients. Camera sample interval in seconds. 0.05 allows up to 20 checks per second; only changed coverage is published. Without a client mod, character heading is used.\n# Acceptable value range: From 0.05 to 5\nCameraHeadingCheckIntervalSeconds = 0.05\n\n## Live console supported; sent to clients. Angular overlap between adjacent directions. 30 is recommended; 0 disables base overlap. Prediction can add one further direction.\n# Acceptable value range: From 0 to 45\nCameraDirectionOverlapDegrees = 30\n\n## Live console supported; sent to clients. Predict camera rotation this many seconds ahead. At most one extra direction uses the inner/red delay. 0 disables. Requires a compatible client.\n# Acceptable value range: From 0 to 0.5\nCameraRotationPredictionSeconds = 0.1\n\n\n[09 - Logs]\n\n## Local only; live console supported. Extra diagnostics. Startup errors are always reported.\nEnableLogs = false\n\n\n[10 - Object Categories]\n\n## All categories below: host/server; restart required. true: managed by TooManyLags; false: vanilla. Active use and safe handoffs remain protected. Without compatible clients, only native-safe categories transfer.\n\n## Doors and gates.\nDoors = true\n\n## Seats and barber stations.\nSeats = true\n\n## Beds.\nBeds = true\n\n## Crafting stations and upgrades.\nWorkstations = true\n\n## Smelters, kilns, windmills and similar refill stations. Each observed insert renews a one-second hold.\nSmelters = true\n\n## Cooking stations.\nCookingStations = true\n\n## Fireplaces and refillable light sources.\nFireplaces = true\n\n## Beehives.\nBeehives = true\n\n## Sap collectors.\nSapCollectors = true\n\n## Wards.\nWards = true\n\n## Cartography tables.\nMapTables = true\n\n## Wisp fountains.\nWisplights = true\n\n## Idle tamed animals; riding, following and friendly player summons retain native control.\nTamedAnimals = true\n\n## Chests and inventories; open inventories and pending requests block transfers.\nContainers = true\n\n## Item and armour stands.\nItemStands = true\n\n## Signs; native editing retains ownership until player movement.\nSigns = true\n\n## Portals and dungeon entrances; native portal-name editing retains ownership until movement.\nPortals = true\n\n## Fermenters.\nFermenters = true\n\n## Incinerators; open inventories, pending requests and burning block transfers.\nIncinerators = true\n\n## Traps and turrets.\nDefenses = true\n\n## Shield generators.\nShieldGenerators = true\n\n## Pickable objects and feasts; excludes loose item drops.\nPickables = true\n\n## Offering altars.\nOfferings = true\n\n## Carts, boats and vehicle controls; active drivers retain control.\nVehicles = true\n\n## Other compatible modded interactables; custom local actions cannot be inferred.\nOtherInteractables = true"))
		{
			string text = item.Trim();
			string key;
			string value;
			if (text.StartsWith("[", StringComparison.Ordinal) && text.EndsWith("]", StringComparison.Ordinal))
			{
				section = text.Substring(1, text.Length - 2);
			}
			else if (Setting(text, out key, out value))
			{
				dictionary.Add(key, new Option
				{
					Section = section,
					Key = key,
					Value = value
				});
			}
		}
		return dictionary;
	}

	private static Dictionary<string, string> ReadValues(string text, Dictionary<string, Option> schema)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
		Dictionary<string, int> dictionary2 = new Dictionary<string, int>(StringComparer.Ordinal);
		string text2 = "";
		foreach (string item in Lines(text))
		{
			string text3 = item.Trim();
			if (text3.StartsWith("[", StringComparison.Ordinal) && text3.EndsWith("]", StringComparison.Ordinal))
			{
				text2 = text3.Substring(1, text3.Length - 2);
			}
			else
			{
				if (!Setting(text3, out var key, out var value))
				{
					continue;
				}
				string text4 = key;
				if (key == "ServerOwnedStaticBuildings")
				{
					key = "ServerOwnedStaticBuildingsByDefault";
				}
				if (!schema.ContainsKey(key))
				{
					switch (key)
					{
					case "ServerFallbackPingMs":
						key = "HighTargetPingMs";
						break;
					case "ServerFallbackRadius":
						key = "NearbyAlternativeOwnerRadiusMeters";
						break;
					case "ServerOverlapCooldownSeconds":
						key = "OverlapOwnershipCooldownSeconds";
						break;
					}
				}
				if (schema.TryGetValue(key, out var value2))
				{
					int num = ((text2 == value2.Section) ? 20 : ((text2.Length == 0 && key == "Enabled") ? 30 : 10)) + ((key == text4) ? 1 : 0);
					if (!dictionary2.TryGetValue(key, out var value3) || value3 <= num)
					{
						dictionary2[key] = num;
						dictionary[key] = value;
					}
				}
			}
		}
		return dictionary;
	}

	private static string Render(Dictionary<string, string> values, List<Option> extra)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.AppendLine("## Configuration layout: 2");
		bool flag = false;
		foreach (string item in Lines("## Settings file was created by plugin TooManyLags - Standalone v@VERSION@\n## Plugin GUID: botanic.toomanylags.standalone\n\n[00 - General]\n\n## Host/server settings control gameplay, camera and mobs. Only EnableLogs is local. Clients are optional with reduced features. Restart unless marked live.\n## Enable TooManyLags for this session. Clients follow the host/server.\nEnabled = true\n\n\n[01 - Simulation Settings]\n\n## Simulation stays on players; there is no server simulation mode.\n## true: retain vacated fields. Only inner fields update automatically when one of several players leaves; outer fields wait for movement/rotation.\n## false: keep the full directional footprint with a red 3x3 centre. Native region ownership release remains active in both modes.\nKeepOwnershipOnCellExit = true\n\n\n[02 - Latency Selection]\n\n## Host/server; restart required. Smoothed ping sampling interval in seconds. Unmodded clients use native connection telemetry without an extra request.\n# Acceptable value range: From 0.5 to 10\nPingMeasurementIntervalSeconds = 2\n\n## Host/server; restart required. Required ping improvement in milliseconds before replacing a candidate; avoids jitter-driven switches.\n# Acceptable value range: From 0 to 500\nOwnershipPingMarginMs = 30\n\n\n[03 - AI Mob Ownership]\n\n## Host/server; restart required. Target-based Hostile Mob ownership requires compatible source/target clients. Friendly player summons and bosses stay vanilla; idle tamed animals use the grid.\nEnableAIOwnership = true\n\n## Live console supported. Above this target ping in milliseconds, prefer a better-connected eligible player close to the Hostile Mob. Does not change its attack target.\n# Acceptable value range: From 50 to 2000\nHighTargetPingMs = 200\n\n## Live console supported. Maximum distance in metres from the mob for a better-ping alternative owner.\n# Acceptable value range: From 1 to 20\nNearbyAlternativeOwnerRadiusMeters = 6\n\n\n[04 - Grid Settings]\n## Defaults should work well. Larger grids prepare ownership earlier for poor connections.\n\n## Cell size in metres: 4, 6.4, 8 or 16. 6.4 divides each vanilla zone into 10x10 cells. 4 requires a rounded grid. Does not change loading distances.\n# Acceptable values: 4, 6.4, 8, 16\nGridCellSizeMeters = 4\n\n## Square3x3 is square; Rounded5x5/Rounded7x7 are rounded. Directional mode omits rear fields with KeepOwnershipOnCellExit=true; false keeps the complete shape. Overlaps prefer the best eligible player ping.\n# Acceptable values: Square3x3, Rounded5x5, Rounded7x7\nGridCoveragePattern = Rounded7x7\n\n## Live console supported. Movement/fallback-heading check interval in seconds. Only changed coverage creates requests; received camera changes wake the next server pass directly. Existing handoffs progress while standing.\n# Acceptable value range: From 0.05 to 5\nMovementRotationCheckIntervalSeconds = 0.1\n\n\n[05 - Directional Grid Mode]\n\n## Recommended: leave enabled. Camera-directed grid with the timers below and camera settings in section 07. Missing camera data uses character heading. false uses the full grid from section 06. Stationary players still count.\nDirectionalGridMode = true\n\n## Live console supported. Red: six inner cells; full 3x3 with KeepOwnershipOnCellExit=false. Delay in seconds; 0 allowed. Safe handoffs can still wait.\n# Acceptable value range: From 0 to 30\nInnerTransitionDelaySeconds = 0\n\n## Live console supported. Orange: one extra three-cell row ahead of red, with 4-metre cells and rounded coverage. Delay in seconds; 0 allowed.\n# Acceptable value range: From 0 to 30\nForwardTransitionDelaySeconds = 0.2\n\n## Live console supported. Yellow: remaining active cells. Delay in seconds. Avoids unnecessary edge handoffs; lower delays can help fast movement on poor connections.\n# Acceptable value range: From 0 to 30\nOuterTransitionDelaySeconds = 3\n\n## Live console supported. Hold an overlap ownership decision for this many seconds. Exclusive fields have no hold; expiry alone causes no transfer. 0 disables.\n# Acceptable value range: From 0 to 30\nOverlapOwnershipCooldownSeconds = 1\n\n\n[06 - Full Grid Mode]\n\n## Live console supported. Only with DirectionalGridMode=false: uniform delay in seconds for new full-grid requests.\n# Acceptable value range: From 0 to 30\nTransitionDelaySeconds = 2\n\n\n[07 - Camera Heading]\n\n## Live console supported; sent to clients. Camera sample interval in seconds. 0.05 allows up to 20 checks per second; only changed coverage is published. Without a client mod, character heading is used.\n# Acceptable value range: From 0.05 to 5\nCameraHeadingCheckIntervalSeconds = 0.05\n\n## Live console supported; sent to clients. Angular overlap between adjacent directions. 30 is recommended; 0 disables base overlap. Prediction can add one further direction.\n# Acceptable value range: From 0 to 45\nCameraDirectionOverlapDegrees = 30\n\n## Live console supported; sent to clients. Predict camera rotation this many seconds ahead. At most one extra direction uses the inner/red delay. 0 disables. Requires a compatible client.\n# Acceptable value range: From 0 to 0.5\nCameraRotationPredictionSeconds = 0.1\n\n\n[09 - Logs]\n\n## Local only; live console supported. Extra diagnostics. Startup errors are always reported.\nEnableLogs = false\n\n\n[10 - Object Categories]\n\n## All categories below: host/server; restart required. true: managed by TooManyLags; false: vanilla. Active use and safe handoffs remain protected. Without compatible clients, only native-safe categories transfer.\n\n## Doors and gates.\nDoors = true\n\n## Seats and barber stations.\nSeats = true\n\n## Beds.\nBeds = true\n\n## Crafting stations and upgrades.\nWorkstations = true\n\n## Smelters, kilns, windmills and similar refill stations. Each observed insert renews a one-second hold.\nSmelters = true\n\n## Cooking stations.\nCookingStations = true\n\n## Fireplaces and refillable light sources.\nFireplaces = true\n\n## Beehives.\nBeehives = true\n\n## Sap collectors.\nSapCollectors = true\n\n## Wards.\nWards = true\n\n## Cartography tables.\nMapTables = true\n\n## Wisp fountains.\nWisplights = true\n\n## Idle tamed animals; riding, following and friendly player summons retain native control.\nTamedAnimals = true\n\n## Chests and inventories; open inventories and pending requests block transfers.\nContainers = true\n\n## Item and armour stands.\nItemStands = true\n\n## Signs; native editing retains ownership until player movement.\nSigns = true\n\n## Portals and dungeon entrances; native portal-name editing retains ownership until movement.\nPortals = true\n\n## Fermenters.\nFermenters = true\n\n## Incinerators; open inventories, pending requests and burning block transfers.\nIncinerators = true\n\n## Traps and turrets.\nDefenses = true\n\n## Shield generators.\nShieldGenerators = true\n\n## Pickable objects and feasts; excludes loose item drops.\nPickables = true\n\n## Offering altars.\nOfferings = true\n\n## Carts, boats and vehicle controls; active drivers retain control.\nVehicles = true\n\n## Other compatible modded interactables; custom local actions cannot be inferred.\nOtherInteractables = true"))
		{
			string text = item.Replace("@VERSION@", version ?? "");
			if (!flag && text.Trim() == "[10 - Object Categories]")
			{
				if (extra != null && extra.Count != 0)
				{
					stringBuilder.AppendLine("[09 - Additional Settings]");
					foreach (Option item2 in extra)
					{
						stringBuilder.AppendLine(item2.Key + " = " + item2.Value);
					}
					stringBuilder.AppendLine();
				}
				flag = true;
			}
			if (Setting(text.Trim(), out var key, out var _) && values.TryGetValue(key, out var value2))
			{
				text = key + " = " + value2;
			}
			stringBuilder.AppendLine(text);
		}
		return stringBuilder.ToString();
	}

	private static bool Setting(string line, out string key, out string value)
	{
		key = (value = null);
		if (line.Length == 0 || line[0] == '#' || line[0] == ';' || line[0] == '[')
		{
			return false;
		}
		int num = line.IndexOf('=');
		if (num <= 0)
		{
			return false;
		}
		key = line.Substring(0, num).Trim();
		value = line.Substring(num + 1).Trim();
		return key.Length != 0;
	}

	private static IEnumerable<string> Lines(string text)
	{
		using StringReader reader = new StringReader(text);
		while (true)
		{
			string text2;
			string line = (text2 = reader.ReadLine());
			if (text2 != null)
			{
				yield return line;
				continue;
			}
			break;
		}
	}

	private static void Write(string path, string text)
	{
		if (File.Exists(path) && File.ReadAllText(path) == text)
		{
			return;
		}
		string directoryName = Path.GetDirectoryName(path);
		if (!string.IsNullOrEmpty(directoryName))
		{
			Directory.CreateDirectory(directoryName);
		}
		string text2 = path + ".layout-" + Guid.NewGuid().ToString("N") + ".tmp";
		try
		{
			File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			if (File.Exists(path))
			{
				File.Replace(text2, path, null);
			}
			else
			{
				File.Move(text2, path);
			}
		}
		finally
		{
			if (File.Exists(text2))
			{
				File.Delete(text2);
			}
		}
	}
}
internal static class ConfigTemplate
{
	internal const string Text = "## Settings file was created by plugin TooManyLags - Standalone v@VERSION@\n## Plugin GUID: botanic.toomanylags.standalone\n\n[00 - General]\n\n## Host/server settings control gameplay, camera and mobs. Only EnableLogs is local. Clients are optional with reduced features. Restart unless marked live.\n## Enable TooManyLags for this session. Clients follow the host/server.\nEnabled = true\n\n\n[01 - Simulation Settings]\n\n## Simulation stays on players; there is no server simulation mode.\n## true: retain vacated fields. Only inner fields update automatically when one of several players leaves; outer fields wait for movement/rotation.\n## false: keep the full directional footprint with a red 3x3 centre. Native region ownership release remains active in both modes.\nKeepOwnershipOnCellExit = true\n\n\n[02 - Latency Selection]\n\n## Host/server; restart required. Smoothed ping sampling interval in seconds. Unmodded clients use native connection telemetry without an extra request.\n# Acceptable value range: From 0.5 to 10\nPingMeasurementIntervalSeconds = 2\n\n## Host/server; restart required. Required ping improvement in milliseconds before replacing a candidate; avoids jitter-driven switches.\n# Acceptable value range: From 0 to 500\nOwnershipPingMarginMs = 30\n\n\n[03 - AI Mob Ownership]\n\n## Host/server; restart required. Target-based Hostile Mob ownership requires compatible source/target clients. Friendly player summons and bosses stay vanilla; idle tamed animals use the grid.\nEnableAIOwnership = true\n\n## Live console supported. Above this target ping in milliseconds, prefer a better-connected eligible player close to the Hostile Mob. Does not change its attack target.\n# Acceptable value range: From 50 to 2000\nHighTargetPingMs = 200\n\n## Live console supported. Maximum distance in metres from the mob for a better-