Decompiled source of RCT Kolejka v1.0.7

BepInEx/plugins/RCTStoneRail/RCTStoneRail.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Mirror;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("RCT Kolejka")]
[assembly: AssemblyDescription("Inventory-integrated mining railway for Stonewards")]
[assembly: AssemblyFileVersion("1.0.7.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.7.0")]
namespace RCTStoneRail;

public static class Convert3
{
	public static V3 Core(Vector3 v)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		return new V3(v.x, v.y, v.z);
	}

	public static Vector3 Unity(V3 v)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(v.X, v.Y, v.Z);
	}
}
public sealed class GameBridge
{
	private readonly RailPlugin plugin;

	private readonly HashSet<string> resources = new HashSet<string>(StringComparer.Ordinal);

	private static readonly FieldInfo clustersField = typeof(DigMatterProfileSO).GetField("resourceClusters", BindingFlags.Instance | BindingFlags.NonPublic);

	private static readonly MethodInfo stackSizeMethod = typeof(InventorySystem).GetMethod("GetMaxItemStackCount", BindingFlags.Instance | BindingFlags.NonPublic);

	private float nextScan;

	public GameBridge(RailPlugin owner)
	{
		plugin = owner;
	}

	public void Reset()
	{
		resources.Clear();
		nextScan = 0f;
	}

	public void RefreshResources()
	{
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		if (Time.unscaledTime < nextScan)
		{
			return;
		}
		nextScan = Time.unscaledTime + 10f;
		string[] array = new string[6] { "STONE", "WOODENPLANK", "IRON", "GOLD", "EMERALD", "DIAMOND" };
		foreach (string item in array)
		{
			resources.Add(item);
		}
		RogueLikeDatabaseSO[] array2 = Resources.FindObjectsOfTypeAll<RogueLikeDatabaseSO>();
		for (int i = 0; i < array2.Length; i++)
		{
			SResourcesValue[] array3 = (SResourcesValue[])(((object)array2[i].ResourcesValues) ?? ((object)new SResourcesValue[0]));
			foreach (SResourcesValue val in array3)
			{
				if ((Object)(object)val.item != (Object)null)
				{
					resources.Add(val.item.itemID);
				}
			}
		}
		DigMatterProfileSO[] array4 = Resources.FindObjectsOfTypeAll<DigMatterProfileSO>();
		foreach (DigMatterProfileSO obj in array4)
		{
			IEnumerable enumerable = ((clustersField == null) ? null : (clustersField.GetValue(obj) as IEnumerable));
			if (enumerable == null)
			{
				continue;
			}
			foreach (object item2 in enumerable)
			{
				FieldInfo field = item2.GetType().GetField("resourceCluster", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				ItemDataSO val2 = (ItemDataSO)((field == null) ? null : /*isinst with value type is only supported in some contexts*/);
				if (!((Object)(object)val2 == (Object)null))
				{
					resources.Add(val2.itemID);
					if (val2.isScrapItem && (Object)(object)val2.itemProduced != (Object)null)
					{
						resources.Add(val2.itemProduced.itemID);
					}
				}
			}
		}
	}

	public ItemDataSO Item(string id)
	{
		if (!((Object)(object)ItemManager.Instance == (Object)null) && !string.IsNullOrEmpty(id))
		{
			return ItemManager.Instance.GetItemDataSoByID(id);
		}
		return null;
	}

	public bool IsResource(string id)
	{
		ItemDataSO val = Item(id);
		if ((Object)(object)val != (Object)null && val.isStackable && resources.Contains(id))
		{
			return (Object)(object)val.pickableItemPrefab != (Object)null;
		}
		return false;
	}

	public string Name(string id)
	{
		ItemDataSO val = Item(id);
		if ((Object)(object)val == (Object)null)
		{
			return id ?? "?";
		}
		try
		{
			string localizedName = val.GetLocalizedName();
			return string.IsNullOrEmpty(localizedName) ? id : localizedName;
		}
		catch
		{
			return id;
		}
	}

	public int InventorySpace(InventorySystem inventory, ItemDataSO item)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)inventory == (Object)null || (Object)(object)item == (Object)null || stackSizeMethod == null)
		{
			return 0;
		}
		int num = (int)stackSizeMethod.Invoke(inventory, new object[1] { item });
		long num2 = 0L;
		Enumerator<InventoryEntry> enumerator = inventory.InventoryEntries.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				InventoryEntry current = enumerator.Current;
				if (((SlotParameters)(ref current.slotParameters)).CanReceiveItem(item.itemID))
				{
					if (((InventoryEntry)(ref current)).IsEmpty)
					{
						num2 += num;
					}
					else if (current.itemID == item.itemID && item.isStackable)
					{
						num2 += Math.Max(0, num - current.count);
					}
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		return (int)Math.Min(10000L, num2);
	}

	public int RemoveInventory(InventorySystem inventory, string id, int amount)
	{
		ItemDataSO val = Item(id);
		if ((Object)(object)val == (Object)null || amount <= 0)
		{
			return 0;
		}
		int itemCount = inventory.GetItemCount(id);
		amount = Math.Min(itemCount, amount);
		try
		{
			int num = amount;
			inventory.ServerRemoveItemQuantity(val, ref num);
		}
		catch (Exception e)
		{
			plugin.LogError("Odbieranie surowca z ekwipunku", e);
		}
		return Math.Min(amount, Math.Max(0, itemCount - inventory.GetItemCount(id)));
	}

	public int AddInventory(InventorySystem inventory, string id, int amount)
	{
		ItemDataSO val = Item(id);
		if ((Object)(object)val == (Object)null || amount <= 0)
		{
			return 0;
		}
		int itemCount = inventory.GetItemCount(id);
		amount = Math.Min(amount, InventorySpace(inventory, val));
		if (amount <= 0)
		{
			return 0;
		}
		try
		{
			inventory.ServerAddItem(val, amount);
		}
		catch (Exception e)
		{
			plugin.LogError("Dodawanie surowca do ekwipunku", e);
		}
		return Math.Min(amount, Math.Max(0, inventory.GetItemCount(id) - itemCount));
	}

	public int Deposit(FirstPersonController player, CargoStore store, string onlyId, int limit)
	{
		InventorySystem inventorySystem = player.InventorySystem;
		int num = 0;
		string[] array = (from e in (IEnumerable<InventoryEntry>)inventorySystem.InventoryEntries
			where !((InventoryEntry)(ref e)).IsEmpty
			select e.itemID).Distinct().ToArray();
		foreach (string text in array)
		{
			if ((onlyId == null || !(onlyId != text)) && IsResource(text))
			{
				int num3 = Math.Min(Math.Min(limit - num, store.RoomFor(text)), inventorySystem.GetItemCount(text));
				if (num3 > 0)
				{
					int num4 = RemoveInventory(inventorySystem, text, num3);
					store.Add(text, num4);
					num += num4;
				}
			}
		}
		return num;
	}

	public int DepositSlot(FirstPersonController player, CargoStore store, int slot, string id, int limit)
	{
		//IL_0037: 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_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)player == (Object)null || slot < 0 || slot >= player.InventorySystem.InventoryEntries.Count || string.IsNullOrEmpty(id))
		{
			return 0;
		}
		InventoryEntry val = player.InventorySystem.InventoryEntries[slot];
		if (((InventoryEntry)(ref val)).IsEmpty || val.itemID != id || !IsResource(id))
		{
			return 0;
		}
		int num = Math.Min(Math.Min(Math.Min(limit, store.RoomFor(id)), val.count), 10000);
		if (num <= 0)
		{
			return 0;
		}
		if (!player.InventorySystem.ServerRemoveItemFromSlot(slot, num))
		{
			return 0;
		}
		return store.Add(id, num);
	}

	public int Withdraw(FirstPersonController player, CargoStore store, string onlyId, int limit)
	{
		int num = 0;
		string[] array = store.Items.Keys.ToArray();
		foreach (string text in array)
		{
			if (onlyId == null || !(onlyId != text))
			{
				int num2 = AddInventory(player.InventorySystem, text, Math.Min(store.Count(text), limit - num));
				store.Remove(text, num2);
				num += num2;
				if (num >= limit)
				{
					break;
				}
			}
		}
		return num;
	}
}
[Serializable]
public struct V3
{
	public float X;

	public float Y;

	public float Z;

	[JsonIgnore]
	public float Length => (float)Math.Sqrt(X * X + Y * Y + Z * Z);

	[JsonIgnore]
	public bool Finite
	{
		get
		{
			if (!float.IsNaN(X) && !float.IsNaN(Y) && !float.IsNaN(Z) && !float.IsInfinity(X) && !float.IsInfinity(Y))
			{
				return !float.IsInfinity(Z);
			}
			return false;
		}
	}

	[JsonIgnore]
	public V3 Normalized
	{
		get
		{
			if (!(Length > 1E-05f))
			{
				return new V3(0f, 0f, 1f);
			}
			return this * (1f / Length);
		}
	}

	public V3(float x, float y, float z)
	{
		X = x;
		Y = y;
		Z = z;
	}

	public static V3 operator +(V3 a, V3 b)
	{
		return new V3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
	}

	public static V3 operator -(V3 a, V3 b)
	{
		return new V3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
	}

	public static V3 operator *(V3 a, float b)
	{
		return new V3(a.X * b, a.Y * b, a.Z * b);
	}

	public static float Dot(V3 a, V3 b)
	{
		return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
	}

	public static float Distance(V3 a, V3 b)
	{
		return (a - b).Length;
	}

	public static V3 Lerp(V3 a, V3 b, float t)
	{
		return a + (b - a) * t;
	}
}
[Serializable]
public sealed class CargoStore
{
	public int Capacity = 1000;

	public Dictionary<string, int> Items = new Dictionary<string, int>(StringComparer.Ordinal);

	[JsonIgnore]
	public int Total => Items.Values.Sum();

	[JsonIgnore]
	public int Free => Math.Max(0, Capacity - Total);

	public int Count(string id)
	{
		if (id == null || !Items.TryGetValue(id, out var value))
		{
			return 0;
		}
		return value;
	}

	public int RoomFor(string id)
	{
		if (string.IsNullOrEmpty(id) || id.Length > 128 || (!Items.ContainsKey(id) && Items.Count >= 64))
		{
			return 0;
		}
		return Free;
	}

	public int Add(string id, int count)
	{
		int num = Math.Min(Math.Max(0, count), RoomFor(id));
		if (num > 0)
		{
			Items[id] = Count(id) + num;
		}
		return num;
	}

	public int Remove(string id, int count)
	{
		int num = Math.Min(Math.Max(0, count), Count(id));
		if (num > 0)
		{
			int num2 = Count(id) - num;
			if (num2 == 0)
			{
				Items.Remove(id);
			}
			else
			{
				Items[id] = num2;
			}
		}
		return num;
	}

	public static int Move(CargoStore source, CargoStore destination, int limit)
	{
		if (source == destination || limit <= 0)
		{
			return 0;
		}
		int num = 0;
		string[] array = source.Items.Keys.OrderBy<string, string>((string x) => x, StringComparer.Ordinal).ToArray();
		foreach (string id in array)
		{
			int num3 = Math.Min(source.Count(id), Math.Min(destination.RoomFor(id), limit - num));
			if (num3 > 0)
			{
				source.Remove(id, num3);
				destination.Add(id, num3);
				num += num3;
				if (num >= limit)
				{
					break;
				}
			}
		}
		return num;
	}
}
public static class Scalar
{
	public static bool Finite(float f)
	{
		if (!float.IsNaN(f))
		{
			return !float.IsInfinity(f);
		}
		return false;
	}
}
public static class RailDurability
{
	public static float ApplyHit(float health, float damage)
	{
		float num = health - damage;
		if (!(num < 1E-06f))
		{
			return num;
		}
		return 0f;
	}

	public static float HitFraction(float hits, float strength, float multiplier)
	{
		if (!Scalar.Finite(hits) || !Scalar.Finite(strength) || !Scalar.Finite(multiplier) || hits <= 0f || strength <= 0f || multiplier <= 0f)
		{
			return 0f;
		}
		float num = strength * multiplier / hits;
		if (!Scalar.Finite(num))
		{
			return 0f;
		}
		return num;
	}
}
public static class RailProtocol
{
	public const int Current = 5;
}
public enum ActionKind : byte
{
	Hello,
	Place,
	Start,
	Deposit,
	Withdraw,
	Hit
}
public enum RailTargetKind : byte
{
	Rail,
	Cart,
	Plank
}
[Serializable]
public sealed class RailSegment
{
	public int Id;

	public float Health = 1f;

	public V3[] Points = new V3[0];

	[JsonIgnore]
	public float Length
	{
		get
		{
			float num = 0f;
			for (int i = 1; i < Points.Length; i++)
			{
				num += V3.Distance(Points[i - 1], Points[i]);
			}
			return num;
		}
	}

	public V3 End(int side)
	{
		return Points[(side != 0) ? (Points.Length - 1) : 0];
	}

	public V3 Outward(int side)
	{
		return ((side == 0) ? (Points[0] - Points[1]) : (Points[Points.Length - 1] - Points[Points.Length - 2])).Normalized;
	}

	public V3 Sample(float distance, out V3 tangent)
	{
		distance = Math.Max(0f, distance);
		for (int i = 1; i < Points.Length; i++)
		{
			V3 v = Points[i] - Points[i - 1];
			float length = v.Length;
			if (distance <= length || i == Points.Length - 1)
			{
				tangent = v.Normalized;
				return V3.Lerp(Points[i - 1], Points[i], Math.Min(1f, distance / Math.Max(1E-05f, length)));
			}
			distance -= length;
		}
		tangent = new V3(0f, 0f, 1f);
		if (Points.Length != 0)
		{
			return Points[0];
		}
		return default(V3);
	}

	public float Nearest(V3 p, out float distance)
	{
		distance = 0f;
		float num = float.MaxValue;
		float num2 = 0f;
		for (int i = 1; i < Points.Length; i++)
		{
			V3 v = Points[i] - Points[i - 1];
			float length = v.Length;
			float num3 = Math.Max(0f, Math.Min(1f, V3.Dot(p - Points[i - 1], v) / Math.Max(1E-06f, length * length)));
			float num4 = V3.Distance(p, Points[i - 1] + v * num3);
			if (num4 < num)
			{
				num = num4;
				distance = num2 + num3 * length;
			}
			num2 += length;
		}
		return num;
	}
}
[Serializable]
public sealed class RailCart
{
	public int Id;

	public int Rail;

	public float Distance;

	public float Health = 1f;

	public int Direction = 1;

	public bool Running;

	public string StopReason = "";

	public CargoStore Cargo = new CargoStore
	{
		Capacity = 120
	};
}
[Serializable]
public sealed class RailPlank
{
	public int Id;

	public V3 Position;

	public float Yaw;

	public float Health = 1f;
}
[Serializable]
public sealed class RailState
{
	public int Protocol = 5;

	public int Revision;

	public int NextId = 1;

	public string Session = "";

	public string World = "test";

	public float Speed = 3f;

	public int CartCapacity = 120;

	public List<RailSegment> Rails = new List<RailSegment>();

	public List<RailCart> Carts = new List<RailCart>();

	public List<RailPlank> Planks = new List<RailPlank>();

	public RailSegment Track(int id)
	{
		return Rails.Find((RailSegment r) => r.Id == id);
	}

	public RailCart Cart(int id)
	{
		return Carts.Find((RailCart c) => c.Id == id);
	}

	public RailPlank Plank(int id)
	{
		return Planks.Find((RailPlank p) => p.Id == id);
	}

	public V3 CartPosition(RailCart c)
	{
		V3 tangent;
		return Track(c.Rail)?.Sample(c.Distance, out tangent) ?? default(V3);
	}

	public void Normalize()
	{
		Rails = Rails ?? new List<RailSegment>();
		Carts = Carts ?? new List<RailCart>();
		Planks = Planks ?? new List<RailPlank>();
	}

	public bool Valid()
	{
		if (World == null || World.Length < 1 || World.Length > 256 || Protocol != 5 || Session == null || Session.Length != 32 || !Guid.TryParseExact(Session, "N", out var _) || NextId < 1 || Revision < 0 || !Scalar.Finite(Speed) || Speed < 0.25f || Speed > 6f || CartCapacity < 1 || CartCapacity > 10000 || Rails == null || Carts == null || Planks == null || Rails.Count > 256 || Carts.Count > 16 || Planks.Count > 128)
		{
			return false;
		}
		HashSet<int> hashSet = new HashSet<int>();
		foreach (RailSegment rail in Rails)
		{
			if (rail == null || rail.Id <= 0 || rail.Id >= NextId || !hashSet.Add(rail.Id) || !Healthy(rail.Health) || rail.Points == null || (rail.Points.Length != 9 && rail.Points.Length != 17))
			{
				return false;
			}
			V3[] points = rail.Points;
			for (int i = 0; i < points.Length; i++)
			{
				V3 v = points[i];
				if (!v.Finite || v.Length > 100000f)
				{
					return false;
				}
			}
			for (int j = 1; j < rail.Points.Length; j++)
			{
				if (V3.Distance(rail.Points[j - 1], rail.Points[j]) < 0.005f || V3.Distance(rail.Points[j - 1], rail.Points[j]) > 1f)
				{
					return false;
				}
			}
			if (rail.Length < 0.25f || rail.Length > 5f)
			{
				return false;
			}
		}
		foreach (RailCart cart in Carts)
		{
			RailSegment railSegment = ((cart == null) ? null : Track(cart.Rail));
			if (cart == null || cart.Id <= 0 || cart.Id >= NextId || !hashSet.Add(cart.Id) || railSegment == null || !Healthy(cart.Health) || !Scalar.Finite(cart.Distance) || cart.Distance < 0f || cart.Distance > railSegment.Length + 0.001f || (cart.Direction != 1 && cart.Direction != -1) || !ValidCargo(cart.Cargo) || cart.StopReason == null || cart.StopReason.Length > 256)
			{
				return false;
			}
		}
		foreach (RailPlank plank in Planks)
		{
			if (plank == null || plank.Id <= 0 || plank.Id >= NextId || !hashSet.Add(plank.Id) || !plank.Position.Finite || plank.Position.Length > 100000f || !Scalar.Finite(plank.Yaw) || !Healthy(plank.Health))
			{
				return false;
			}
		}
		return true;
	}

	private static bool Healthy(float h)
	{
		if (Scalar.Finite(h) && h > 0f)
		{
			return h <= 1f;
		}
		return false;
	}

	private static bool ValidCargo(CargoStore c)
	{
		if (c == null || c.Capacity < 1 || c.Capacity > 10000 || c.Items == null || c.Items.Count > 64)
		{
			return false;
		}
		long num = 0L;
		foreach (KeyValuePair<string, int> item in c.Items)
		{
			if (string.IsNullOrEmpty(item.Key) || item.Key.Length > 128 || item.Value < 1 || item.Value > 10000)
			{
				return false;
			}
			num += item.Value;
		}
		return num <= c.Capacity;
	}
}
public static class RailPlankRules
{
	public const float Width = 1.4f;

	public const float Length = 2.4f;

	public const float Thickness = 0.1f;

	public const float SnapRadius = 2.7f;

	public const float JoinTolerance = 0.02f;

	public const int Limit = 128;

	public static float QuantizeYaw(float yaw)
	{
		if (!Scalar.Finite(yaw))
		{
			yaw = 0f;
		}
		float num = (float)Math.Round(yaw / 90f) * 90f;
		num %= 360f;
		if (num < 0f)
		{
			num += 360f;
		}
		if (num >= 360f)
		{
			num -= 360f;
		}
		return num;
	}

	public static void Footprint(float yaw, out float halfX, out float halfZ)
	{
		int num = (int)Math.Round(QuantizeYaw(yaw) / 90f) & 3;
		halfX = ((num % 2 == 0) ? 0.7f : 1.2f);
		halfZ = ((num % 2 == 0) ? 1.2f : 0.7f);
	}

	public static bool Overlaps(RailPlank existing, V3 center, float yaw)
	{
		if (existing == null)
		{
			return false;
		}
		Footprint(existing.Yaw, out var halfX, out var halfZ);
		Footprint(yaw, out var halfX2, out var halfZ2);
		if (Math.Abs(center.X - existing.Position.X) < halfX + halfX2 - 0.02f && Math.Abs(center.Z - existing.Position.Z) < halfZ + halfZ2 - 0.02f)
		{
			return Math.Abs(center.Y - existing.Position.Y) < 0.6f;
		}
		return false;
	}

	public static bool OverlapAny(RailState state, V3 center, float yaw)
	{
		if (state == null || state.Planks == null)
		{
			return false;
		}
		foreach (RailPlank plank in state.Planks)
		{
			if (Overlaps(plank, center, yaw))
			{
				return true;
			}
		}
		return false;
	}

	public static V3 Right(float yaw)
	{
		double num = (double)yaw * Math.PI / 180.0;
		return new V3((float)Math.Cos(num), 0f, 0f - (float)Math.Sin(num));
	}

	public static V3 Forward(float yaw)
	{
		double num = (double)yaw * Math.PI / 180.0;
		return new V3((float)Math.Sin(num), 0f, (float)Math.Cos(num));
	}

	public static bool TryPlan(RailState state, V3 aim, float yaw, out RailPlank plank, out bool snapped)
	{
		plank = null;
		snapped = false;
		if (state == null || !aim.Finite || !Scalar.Finite(yaw))
		{
			return false;
		}
		if (state.Planks == null)
		{
			state.Planks = new List<RailPlank>();
		}
		if (state.Planks.Count >= 128)
		{
			return false;
		}
		float yaw2 = QuantizeYaw(yaw);
		RailPlank railPlank = null;
		float num = 2.7f;
		foreach (RailPlank plank2 in state.Planks)
		{
			if (plank2 == null || !plank2.Position.Finite || !Scalar.Finite(plank2.Yaw))
			{
				continue;
			}
			float yaw3 = QuantizeYaw(plank2.Yaw);
			V3 v = Right(yaw3);
			V3 v2 = Forward(yaw3);
			V3[] array = new V3[4]
			{
				v * 1.4f,
				v * -1.4f,
				v2 * 2.4f,
				v2 * -2.4f
			};
			foreach (V3 v3 in array)
			{
				RailPlank railPlank2 = new RailPlank
				{
					Position = plank2.Position + v3,
					Yaw = yaw3
				};
				if (!OverlapAny(state, railPlank2.Position, railPlank2.Yaw))
				{
					float num2 = Horizontal(railPlank2.Position, aim) + Math.Abs(railPlank2.Position.Y - aim.Y) * 2f;
					if (num2 < num)
					{
						num = num2;
						railPlank = railPlank2;
					}
				}
			}
		}
		if (railPlank != null)
		{
			plank = railPlank;
			snapped = true;
			return true;
		}
		if (OverlapAny(state, aim, yaw2))
		{
			return false;
		}
		plank = new RailPlank
		{
			Position = new V3(aim.X, aim.Y, aim.Z),
			Yaw = yaw2
		};
		return true;
	}

	private static float Horizontal(V3 a, V3 b)
	{
		float num = a.X - b.X;
		float num2 = a.Z - b.Z;
		return (float)Math.Sqrt(num * num + num2 * num2);
	}
}
public static class RailGraph
{
	public const float JoinTolerance = 0.035f;

	public static float HorizontalDot(V3 a, V3 b)
	{
		a.Y = 0f;
		b.Y = 0f;
		if (a.Length < 1E-05f || b.Length < 1E-05f)
		{
			return 1f;
		}
		return V3.Dot(a.Normalized, b.Normalized);
	}

	public static RailSegment ClosestOpenEnd(RailState state, V3 point, V3 heading, float radius, int skipId, out int side)
	{
		RailSegment result = null;
		side = 0;
		foreach (RailSegment rail in state.Rails)
		{
			if (rail.Id == skipId)
			{
				continue;
			}
			for (int i = 0; i < 2; i++)
			{
				float num = V3.Distance(point, rail.End(i));
				if (num < radius && IsOpen(state, rail, i) && HorizontalDot(heading, rail.Outward(i)) < -0.75f)
				{
					result = rail;
					side = i;
					radius = num;
				}
			}
		}
		return result;
	}

	public static RailSegment Next(RailState s, RailSegment current, int side, out int nextSide)
	{
		nextSide = 0;
		foreach (RailSegment rail in s.Rails)
		{
			if (rail.Id == current.Id)
			{
				continue;
			}
			for (int i = 0; i < 2; i++)
			{
				if (V3.Distance(current.End(side), rail.End(i)) < 0.035f && HorizontalDot(current.Outward(side), rail.Outward(i)) < -0.65f)
				{
					nextSide = i;
					return rail;
				}
			}
		}
		return null;
	}

	public static bool IsOpen(RailState s, RailSegment r, int side)
	{
		int nextSide;
		return Next(s, r, side, out nextSide) == null;
	}

	public static void Start(RailState s, RailCart cart)
	{
		RailSegment railSegment = s.Track(cart.Rail);
		if (railSegment != null)
		{
			int num = ((cart.Direction > 0) ? 1 : 0);
			if (((num == 1) ? (cart.Distance >= railSegment.Length - 0.001f) : (cart.Distance <= 0.001f)) && Next(s, railSegment, num, out var _) == null)
			{
				cart.Direction = -cart.Direction;
			}
			cart.StopReason = "";
			cart.Running = true;
		}
	}

	public static void Tick(RailState s, RailCart cart, float seconds)
	{
		if (!cart.Running || !Scalar.Finite(seconds) || seconds <= 0f)
		{
			return;
		}
		float num = s.Speed * Math.Min(seconds, 1f);
		int num2 = 0;
		while (num > 1E-06f && num2 < 64)
		{
			RailSegment railSegment = s.Track(cart.Rail);
			if (railSegment == null)
			{
				cart.Running = false;
				break;
			}
			float num3 = ((cart.Direction > 0) ? (railSegment.Length - cart.Distance) : cart.Distance);
			float num4 = Math.Min(num, Math.Max(0f, num3));
			cart.Distance += num4 * (float)cart.Direction;
			num -= num4;
			if (!(num3 > num4 + 1E-06f))
			{
				int side = ((cart.Direction > 0) ? 1 : 0);
				int nextSide;
				RailSegment railSegment2 = Next(s, railSegment, side, out nextSide);
				if (railSegment2 == null)
				{
					cart.Running = false;
					cart.StopReason = "Koniec torów";
					break;
				}
				cart.Rail = railSegment2.Id;
				cart.Distance = ((nextSide == 0) ? 0f : railSegment2.Length);
				cart.Direction = ((nextSide == 0) ? 1 : (-1));
				num2++;
				continue;
			}
			break;
		}
	}
}
public static class RailCrafting
{
	public const string RailItem = "STONERAIL_RAIL";

	public const string CartItem = "STONERAIL_CART";

	public const string PlankItem = "STONERAIL_PLANK";

	public const string WoodItem = "WOODENPLANK";

	public const string IronItem = "IRON";

	public const string EmeraldItem = "EMERALD";

	private static readonly Dictionary<string, ItemDataSO> products = new Dictionary<string, ItemDataSO>();

	private static readonly Dictionary<string, ItemPerWorldDataSO> ingredients = new Dictionary<string, ItemPerWorldDataSO>();

	private static readonly Dictionary<string, GameObject> visuals = new Dictionary<string, GameObject>();

	private static readonly Dictionary<string, string> labels = new Dictionary<string, string>
	{
		["STONERAIL_RAIL"] = "Szyny górnicze",
		["STONERAIL_CART"] = "Wagonik górniczy",
		["STONERAIL_PLANK"] = "Deska"
	};

	private static readonly Dictionary<string, string> descriptions = new Dictionary<string, string>
	{
		["STONERAIL_RAIL"] = "Wybierz w pasku i postaw lewym przyciskiem myszy. Końce łączą się automatycznie, a szyny dopasowują się do podłoża.",
		["STONERAIL_CART"] = "Postaw na szynach. Interakcja: jedź lub zatrzymaj. Surowiec w ręce + lewy przycisk: załaduj. Prawy przycisk: odbierz ładunek.",
		["STONERAIL_PLANK"] = "Deska 1,4 × 2,4 m. Kładź lewym przyciskiem myszy — krawędzie łączą się automatycznie. Po deskach można prowadzić szyny nad wykopami. Rozbiórka kilofem."
	};

	private static readonly FieldInfo databaseField = AccessTools.Field(typeof(ItemManager), "itemDataBase");

	private static readonly MethodInfo generateVisuals = AccessTools.Method(typeof(CrafterOutputSlot), "GenerateVisuals", (Type[])null, (Type[])null);

	private static GameObject templates;

	private static bool installing;

	public static bool IsProduct(string id)
	{
		if (!(id == "STONERAIL_RAIL") && !(id == "STONERAIL_CART"))
		{
			return id == "STONERAIL_PLANK";
		}
		return true;
	}

	public static string Label(string id)
	{
		if (id == null || !labels.TryGetValue(id, out var value))
		{
			return id;
		}
		return value;
	}

	public static GameObject Visual(string id)
	{
		if (id == null || !visuals.TryGetValue(id, out var value))
		{
			return null;
		}
		return value;
	}

	public static void Patch(Harmony h)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Expected O, but got Unknown
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Expected O, but got Unknown
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Expected O, but got Unknown
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Expected O, but got Unknown
		//IL_017e: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Expected O, but got Unknown
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Expected O, but got Unknown
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f7: Expected O, but got Unknown
		h.Patch((MethodBase)AccessTools.Method(typeof(ItemManager), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(RailCrafting), "Ensure", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(CraftManager), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(RailCrafting), "Ensure", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(UICraftMenu), "InitRecipes", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailCrafting), "Ensure", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(ItemDataSO), "GetLocalizedName", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailCrafting), "NamePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(ItemDataSO), "GetLocalizedDescription", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailCrafting), "DescriptionPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(ItemPerWorldDataSO), "GetItemDataSO", new Type[1] { typeof(string) }, (Type[])null), new HarmonyMethod(typeof(RailCrafting), "IngredientPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(CrafterOutputSlot), "OnItemIDChanged", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(RailCrafting), "SlotPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(PickableItem), "OnStartClient", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(RailCrafting), "PickupPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(PickableItem), "NetworkInit", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(RailCrafting), "PickupPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	public static void Ensure()
	{
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Expected O, but got Unknown
		//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d3: Expected O, but got Unknown
		//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fe: Expected O, but got Unknown
		//IL_0335: Unknown result type (might be due to invalid IL or missing references)
		//IL_033f: Unknown result type (might be due to invalid IL or missing references)
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		if (installing || (Object)(object)ItemManager.Instance == (Object)null || (Object)(object)RailPlugin.Instance == (Object)null)
		{
			return;
		}
		installing = true;
		try
		{
			object? value = databaseField.GetValue(ItemManager.Instance);
			ItemDatabaseSO val = (ItemDatabaseSO)((value is ItemDatabaseSO) ? value : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			ItemDataSO val2 = ((IEnumerable<ItemDataSO>)val.items).FirstOrDefault((Func<ItemDataSO, bool>)((ItemDataSO i) => (Object)(object)i != (Object)null && !IsProduct(i.itemID) && i.equippedItemPrefab is LadderTool && (Object)(object)i.pickableItemPrefab != (Object)null && ((object)i.pickableItemPrefab).GetType() == typeof(PickableItem))) ?? ((IEnumerable<ItemDataSO>)val.items).FirstOrDefault((Func<ItemDataSO, bool>)((ItemDataSO i) => (Object)(object)i != (Object)null && !IsProduct(i.itemID) && !i.isScrapItem && (Object)(object)i.pickableItemPrefab != (Object)null && ((object)i.pickableItemPrefab).GetType() == typeof(PickableItem)));
			if ((Object)(object)val2 == (Object)null)
			{
				throw new InvalidOperationException("Brak standardowego prefabu PickableItem w bazie gry.");
			}
			if ((Object)(object)templates == (Object)null)
			{
				templates = new GameObject("RCT Kolejka item templates");
				templates.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)templates);
			}
			string[] array = new string[3] { "STONERAIL_RAIL", "STONERAIL_CART", "STONERAIL_PLANK" };
			foreach (string id in array)
			{
				if (!products.TryGetValue(id, out var item) || (Object)(object)item == (Object)null)
				{
					item = ScriptableObject.CreateInstance<ItemDataSO>();
					((Object)item).name = id;
					item.itemID = id;
					((Object)item).hideFlags = (HideFlags)32;
					item.isStackable = true;
					item.maxStackSize = ((id == "STONERAIL_RAIL") ? 50 : ((id == "STONERAIL_PLANK") ? 20 : 10));
					item.pickableItemPrefab = val2.pickableItemPrefab;
					item.isScrapItem = false;
					item.spawnWithVFX = true;
					item.itemIcon = LoadIcon((id == "STONERAIL_RAIL") ? "rail" : ((id == "STONERAIL_CART") ? "cart" : "plank"));
					GameObject val3 = RailPlugin.Instance.Visuals.ItemModel(id, templates.transform);
					((Object)val3).name = "RCT " + id + " table visual";
					visuals[id] = val3;
					item.visualItemPrefabs = new List<GameObject> { val3 };
					GameObject val4 = new GameObject("RCT " + id + " equipped");
					val4.SetActive(false);
					val4.transform.SetParent(templates.transform, false);
					GameObject val5 = new GameObject("Pivot");
					val5.transform.SetParent(val4.transform, false);
					val5.AddComponent<Animator>();
					GameObject obj = Object.Instantiate<GameObject>(val3, val5.transform);
					obj.SetActive(true);
					obj.transform.localScale = Vector3.one * 0.55f;
					obj.transform.localPosition = new Vector3(0.25f, -0.23f, 0.45f);
					item.equippedItemPrefab = (EquippedItem)(object)val4.AddComponent<RailBuildTool>();
					products[id] = item;
				}
				val.items.RemoveAll((ItemDataSO i) => (Object)(object)i != (Object)null && i.itemID == id && (Object)(object)i != (Object)(object)item);
				if (!val.items.Contains(item))
				{
					val.items.Add(item);
				}
			}
			if ((Object)(object)CraftManager.Instance != (Object)null)
			{
				InstallRecipes(CraftManager.Instance.CraftRecipeDatabase);
			}
		}
		catch (Exception e)
		{
			RailPlugin.Instance.LogError("Rejestracja przedmiotów Craftera", e);
		}
		finally
		{
			installing = false;
		}
	}

	private static Sprite LoadIcon(string name)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Expected O, but got Unknown
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		using Stream stream = typeof(RailCrafting).Assembly.GetManifestResourceStream("RCTStoneRail.Icons." + name + ".png");
		if (stream == null)
		{
			throw new FileNotFoundException("Brak ikony w DLL: " + name);
		}
		using MemoryStream memoryStream = new MemoryStream();
		stream.CopyTo(memoryStream);
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
		MethodInfo method = typeof(ImageConversion).GetMethod("LoadImage", new Type[3]
		{
			typeof(Texture2D),
			typeof(byte[]),
			typeof(bool)
		});
		if (method == null || !(bool)method.Invoke(null, new object[3]
		{
			val,
			memoryStream.ToArray(),
			true
		}))
		{
			throw new InvalidDataException("Błędna ikona: " + name);
		}
		((Object)val).name = "RCT icon " + name;
		((Object)val).hideFlags = (HideFlags)32;
		((Texture)val).filterMode = (FilterMode)1;
		return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
	}

	private static ItemPerWorldDataSO Ingredient(string id)
	{
		if ((Object)(object)ItemManager.Instance.GetItemDataSoByID(id) == (Object)null)
		{
			throw new InvalidOperationException("Brak składnika " + id);
		}
		if (!ingredients.TryGetValue(id, out var value) || (Object)(object)value == (Object)null)
		{
			value = ScriptableObject.CreateInstance<ItemPerWorldDataSO>();
			((Object)value).name = "RCTIngredient_" + id;
			((Object)value).hideFlags = (HideFlags)32;
			ingredients[id] = value;
		}
		return value;
	}

	private static void InstallRecipes(CraftRecipeDatabaseSO db)
	{
		if (!((Object)(object)db == (Object)null) && db.Recipes != null)
		{
			AddRecipe(db, "STONERAIL_RAIL", 2.5f, new string[2] { "IRON", "WOODENPLANK" }, new int[2] { 2, 3 });
			AddRecipe(db, "STONERAIL_CART", 8f, new string[2] { "IRON", "EMERALD" }, new int[2] { 5, 2 });
			AddRecipe(db, "STONERAIL_PLANK", 1.5f, new string[1] { "WOODENPLANK" }, new int[1] { 3 });
		}
	}

	private static void AddRecipe(CraftRecipeDatabaseSO db, string id, float seconds, string[] ids, int[] counts)
	{
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		CraftRecipeSO val = ((IEnumerable<CraftRecipeSO>)db.Recipes).FirstOrDefault((Func<CraftRecipeSO, bool>)((CraftRecipeSO r) => (Object)(object)r != (Object)null && (Object)(object)r.itemCrafted != (Object)null && r.itemCrafted.itemID == id));
		if (!((Object)(object)val != (Object)null) || !((Object)(object)val.itemCrafted == (Object)(object)products[id]))
		{
			if ((Object)(object)val != (Object)null)
			{
				db.Recipes.Remove(val);
			}
			CraftRecipeSO val2 = ScriptableObject.CreateInstance<CraftRecipeSO>();
			((Object)val2).name = "RCT recipe " + id;
			((Object)val2).hideFlags = (HideFlags)32;
			val2.itemCrafted = products[id];
			val2.timeToProduceItem = seconds;
			val2.exclusiveClasses = new List<PlayerClass>();
			val2.itemsRequired = new List<ItemRequired>();
			for (int num = 0; num < ids.Length; num++)
			{
				val2.itemsRequired.Add(new ItemRequired
				{
					itemPerWorld = Ingredient(ids[num]),
					countRequired = counts[num]
				});
			}
			db.Recipes.Add(val2);
		}
	}

	private static bool IngredientPrefix(ItemPerWorldDataSO __instance, ref ItemDataSO __result, string __0)
	{
		if ((Object)(object)__instance == (Object)null || !((Object)__instance).name.StartsWith("RCTIngredient_", StringComparison.Ordinal))
		{
			return true;
		}
		__result = (((Object)(object)ItemManager.Instance == (Object)null) ? null : RailRecipeMaterials.Resolve(ItemManager.Instance, ((Object)__instance).name.Substring(14), __0));
		return false;
	}

	private static bool NamePrefix(ItemDataSO __instance, ref string __result)
	{
		if ((Object)(object)__instance == (Object)null || !IsProduct(__instance.itemID))
		{
			return true;
		}
		__result = Label(__instance.itemID);
		return false;
	}

	private static bool DescriptionPrefix(ItemDataSO __instance, ref string __result)
	{
		if ((Object)(object)__instance == (Object)null || !IsProduct(__instance.itemID))
		{
			return true;
		}
		__result = descriptions[__instance.itemID];
		return false;
	}

	private static void SlotPostfix(CrafterOutputSlot __instance)
	{
		GameObject val = Visual(__instance.ItemID);
		if ((Object)(object)val != (Object)null)
		{
			generateVisuals.Invoke(__instance, new object[1] { val });
		}
	}

	private static void PickupPostfix(PickableItem __instance)
	{
		if (IsProduct(__instance.NetworkSyncItemID))
		{
			(((Component)__instance).GetComponent<RailPickupVisual>() ?? ((Component)__instance).gameObject.AddComponent<RailPickupVisual>()).Refresh(__instance.NetworkSyncItemID);
		}
	}
}
public sealed class RailPickupVisual : MonoBehaviour
{
	private string current;

	private Renderer[] originals;

	public void Refresh(string id)
	{
		//IL_006b: 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)
		if (current == id)
		{
			return;
		}
		GameObject val = RailCrafting.Visual(id);
		if (!((Object)(object)val == (Object)null))
		{
			current = id;
			originals = ((Component)this).GetComponentsInChildren<Renderer>(true);
			Renderer[] array = originals;
			for (int i = 0; i < array.Length; i++)
			{
				array[i].enabled = false;
			}
			GameObject obj = Object.Instantiate<GameObject>(val, ((Component)this).transform);
			obj.SetActive(true);
			obj.transform.localPosition = Vector3.zero;
			obj.transform.localRotation = Quaternion.identity;
		}
	}

	private void LateUpdate()
	{
		if (originals == null)
		{
			return;
		}
		Renderer[] array = originals;
		foreach (Renderer val in array)
		{
			if ((Object)(object)val != (Object)null)
			{
				val.enabled = false;
			}
		}
	}
}
public sealed class RailBuildTool : Tool
{
	protected override void Awake()
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		Animator componentInChildren = ((Component)this).GetComponentInChildren<Animator>(true);
		AccessTools.Field(typeof(EquippedItem), "itemAnimator").SetValue(this, componentInChildren);
		((EquippedItem)this).handRequirement = (HandRequirement)3;
		((EquippedItem)this).Awake();
	}

	public override void OnPrimaryAction(bool down)
	{
		if (down && (Object)(object)((EquippedItem)this).Player != (Object)null && ((NetworkBehaviour)((EquippedItem)this).Player).isLocalPlayer)
		{
			RailPlugin.Instance?.PlaceSelected();
		}
	}

	public override void OnSecondaryAction(bool down)
	{
	}

	public override void OnAnimationEvent(string id)
	{
	}

	public override void StopUsing(bool changed = false)
	{
		RailPlugin.Instance?.Visuals.HidePreview();
	}

	public override void Hide()
	{
		((EquippedItem)this).Hide();
		if ((Object)(object)((EquippedItem)this).Player != (Object)null && ((NetworkBehaviour)((EquippedItem)this).Player).isLocalPlayer)
		{
			RailPlugin.Instance?.Visuals.HidePreview();
		}
	}
}
public sealed class RailHud
{
	private readonly RailPlugin plugin;

	private GUIStyle style;

	public RailHud(RailPlugin owner)
	{
		plugin = owner;
	}

	public void Draw()
	{
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Expected O, but got Unknown
		//IL_0086: Expected O, but got Unknown
		if (!plugin.Gameplay)
		{
			return;
		}
		string text = ((Time.unscaledTime < plugin.NoticeUntil) ? plugin.NoticeText : plugin.PlacementHint);
		if (!string.IsNullOrEmpty(text))
		{
			if (style == null)
			{
				style = new GUIStyle(GUI.skin.box)
				{
					fontSize = 16,
					alignment = (TextAnchor)4,
					wordWrap = true,
					padding = new RectOffset(12, 12, 8, 8)
				};
			}
			float num = Mathf.Min(640, Screen.width - 40);
			GUI.Box(new Rect(((float)Screen.width - num) / 2f, (float)Screen.height * 0.76f, num, 62f), text, style);
		}
	}
}
public sealed class RailHitTarget : MonoBehaviour, IInteractable, ICrosshairTarget, IDestructible
{
	public RailTargetKind Kind;

	public int Id;

	public void OnCrosshairEnter()
	{
		RailPlugin.Instance?.Visuals.Highlight(Id, value: true);
	}

	public void OnCrosshairExit()
	{
		RailPlugin.Instance?.Visuals.Highlight(Id, value: false);
	}

	public float GetInteractionDistance()
	{
		return 4f;
	}

	public string GetInteractionInput()
	{
		if (Kind != RailTargetKind.Cart)
		{
			return "";
		}
		return "<style=Player/Interact> ";
	}

	public string GetInteractionText()
	{
		RailState railState = RailPlugin.Instance?.ViewState;
		if (railState == null)
		{
			return "";
		}
		if (Kind == RailTargetKind.Rail)
		{
			return "Szyny górnicze — demontaż kilofem";
		}
		if (Kind == RailTargetKind.Plank)
		{
			return "Deska — rozbiórka kilofem";
		}
		RailCart railCart = railState.Cart(Id);
		if (railCart != null)
		{
			if (!railCart.Running)
			{
				return "Uruchom wagonik";
			}
			return "Zatrzymaj wagonik";
		}
		return "";
	}

	public string GetInteractionStatInfo()
	{
		RailState railState = RailPlugin.Instance?.ViewState;
		if (railState == null)
		{
			return "";
		}
		CargoStore cargoStore = null;
		float num = 1f;
		string text = "";
		if (Kind == RailTargetKind.Rail)
		{
			num = railState.Track(Id)?.Health ?? 1f;
		}
		else if (Kind == RailTargetKind.Plank)
		{
			num = railState.Plank(Id)?.Health ?? 1f;
		}
		else
		{
			RailCart railCart = railState.Cart(Id);
			if (railCart != null)
			{
				cargoStore = railCart.Cargo;
				num = railCart.Health;
				text = (railCart.Running ? "W ruchu" : railCart.StopReason);
			}
		}
		string text2 = "Wytrzymałość: " + Mathf.CeilToInt(num * 100f) + "%";
		if (cargoStore != null)
		{
			text2 = text2 + "   Ładunek: " + cargoStore.Total + "/" + cargoStore.Capacity;
			int num2 = 0;
			foreach (KeyValuePair<string, int> item in cargoStore.Items)
			{
				if (num2++ == 3)
				{
					text2 += "\n…";
					break;
				}
				text2 = text2 + "\n" + RailPlugin.Instance.Bridge.Name(item.Key) + ": " + item.Value;
			}
			text2 += "\nSurowiec w ręce + LPM: włóż | PPM: odbierz";
		}
		if (!string.IsNullOrEmpty(text))
		{
			text2 = text2 + "\n" + text;
		}
		return text2;
	}

	public void Interact(FirstPersonController player)
	{
		//IL_003a: 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)
		RailPlugin instance = RailPlugin.Instance;
		if (!((Object)(object)instance == (Object)null) && ((NetworkBehaviour)player).isLocalPlayer && instance.Gameplay && Kind == RailTargetKind.Cart)
		{
			instance.Net.Send(ActionKind.Start, Id);
		}
	}

	public void CmdTap(FirstPersonController owner, Vector3 position, Vector3 direction, float damage)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)owner == (Object)null) && ((NetworkBehaviour)owner).isLocalPlayer)
		{
			float value = owner.PlayerStats.DigStrength.Value;
			RailPlugin.Instance?.Net.Send(ActionKind.Hit, Id, null, 0, position, (value > 0f) ? (damage / value) : 1f);
		}
	}
}
public static class RailInteractions
{
	private static float nextLoad;

	private static float nextStat;

	public static void Patch(Harmony h)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Expected O, but got Unknown
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Expected O, but got Unknown
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Expected O, but got Unknown
		h.Patch((MethodBase)AccessTools.Method(typeof(PlayerInteraction), "RaycastForTarget", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailInteractions), "TargetPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(PlayerInteraction), "OnInteract", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailInteractions), "InteractPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(PlayerInteraction), "OnPrimaryAction", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailInteractions), "PrimaryPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(PlayerInteraction), "OnSecondaryAction", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailInteractions), "SecondaryPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(DiggingTool), "OnHit", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RailInteractions), "HitPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static bool TargetPrefix(PlayerInteraction __instance, ref ICrosshairTarget __result)
	{
		RailPlugin instance = RailPlugin.Instance;
		if ((Object)(object)instance == (Object)null || !instance.Gameplay || (Object)(object)__instance != (Object)(object)instance.LocalPlayer.PlayerInteraction)
		{
			return true;
		}
		RailHitTarget railHitTarget = RailTerrain.Target(instance.LocalPlayer);
		if ((Object)(object)railHitTarget == (Object)null)
		{
			return true;
		}
		__result = (ICrosshairTarget)(object)railHitTarget;
		return false;
	}

	private static bool InteractPrefix(PlayerInteraction __instance, bool _Down)
	{
		RailPlugin instance = RailPlugin.Instance;
		if ((Object)(object)instance == (Object)null || !instance.Gameplay || (Object)(object)__instance != (Object)(object)instance.LocalPlayer.PlayerInteraction)
		{
			return true;
		}
		RailHitTarget railHitTarget = RailTerrain.Target(instance.LocalPlayer);
		if ((Object)(object)railHitTarget == (Object)null)
		{
			return true;
		}
		if (!instance.LocalPlayer.PlayerEquipment.HasCarriable())
		{
			railHitTarget.Interact(instance.LocalPlayer);
		}
		return false;
	}

	private static bool PrimaryPrefix(PlayerInteraction __instance, bool _B)
	{
		RailPlugin instance = RailPlugin.Instance;
		if ((Object)(object)instance == (Object)null || !instance.Gameplay || (Object)(object)__instance != (Object)(object)instance.LocalPlayer.PlayerInteraction)
		{
			return true;
		}
		RailHitTarget railHitTarget = RailTerrain.Target(instance.LocalPlayer);
		if ((Object)(object)railHitTarget == (Object)null || railHitTarget.Kind != RailTargetKind.Cart || instance.LocalPlayer.PlayerEquipment.HasCarriable() || !instance.Bridge.IsResource(instance.SelectedItem))
		{
			return true;
		}
		if (!_B)
		{
			return true;
		}
		Load(instance, railHitTarget);
		return false;
	}

	private static bool SecondaryPrefix(PlayerInteraction __instance, bool _Obj)
	{
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		RailPlugin instance = RailPlugin.Instance;
		if ((Object)(object)instance == (Object)null || !instance.Gameplay || (Object)(object)__instance != (Object)(object)instance.LocalPlayer.PlayerInteraction)
		{
			return true;
		}
		RailHitTarget railHitTarget = RailTerrain.Target(instance.LocalPlayer);
		if ((Object)(object)railHitTarget == (Object)null || railHitTarget.Kind != RailTargetKind.Cart || instance.LocalPlayer.PlayerEquipment.HasCarriable() || instance.LocalPlayer.PlayerEquipment.CurrentEquippedItem is DiggingTool || RailCrafting.IsProduct(instance.SelectedItem))
		{
			return true;
		}
		if (_Obj)
		{
			instance.Net.Send(ActionKind.Withdraw, railHitTarget.Id, instance.Bridge.IsResource(instance.SelectedItem) ? instance.SelectedItem : null, 10000);
		}
		return false;
	}

	private static bool HitPrefix(DiggingTool __instance, float digMultiplier)
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		RailPlugin instance = RailPlugin.Instance;
		if ((Object)(object)instance == (Object)null || !instance.Gameplay || (Object)(object)((EquippedItem)__instance).Player != (Object)(object)instance.LocalPlayer)
		{
			return true;
		}
		if (!RailTerrain.Aim(instance.LocalPlayer, 3f, out var result))
		{
			return true;
		}
		RailHitTarget componentInParent = ((Component)((RaycastHit)(ref result)).collider).GetComponentInParent<RailHitTarget>();
		if ((Object)(object)componentInParent == (Object)null)
		{
			return true;
		}
		instance.Net.Send(ActionKind.Hit, componentInParent.Id, null, 0, ((RaycastHit)(ref result)).point, digMultiplier);
		return false;
	}

	private static void Load(RailPlugin p, RailHitTarget target)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		if (!(Time.unscaledTime < nextLoad))
		{
			nextLoad = Time.unscaledTime + 0.12f;
			p.Net.Send(ActionKind.Deposit, target.Id, p.SelectedItem, p.LocalPlayer.PlayerEquipment.CurrentSlot);
		}
	}

	public static void Update(RailPlugin p)
	{
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		if (!p.Gameplay || p.LocalPlayer.PlayerEquipment.HasCarriable())
		{
			return;
		}
		RailHitTarget railHitTarget = RailTerrain.Target(p.LocalPlayer);
		if ((Object)(object)railHitTarget == (Object)null)
		{
			return;
		}
		if (railHitTarget.Kind == RailTargetKind.Cart && p.Bridge.IsResource(p.SelectedItem))
		{
			PlayerActions player = InputManager.PlayerInputActions.Player;
			if (((PlayerActions)(ref player)).PrimaryAction.IsPressed())
			{
				Load(p, railHitTarget);
			}
		}
		if (Time.unscaledTime >= nextStat && (Object)(object)Hud.Instance != (Object)null)
		{
			nextStat = Time.unscaledTime + 0.2f;
			Hud.Instance.ShowInteractionStatInfoLabel(railHitTarget.GetInteractionStatInfo(), (ICrosshairTarget)(object)railHitTarget);
			Hud.Instance.ShowInteractionLabel(railHitTarget.GetInteractionText(), railHitTarget.GetInteractionInput());
		}
	}
}
public struct RailRequest : NetworkMessage
{
	public int Protocol;

	public int Sequence;

	public int Revision;

	public int Number;

	public int Amount;

	public string Session;

	public string Item;

	public ActionKind Action;

	public Vector3 Position;

	public float Yaw;
}
public struct RailSnapshot : NetworkMessage
{
	public string Session;

	public string Data;

	public int Sequence;

	public int Index;

	public int Count;
}
public struct RailMotion : NetworkMessage
{
	public string Session;

	public int Revision;

	public int CartId;

	public int RailId;

	public int Direction;

	public float Distance;

	public bool Running;
}
public struct RailNotice : NetworkMessage
{
	public string Text;
}
public sealed class RailNetwork
{
	private sealed class Peer
	{
		public NetworkConnectionToClient Connection;

		public int LastSequence;

		public float NextAction;

		public float NextHello;
	}

	private readonly Dictionary<int, Peer> peers = new Dictionary<int, Peer>();

	private readonly RailPlugin plugin;

	private bool serverRegistered;

	private bool clientRegistered;

	private float nextHello;

	private float nextSnapshot;

	private float nextMotion;

	private int sendSequence;

	private int snapshotSequence;

	private int assemblingSequence = -1;

	private int acceptedSequence = -1;

	private string assemblingSession;

	private string[] chunks;

	private float assemblyDeadline;

	public bool Connected { get; private set; }

	public int PeerCount => peers.Count;

	public RailNetwork(RailPlugin owner)
	{
		plugin = owner;
		InstallSerializers();
	}

	private static void InstallSerializers()
	{
		Writer<RailRequest>.write = delegate(NetworkWriter w, RailRequest m)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			NetworkWriterExtensions.WriteInt(w, m.Protocol);
			NetworkWriterExtensions.WriteInt(w, m.Sequence);
			NetworkWriterExtensions.WriteInt(w, m.Revision);
			w.WriteByte((byte)m.Action);
			NetworkWriterExtensions.WriteInt(w, m.Number);
			NetworkWriterExtensions.WriteInt(w, m.Amount);
			NetworkWriterExtensions.WriteString(w, m.Session);
			NetworkWriterExtensions.WriteString(w, m.Item);
			NetworkWriterExtensions.WriteVector3(w, m.Position);
			NetworkWriterExtensions.WriteFloat(w, m.Yaw);
		};
		Reader<RailRequest>.read = (NetworkReader r) => new RailRequest
		{
			Protocol = NetworkReaderExtensions.ReadInt(r),
			Sequence = NetworkReaderExtensions.ReadInt(r),
			Revision = NetworkReaderExtensions.ReadInt(r),
			Action = (ActionKind)r.ReadByte(),
			Number = NetworkReaderExtensions.ReadInt(r),
			Amount = NetworkReaderExtensions.ReadInt(r),
			Session = NetworkReaderExtensions.ReadString(r),
			Item = NetworkReaderExtensions.ReadString(r),
			Position = NetworkReaderExtensions.ReadVector3(r),
			Yaw = NetworkReaderExtensions.ReadFloat(r)
		};
		Writer<RailSnapshot>.write = delegate(NetworkWriter w, RailSnapshot m)
		{
			NetworkWriterExtensions.WriteString(w, m.Session);
			NetworkWriterExtensions.WriteInt(w, m.Sequence);
			NetworkWriterExtensions.WriteInt(w, m.Index);
			NetworkWriterExtensions.WriteInt(w, m.Count);
			NetworkWriterExtensions.WriteString(w, m.Data);
		};
		Reader<RailSnapshot>.read = (NetworkReader r) => new RailSnapshot
		{
			Session = NetworkReaderExtensions.ReadString(r),
			Sequence = NetworkReaderExtensions.ReadInt(r),
			Index = NetworkReaderExtensions.ReadInt(r),
			Count = NetworkReaderExtensions.ReadInt(r),
			Data = NetworkReaderExtensions.ReadString(r)
		};
		Writer<RailMotion>.write = delegate(NetworkWriter w, RailMotion m)
		{
			NetworkWriterExtensions.WriteString(w, m.Session);
			NetworkWriterExtensions.WriteInt(w, m.Revision);
			NetworkWriterExtensions.WriteInt(w, m.CartId);
			NetworkWriterExtensions.WriteInt(w, m.RailId);
			NetworkWriterExtensions.WriteInt(w, m.Direction);
			NetworkWriterExtensions.WriteFloat(w, m.Distance);
			NetworkWriterExtensions.WriteBool(w, m.Running);
		};
		Reader<RailMotion>.read = (NetworkReader r) => new RailMotion
		{
			Session = NetworkReaderExtensions.ReadString(r),
			Revision = NetworkReaderExtensions.ReadInt(r),
			CartId = NetworkReaderExtensions.ReadInt(r),
			RailId = NetworkReaderExtensions.ReadInt(r),
			Direction = NetworkReaderExtensions.ReadInt(r),
			Distance = NetworkReaderExtensions.ReadFloat(r),
			Running = NetworkReaderExtensions.ReadBool(r)
		};
		Writer<RailNotice>.write = delegate(NetworkWriter w, RailNotice m)
		{
			NetworkWriterExtensions.WriteString(w, m.Text);
		};
		Reader<RailNotice>.read = (NetworkReader r) => new RailNotice
		{
			Text = NetworkReaderExtensions.ReadString(r)
		};
	}

	public void Update()
	{
		if (!NetworkServer.active && serverRegistered)
		{
			serverRegistered = false;
			peers.Clear();
		}
		if (NetworkServer.active && !serverRegistered)
		{
			NetworkServer.RegisterHandler<RailRequest>((Action<NetworkConnectionToClient, RailRequest>)OnRequest, true);
			serverRegistered = true;
		}
		if (!NetworkClient.active && clientRegistered)
		{
			clientRegistered = false;
			ResetClient();
		}
		if (NetworkClient.active && !clientRegistered)
		{
			NetworkClient.RegisterHandler<RailSnapshot>((Action<RailSnapshot>)OnSnapshot, true);
			NetworkClient.RegisterHandler<RailMotion>((Action<RailMotion>)OnMotion, true);
			NetworkClient.RegisterHandler<RailNotice>((Action<RailNotice>)delegate(RailNotice m)
			{
				plugin.Notify(m.Text);
			}, true);
			clientRegistered = true;
			nextHello = Time.unscaledTime + 1f;
		}
		if (NetworkClient.isConnected && NetworkClient.ready && plugin.InLevel && !NetworkServer.active && Time.unscaledTime >= nextHello)
		{
			nextHello = Time.unscaledTime + (float)(Connected ? 10 : 3);
			NetworkClient.Send<RailRequest>(new RailRequest
			{
				Protocol = 5,
				Action = ActionKind.Hello
			}, 0);
		}
		if (NetworkServer.active && plugin.ServerState != null)
		{
			if (Time.unscaledTime >= nextSnapshot)
			{
				BroadcastSnapshot();
				nextSnapshot = Time.unscaledTime + 10f;
			}
			if (Time.unscaledTime >= nextMotion)
			{
				BroadcastMotion();
				nextMotion = Time.unscaledTime + 0.1f;
			}
		}
		if (chunks != null && Time.unscaledTime > assemblyDeadline)
		{
			chunks = null;
		}
	}

	public void ResetClient()
	{
		Connected = false;
		chunks = null;
		acceptedSequence = -1;
		assemblingSequence = -1;
		assemblingSession = null;
		nextHello = Time.unscaledTime + 1f;
	}

	public void ResetServer()
	{
		peers.Clear();
		nextSnapshot = 0f;
		nextMotion = 0f;
	}

	public void Send(ActionKind action, int number = 0, string item = null, int amount = 0, Vector3 position = default(Vector3), float yaw = 0f)
	{
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		RailState viewState = plugin.ViewState;
		if (viewState == null)
		{
			plugin.Notify("Brak połączenia z kolejką hosta. Wszyscy gracze muszą mieć tę samą wersję moda.");
			return;
		}
		RailRequest railRequest = new RailRequest
		{
			Protocol = 5,
			Sequence = ++sendSequence,
			Revision = viewState.Revision,
			Session = viewState.Session,
			Action = action,
			Number = number,
			Item = item,
			Amount = amount,
			Position = position,
			Yaw = yaw
		};
		if (NetworkServer.active)
		{
			if ((Object)(object)plugin.LocalPlayer != (Object)null)
			{
				plugin.HandleRequest(plugin.LocalPlayer, railRequest, plugin.Notify);
			}
		}
		else if (Connected && NetworkClient.ready)
		{
			NetworkClient.Send<RailRequest>(railRequest, 0);
		}
	}

	private void OnRequest(NetworkConnectionToClient connection, RailRequest m)
	{
		if (connection == null || !((NetworkConnection)connection).isAuthenticated || !((NetworkConnection)connection).isReady)
		{
			return;
		}
		Peer value;
		if (m.Protocol != 5)
		{
			Notice(connection, "Niezgodna wersja RCT Kolejka. Zainstaluj taką samą paczkę jak host.");
		}
		else if (m.Action == ActionKind.Hello)
		{
			if (!peers.TryGetValue(connection.connectionId, out value) || value.Connection != connection || !(Time.unscaledTime < value.NextHello))
			{
				if (value == null || value.Connection != connection)
				{
					Dictionary<int, Peer> dictionary = peers;
					int connectionId = connection.connectionId;
					Peer obj = new Peer
					{
						Connection = connection
					};
					value = obj;
					dictionary[connectionId] = obj;
				}
				value.NextHello = Time.unscaledTime + 2f;
				if (plugin.ServerState != null)
				{
					SendSnapshot(connection, ++snapshotSequence);
				}
			}
		}
		else
		{
			if (!peers.TryGetValue(connection.connectionId, out value) || value.Connection != connection || m.Sequence <= value.LastSequence)
			{
				return;
			}
			value.LastSequence = m.Sequence;
			if (Time.unscaledTime < value.NextAction)
			{
				return;
			}
			value.NextAction = Time.unscaledTime + 0.08f;
			if ((Object)(object)((NetworkConnection)connection).identity == (Object)null || plugin.ServerState == null || m.Session != plugin.ServerState.Session)
			{
				return;
			}
			FirstPersonController component = ((Component)((NetworkConnection)connection).identity).GetComponent<FirstPersonController>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			try
			{
				plugin.HandleRequest(component, m, delegate(string text)
				{
					Notice(connection, text);
				});
			}
			catch (Exception e)
			{
				plugin.LogError("Żądanie kolejki", e);
				Notice(connection, "Operacja przerwana. Sprawdź BepInEx/LogOutput.log.");
			}
		}
	}

	private static void Notice(NetworkConnectionToClient connection, string text)
	{
		if (connection != null && ((NetworkConnection)connection).isReady)
		{
			((NetworkConnection)connection).Send<RailNotice>(new RailNotice
			{
				Text = text
			}, 0);
		}
	}

	private IEnumerable<NetworkConnectionToClient> RemotePeers()
	{
		foreach (Peer item in new List<Peer>(peers.Values))
		{
			if (NetworkServer.connections.TryGetValue(item.Connection.connectionId, out var value) && value == item.Connection && ((NetworkConnection)value).isReady && (object)value != NetworkServer.localConnection)
			{
				yield return value;
			}
			else if (!NetworkServer.connections.ContainsKey(item.Connection.connectionId))
			{
				peers.Remove(item.Connection.connectionId);
			}
		}
	}

	public void BroadcastSnapshot()
	{
		if (plugin.ServerState == null)
		{
			return;
		}
		int sequence = ++snapshotSequence;
		string json = Encode(plugin.ServerState);
		foreach (NetworkConnectionToClient item in RemotePeers())
		{
			SendSnapshot(item, sequence, json);
		}
	}

	private void SendSnapshot(NetworkConnectionToClient connection, int sequence, string json = null)
	{
		RailState serverState = plugin.ServerState;
		if (serverState == null)
		{
			return;
		}
		json = json ?? Encode(serverState);
		int num = (json.Length + 2048 - 1) / 2048;
		if (num > 512)
		{
			plugin.Notify("Stan kolejki przekroczył limit synchronizacji.");
			return;
		}
		for (int i = 0; i < num; i++)
		{
			((NetworkConnection)connection).Send<RailSnapshot>(new RailSnapshot
			{
				Session = serverState.Session,
				Sequence = sequence,
				Index = i,
				Count = num,
				Data = json.Substring(i * 2048, Math.Min(2048, json.Length - i * 2048))
			}, 0);
		}
	}

	private void BroadcastMotion()
	{
		RailState serverState = plugin.ServerState;
		foreach (RailCart cart in serverState.Carts)
		{
			RailMotion railMotion = new RailMotion
			{
				Session = serverState.Session,
				Revision = serverState.Revision,
				CartId = cart.Id,
				RailId = cart.Rail,
				Direction = cart.Direction,
				Distance = cart.Distance,
				Running = cart.Running
			};
			foreach (NetworkConnectionToClient item in RemotePeers())
			{
				((NetworkConnection)item).Send<RailMotion>(railMotion, 0);
			}
		}
	}

	private void OnSnapshot(RailSnapshot m)
	{
		if (NetworkServer.active || !plugin.InLevel || string.IsNullOrEmpty(m.Session) || m.Session.Length != 32 || m.Count < 1 || m.Count > 512 || m.Index < 0 || m.Index >= m.Count || m.Data == null || m.Data.Length > 2048 || (plugin.ClientState != null && plugin.ClientState.Session == m.Session && m.Sequence <= acceptedSequence))
		{
			return;
		}
		if (chunks == null || assemblingSession != m.Session || assemblingSequence != m.Sequence)
		{
			if (assemblingSession == m.Session && m.Sequence < assemblingSequence)
			{
				return;
			}
			chunks = new string[m.Count];
			assemblingSession = m.Session;
			assemblingSequence = m.Sequence;
			assemblyDeadline = Time.unscaledTime + 5f;
		}
		if (chunks.Length != m.Count)
		{
			return;
		}
		chunks[m.Index] = m.Data;
		for (int i = 0; i < chunks.Length; i++)
		{
			if (chunks[i] == null)
			{
				return;
			}
		}
		string data = string.Concat(chunks);
		chunks = null;
		try
		{
			RailState railState = Decode(data);
			if (Valid(railState) && !(railState.Session != m.Session) && !(railState.World != plugin.WorldKey))
			{
				acceptedSequence = m.Sequence;
				Connected = true;
				plugin.ReceiveSnapshot(railState);
			}
		}
		catch (Exception e)
		{
			plugin.LogError("Odbiór stanu kolejki", e);
		}
	}

	public static string Encode(RailState s)
	{
		byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject((object)s));
		using MemoryStream memoryStream = new MemoryStream();
		using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionLevel.Fastest, leaveOpen: true))
		{
			gZipStream.Write(bytes, 0, bytes.Length);
		}
		return Convert.ToBase64String(memoryStream.ToArray());
	}

	public static RailState Decode(string data)
	{
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Expected O, but got Unknown
		if (data == null || data.Length > 1048576)
		{
			throw new InvalidDataException("Snapshot size");
		}
		using MemoryStream stream = new MemoryStream(Convert.FromBase64String(data));
		using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress);
		using MemoryStream memoryStream = new MemoryStream();
		byte[] array = new byte[8192];
		int num;
		while ((num = gZipStream.Read(array, 0, array.Length)) > 0)
		{
			if (memoryStream.Length + num > 1048576)
			{
				throw new InvalidDataException("Inflated snapshot size");
			}
			memoryStream.Write(array, 0, num);
		}
		RailState railState = JsonConvert.DeserializeObject<RailState>(Encoding.UTF8.GetString(memoryStream.ToArray()), new JsonSerializerSettings
		{
			MaxDepth = 16,
			TypeNameHandling = (TypeNameHandling)0
		});
		railState?.Normalize();
		return railState;
	}

	private static bool Valid(RailState s)
	{
		return s?.Valid() ?? false;
	}

	private void OnMotion(RailMotion m)
	{
		RailState clientState = plugin.ClientState;
		if (!NetworkServer.active && clientState != null && !(m.Session != clientState.Session) && m.Revision == clientState.Revision && Scalar.Finite(m.Distance) && !(m.Distance < 0f) && (m.Direction == 1 || m.Direction == -1))
		{
			RailCart railCart = clientState.Cart(m.CartId);
			RailSegment railSegment = clientState.Track(m.RailId);
			if (railCart != null && railSegment != null && !(m.Distance > railSegment.Length + 0.001f))
			{
				railCart.Rail = m.RailId;
				railCart.Distance = m.Distance;
				railCart.Direction = m.Direction;
				railCart.Running = m.Running;
			}
		}
	}

	public void Dispose()
	{
		if (serverRegistered)
		{
			NetworkServer.UnregisterHandler<RailRequest>();
		}
		if (clientRegistered)
		{
			NetworkClient.UnregisterHandler<RailSnapshot>();
			NetworkClient.UnregisterHandler<RailMotion>();
			NetworkClient.UnregisterHandler<RailNotice>();
		}
		peers.Clear();
	}
}
public sealed class RailPlan
{
	public string Item;

	public string Reason = "";

	public bool Valid;

	public Vector3 Position;

	public float Yaw;

	public float Distance;

	public int Track;

	public int Direction = 1;

	public RailSegment Segment;

	public RailPlank Plank;
}
public static class RailTerrain
{
	private static bool Ignore(Collider c)
	{
		if (!((Object)(object)c == (Object)null) && !c.isTrigger && ((Component)c).gameObject.layer != 2 && !((Object)(object)((Component)c).GetComponentInParent<FirstPersonController>() != (Object)null) && !((Object)(object)((Component)c).GetComponentInParent<PickableItem>() != (Object)null))
		{
			return (Object)(object)((Component)c).GetComponentInParent<EquippedItem>() != (Object)null;
		}
		return true;
	}

	private static bool IgnoreSurface(Collider c)
	{
		if (Ignore(c))
		{
			return true;
		}
		RailHitTarget componentInParent = ((Component)c).GetComponentInParent<RailHitTarget>();
		if ((Object)(object)componentInParent != (Object)null)
		{
			return componentInParent.Kind != RailTargetKind.Plank;
		}
		return false;
	}

	private static RaycastHit[] Hits(Vector3 from, Vector3 direction, float range)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		RaycastHit[] array = Physics.RaycastAll(from, direction, range, -5, (QueryTriggerInteraction)1);
		Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
		return array;
	}

	public static bool Aim(FirstPersonController player, float range, out RaycastHit result)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: 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)
		result = default(RaycastHit);
		if ((Object)(object)player == (Object)null || (Object)(object)player.fpsCameraTarget == (Object)null)
		{
			return false;
		}
		RaycastHit[] array = Hits(player.fpsCameraTarget.position, player.fpsCameraTarget.forward, range);
		for (int i = 0; i < array.Length; i++)
		{
			RaycastHit val = array[i];
			if (!Ignore(((RaycastHit)(ref val)).collider))
			{
				result = val;
				return true;
			}
		}
		return false;
	}

	public static RailHitTarget Target(FirstPersonController player, float range = 4f)
	{
		if (!Aim(player, range, out var result))
		{
			return null;
		}
		return ((Component)((RaycastHit)(ref result)).collider).GetComponentInParent<RailHitTarget>();
	}

	public static bool Reach(FirstPersonController player, Vector3 point, float range)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: 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)
		//IL_0028: 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)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)player == (Object)null || !Convert3.Core(point).Finite)
		{
			return false;
		}
		Vector3 position = player.fpsCameraTarget.position;
		Vector3 val = point - position;
		if (((Vector3)(ref val)).magnitude > range)
		{
			return false;
		}
		RaycastHit[] array = Hits(position, ((Vector3)(ref val)).normalized, Mathf.Max(0f, ((Vector3)(ref val)).magnitude - 0.15f));
		for (int i = 0; i < array.Length; i++)
		{
			RaycastHit val2 = array[i];
			if (!Ignore(((RaycastHit)(ref val2)).collider) && (Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<RailHitTarget>() == (Object)null)
			{
				return false;
			}
		}
		return true;
	}

	private static bool Floor(Vector3 near, float up, float down, out Vector3 point)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: 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_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		point = near;
		bool result = false;
		float num = float.MaxValue;
		RaycastHit[] array = Hits(near + Vector3.up * up, Vector3.down, up + down);
		for (int i = 0; i < array.Length; i++)
		{
			RaycastHit val = array[i];
			if (!IgnoreSurface(((RaycastHit)(ref val)).collider) && !(((RaycastHit)(ref val)).normal.y < 0.5f))
			{
				Vector3 val2 = ((RaycastHit)(ref val)).point + Vector3.up * 0.09f;
				float num2 = Mathf.Abs(val2.y - near.y);
				if (num2 < num)
				{
					point = val2;
					num = num2;
					result = true;
				}
			}
		}
		return result;
	}

	private static bool GroundProbe(V3 near, float up, float down, out V3 railBed)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		Vector3 point;
		bool result = Floor(Convert3.Unity(near), up, down, out point);
		railBed = Convert3.Core(point);
		return result;
	}

	public static bool Clearance(Vector3 point, Vector3 tangent)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		if (((Vector3)(ref tangent)).sqrMagnitude < 0.001f)
		{
			tangent = Vector3.forward;
		}
		Quaternion val = Quaternion.LookRotation(tangent, Vector3.up);
		Collider[] array = Physics.OverlapBox(point + val * Vector3.up * 0.92f, new Vector3(0.53f, 0.68f, 0.13f), val, -5, (QueryTriggerInteraction)1);
		foreach (Collider val2 in array)
		{
			if (!Ignore(val2) && (Object)(object)((Component)val2).GetComponentInParent<RailHitTarget>() == (Object)null)
			{
				return false;
			}
		}
		return true;
	}

	public static bool Supported(Vector3 point)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		if (Floor(point, 0.7f, 0.8f, out var point2))
		{
			return Mathf.Abs(point.y - point2.y) < 0.5f;
		}
		return false;
	}

	public static RailPlan Plan(RailState state, string item, Vector3 aimed, float yaw)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0204: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: 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_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_037a: Unknown result type (might be due to invalid IL or missing references)
		//IL_037b: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0411: Unknown result type (might be due to invalid IL or missing references)
		//IL_038d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0392: Unknown result type (might be due to invalid IL or missing references)
		//IL_039c: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03be: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0402: Unknown result type (might be due to invalid IL or missing references)
		//IL_0407: Unknown result type (might be due to invalid IL or missing references)
		//IL_0408: Unknown result type (might be due to invalid IL or missing references)
		//IL_040d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0432: Unknown result type (might be due to invalid IL or missing references)
		//IL_0433: Unknown result type (might be due to invalid IL or missing references)
		//IL_0434: Unknown result type (might be due to invalid IL or missing references)
		//IL_0436: Unknown result type (might be due to invalid IL or missing references)
		//IL_043b: Unknown result type (might be due to invalid IL or missing references)
		//IL_043f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0449: Unknown result type (might be due to invalid IL or missing references)
		//IL_044e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0453: Unknown result type (might be due to invalid IL or missing references)
		//IL_0455: Unknown result type (might be due to invalid IL or missing references)
		//IL_045b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0461: Unknown result type (might be due to invalid IL or missing references)
		//IL_0468: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_058d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0592: Unknown result type (might be due to invalid IL or missing references)
		//IL_0500: Unknown result type (might be due to invalid IL or missing references)
		//IL_0505: Unknown result type (might be due to invalid IL or missing references)
		//IL_0510: Unknown result type (might be due to invalid IL or missing references)
		//IL_0515: Unknown result type (might be due to invalid IL or missing references)
		//IL_051a: Unknown result type (might be due to invalid IL or missing references)
		//IL_051c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0522: Unknown result type (might be due to invalid IL or missing references)
		//IL_0528: Unknown result type (might be due to invalid IL or missing references)
		//IL_052f: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_05ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_05f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_05fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_05ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0609: Unknown result type (might be due to invalid IL or missing references)
		//IL_060e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0637: Unknown result type (might be due to invalid IL or missing references)
		//IL_0639: Unknown result type (might be due to invalid IL or missing references)
		//IL_063d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0642: Unknown result type (might be due to invalid IL or missing references)
		//IL_065a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0661: Unknown result type (might be due to invalid IL or missing references)
		//IL_069a: Unknown result type (might be due to invalid IL or missing references)
		//IL_069c: Unknown result type (might be due to invalid IL or missing references)
		//IL_06d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_06d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_06e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_06e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_06ff: Unknown result type (might be due to invalid IL or missing references)
		RailPlan railPlan = new RailPlan
		{
			Item = item,
			Position = aimed,
			Yaw = yaw
		};
		if (state == null || !RailCrafting.IsProduct(item) || !Convert3.Core(aimed).Finite || !Scalar.Finite(yaw))
		{
			railPlan.Reason = "Brak gotowego świata";
			return railPlan;
		}
		if (item == "STONERAIL_CART")
		{
			RailSegment railSegment = null;
			float num = 0.8f;
			float distance = 0f;
			foreach (RailSegment rail in state.Rails)
			{
				float distance2;
				float num2 = rail.Nearest(Convert3.Core(aimed), out distance2);
				if (num2 < num)
				{
					num = num2;
					railSegment = rail;
					distance = distance2;
				}
			}
			if (railSegment == null)
			{
				railPlan.Reason = "Wagonik można postawić tylko na szynach";
				return railPlan;
			}
			railPlan.Track = railSegment.Id;
			railPlan.Distance = distance;
			railPlan.Position = Convert3.Unity(railSegment.Sample(distance, out var tangent));
			Vector3 val = Quaternion.Euler(0f, yaw, 0f) * Vector3.forward;
			railPlan.Direction = ((Vector3.Dot(val, Convert3.Unity(tangent)) >= 0f) ? 1 : (-1));
			foreach (RailCart cart in state.Carts)
			{
				if (V3.Distance(state.CartPosition(cart), Convert3.Core(railPlan.Position)) < 2f)
				{
					railPlan.Reason = "Za blisko innego wagonika";
					return railPlan;
				}
			}
			if (!Clearance(railPlan.Position, Convert3.Unity(tangent)) || !Supported(railPlan.Position))
			{
				railPlan.Reason = "Brak miejsca lub podparcia";
				return railPlan;
			}
			railPlan.Valid = state.Carts.Count < 16;
			if (!railPlan.Valid)
			{
				railPlan.Reason = "Limit 16 wagoników";
			}
			return railPlan;
		}
		if (item == "STONERAIL_PLANK")
		{
			if (!RailPlankRules.TryPlan(state, Convert3.Core(aimed), yaw, out var plank, out var snapped))
			{
				railPlan.Reason = ((state.Planks.Count >= 128) ? "Limit 128 desek" : "W tym miejscu już jest deska");
				return railPlan;
			}
			railPlan.Plank = plank;
			railPlan.Position = Convert3.Unity(plank.Position);
			railPlan.Yaw = plank.Yaw;
			if (!snapped && (!Floor(railPlan.Position, 1.2f, 1.4f, out var point) || Mathf.Abs(point.y - plank.Position.Y) > 0.8f))
			{
				railPlan.Reason = "Postaw deskę na podłożu";
				return railPlan;
			}
			railPlan.Valid = true;
			return railPlan;
		}
		if (state.Rails.Count >= 256)
		{
			railPlan.Reason = "Limit 256 odcinków toru";
			return railPlan;
		}
		Vector3 point2 = aimed;
		Vector3 val2 = Quaternion.Euler(0f, yaw, 0f) * Vector3.forward;
		float startingGrade = 0f;
		RailSegment railSegment2 = null;
		int side = 0;
		float num3 = 1f;
		foreach (RailSegment rail2 in state.Rails)
		{
			for (int i = 0; i < 2; i++)
			{
				float num4 = V3.Distance(rail2.End(i), Convert3.Core(aimed));
				if (num4 < num3 && RailGraph.IsOpen(state, rail2, i))
				{
					num3 = num4;
					railSegment2 = rail2;
					side = i;
				}
			}
		}
		Vector3 val3 = val2;
		if (railSegment2 != null)
		{
			point2 = Convert3.Unity(railSegment2.End(side));
			val2 = Convert3.Unity(railSegment2.Outward(side));
			float y = val2.y;
			Vector2 val4 = new Vector2(val2.x, val2.z);
			startingGrade = y / Mathf.Max(0.001f, ((Vector2)(ref val4)).magnitude);
			val2.y = 0f;
			((Vector3)(ref val2)).Normalize();
			val3 = Quaternion.AngleAxis(Mathf.Clamp(Vector3.SignedAngle(val2, val3, Vector3.up), -35f, 35f), Vector3.up) * val2;
		}
		else if (!Floor(point2, 1.8f, 2f, out point2))
		{
			railPlan.Reason = "Brak podłoża pod szynami";
			return railPlan;
		}
		Vector3 val5 = point2;
		Vector3 val6 = val2 + val3;
		Vector3 val7 = val5 + ((Vector3)(ref val6)).normalized * 2f;
		V3[] horizontal = RailTerrainProfile.Curve(Convert3.Core(point2), Convert3.Core(val2), Convert3.Core(val7), Convert3.Core(val3));
		V3? pinnedStart = railSegment2?.End(side);
		if (!RailTerrainProfile.Fit(horizontal, GroundProbe, pinnedStart, null, startingGrade, out var points, out var reason))
		{
			railPlan.Reason = reason;
			return railPlan;
		}
		int side2;
		RailSegment railSegment3 = RailGraph.ClosestOpenEnd(state, points[^1], Convert3.Core(val3), 0.35f, railSegment2?.Id ?? 0, out side2);
		if (railSegment3 != null)
		{
			val7 = Convert3.Unity(railSegment3.End(side2));
			val3 = -Convert3.Unity(railSegment3.Outward(side2));
			if (!RailTerrainProfile.Fit(RailTerrainProfile.Curve(Convert3.Core(point2), Convert3.Core(val2), Convert3.Core(val7), Convert3.Core(val3)), GroundProbe, pinnedStart, railSegment3.End(side2), startingGrade, out points, out reason))
			{
				railPlan.Reason = reason;
				return railPlan;
			}
		}
		RailSegment segment = new RailSegment
		{
			Points = points
		};
		railPlan.Segment = segment;
		railPlan.Position = Convert3.Unity(points[0]);
		for (int j = 0; j < points.Length; j++)
		{
			Vector3 val8 = Convert3.Unity(points[j]);
			Vector3 tangent2 = Convert3.Unity((j == 0) ? (points[1] - points[0]) : (points[j] - points[j - 1]));
			val6 = Vector3.Cross(Vector3.up, ((Vector3)(ref tangent2)).normalized);
			Vector3 val9 = ((Vector3)(ref val6)).normalized * 0.44f;
			int num5 = 0;
			float[] array = new float[2] { -1f, 1f };
			foreach (float num6 in array)
			{
				if (Floor(val8 + val9 * num6, 0.8f, 1f, out var point3) && Mathf.Abs(point3.y - val8.y) <= 0.9f)
				{
					num5++;
				}
			}
			if (num5 == 0)
			{
				railPlan.Reason = "Podłoże jest za wąskie na szyny";
				return railPlan;
			}
			if (!Clearance(val8, tangent2))
			{
				railPlan.Reason = "Przeszkoda na trasie wagonika";
				return railPlan;
			}
			foreach (RailSegment rail3 in state.Rails)
			{
				if ((rail3 != railSegment2 || !(Vector3.Distance(val8, point2) < 1.2f)) && (rail3 != railSegment3 || !(Vector3.Distance(val8, val7) < 1.2f)) && rail3.Nearest(Convert3.Core(val8), out var _) < 1.12f)
				{
					railPlan.Reason = "Szyny przecinają istniejący tor";
					return railPlan;
				}
			}
		}
		railPlan.Valid = true;
		return railPlan;
	}
}
[BepInPlugin("pl.rct.stonewards.stonerail", "RCT Kolejka", "1.0.7")]
public sealed class RailPlugin : BaseUnityPlugin
{
	private sealed class Recovery
	{
		public FirstPersonController Player;

		public string Item;

		public int Count;

		public Vector3 Position;
	}

	public const string Id = "pl.rct.stonewards.stonerail";

	public const string Version = "1.0.7";

	private RailHud hud;

	public string PlacementHint = "";

	private ConfigEntry<float> speed;

	private ConfigEntry<int> capacity;

	private ConfigEntry<ETerrainMaterialType> hardnessTerrain;

	private int sceneToken = -1;

	private float nextEnsure;

	private float nextLog;

	private float nextObstacle;

	private readonly Dictionary<ulong, float> nextHit = new Dictionary<ulong, float>();

	private readonly Dictionary<ulong, float> nextOperation = new Dictionary<ulong, float>();

	private Harmony harmony;

	private readonly List<Recovery> recoveries = new List<Recovery>();

	private float nextRecovery;

	public static RailPlugin Instance { get; private set; }

	public RailState ServerState { get; private set; }

	public RailState ClientState { get; private set; }

	public RailState ViewState
	{
		get
		{
			if (!NetworkServer.active)
			{
				return ClientState;
			}
			return ServerState;
		}
	}

	public RailNetwork Net { get; private set; }

	public GameBridge Bridge { get; private set; }

	public RailVisuals Visuals { get; private set; }

	public FirstPersonController LocalPlayer
	{
		get
		{
			if (!((Object)(object)GameManager.Instance == (Object)null))
			{
				return GameManager.Instance.LocalPlayer;
			}
			return null;
		}
	}

	public bool InLevel
	{
		get
		{
			if ((Object)(object)GameManager.Instance != (Object)null && GameManager.Instance.IsInitialized)
			{
				if (!NetworkServer.active)
				{
					return NetworkClient.isConnected;
				}
				return true;
			}
			return false;
		}
	}

	public bool Gameplay
	{
		get
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Invalid comparison between Unknown and I4
			if (InLevel && (Object)(object)LocalPlayer != (Object)null && (Object)(object)LocalPlayer.PlayerStats != (Object)null && !LocalPlayer.PlayerStats.isDead && LocalPlayer.IsAvailable && (Object)(object)InputManager.Instance != (Object)null)
			{
				return (int)InputManager.Instance.CurrentInputState == 2;
			}
			return false;
		}
	}

	public string WorldKey
	{
		get
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			return ((Scene)(ref activeScene)).name + "|" + (((Object)(object)DifficultyManager.Instance == (Object)null) ? "" : DifficultyManager.Instance.MapID);
		}
	}

	public string SelectedItem
	{
		get
		{
			FirstPersonController localPlayer = LocalPlayer;
			if (localPlayer == null)
			{
				return null;
			}
			PlayerEquipment playerEquipment = localPlayer.PlayerEquipment;
			if (playerEquipment == null)
			{
				return null;
			}
			return playerEquipment.GetCurrentEquippedItemID();
		}
	}

	public string NoticeText { get; private set; } = "";

	public float NoticeUntil { get; private set; }

	private void Awake()
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Expected O, but got Unknown
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Expected O, but got Unknown
		Instance = this;
		speed = ((BaseUnityPlugin)this).Config.Bind<float>("Transport", "Predkosc", 3f, new ConfigDescription("Metry na sekundę; ustawienie hosta.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 6f), Array.Empty<object>()));
		capacity = ((BaseUnityPlugin)this).Config.Bind<int>("Transport", "PojemnoscWagonika", 120, new ConfigDescription("Ustawienie hosta.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 1000), Array.Empty<object>()));
		hardnessTerrain = ((BaseUnityPlugin)this).Config.Bind<ETerrainMaterialType>("Wytrzymalosc", "TypPodloza", (ETerrainMaterialType)11, "Typ podłoża, którego twardość odczytujemy z tabeli aktualnego kilofa. Domyślnie ROCK_4. BEDROCK jest niedozwolony.");
		Visuals = new RailVisuals(this);
		Bridge = new GameBridge(this);
		Net = new RailNetwork(this);
		hud = new RailHud(this);
		harmony = new Harmony("pl.rct.stonewards.stonerail");
		RailCrafting.Patch(harmony);
		RailInteractions.Patch(harmony);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"RCT Kolejka 1.0.7: crafting, pasek ekwipunku, budowa LPM, interakcja E. Bez klawiszy funkcyjnych.");
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Assembly-CSharp MVID=" + typeof(FirstPersonController).Assembly.ManifestModule.ModuleVersionId));
	}

	private void Update()
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (Time.unscaledTime >= nextEnsure)
			{
				nextEnsure = Time.unscaledTime + 2f;
				RailCrafting.Ensure();
			}
			if (!InLevel)
			{
				if (sceneToken != -1)
				{
					ClearSession();
				}
				Net.Update();
				return;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
			if (sceneToken != num)
			{
				ClearSession();
				sceneToken = num;
				if (NetworkServer.active)
				{
					ServerState = new RailState
					{
						Session = Guid.NewGuid().ToString("N"),
						World = WorldKey,
						Speed = speed.Value,
						CartCapacity = capacity.Value
					};
				}
			}
			Net.Update();
			Bridge.RefreshResources();
			if (NetworkServer.active && ServerState != null)
			{
				Simulate();
				FlushRecoveries();
			}
			Visuals.Update();
			RailInteractions.Update(this);
		}
		catch (Exception e)
		{
			if (Time.unscaledTime >= nextLog)
			{
				nextLog = Time.unscaledTime + 5f;
				LogError("Aktualizacja kolejki", e);
			}
		}
	}

	private void Simulate()
	{
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		RailState s = ServerState;
		bool flag = false;
		bool flag2 = Time.unscaledTime >= nextObstacle;
		if (flag2)
		{
			nextObstacle = Time.unscaledTime + 0.12f;
		}
		foreach (RailCart cart in s.Carts)
		{
			if (!cart.Running)
			{
				continue;
			}
			if (flag2)
			{
				RailCart railCart = new RailCart
				{
					Rail = cart.Rail,
					Distance = cart.Distance,
					Direction = cart.Direction,
					Running = true
				};
				for (int i = 0; i < 5; i++)
				{
					RailSegment railSegment = s.Track(railCart.Rail);
					V3 tangent;
					Vector3 point = Convert3.Unity(railSegment.Sample(railCart.Distance, out tangent));
					if (!RailTerrain.Supported(point) || !RailTerrain.Clearance(point, Convert3.Unity(tangent)))
					{
						cart.Running = false;
						cart.StopReason = "Przeszkoda lub brak podparcia";
						flag = true;
						break;
					}
					if (s.Carts.Any((RailCart other) => other.Id != cart.Id && V3.Distance(s.CartPosition(other), Convert3.Core(point)) < 1.6f))
					{
						cart.Running = false;
						cart.StopReason = "Wagonik na trasie";
						flag = true;
						break;
					}
					RailGraph.Tick(s, railCart, 0.28f / s.Speed);
				}
			}
			bool running = cart.Running;
			RailGraph.Tick(s, cart, Time.deltaTime);
			if (running != cart.Running)
			{
				flag = true;
			}
		}
		if (flag)
		{
			Changed(geometry: false);
		}
	}

	public void PlaceSelected()
	{
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		if (!Gameplay || !RailCrafting.IsProduct(SelectedItem) || LocalPlayer.PlayerEquipment.HasCarriable())
		{