Decompiled source of MassFixStructure v1.0.1

MassFixStructure.dll

Decompiled 14 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using MassFixStructure.Configuration;
using MassFixStructure.Core;
using MassFixStructure.Network;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MassFixStructure")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+e5396deb4fd29a787980f4c3ac2aa783ed47b76d")]
[assembly: AssemblyProduct("MassFixStructure")]
[assembly: AssemblyTitle("MassFixStructure")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/UncleBugDev/MassFixStructure")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MassFixStructure
{
	[BepInPlugin("com.unclebug.massfixstructure", "MassFixStructure", "1.0.1")]
	public class MassFixStructurePlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.unclebug.massfixstructure";

		public const string PluginName = "MassFixStructure";

		public const string PluginVersion = "1.0.1";

		private Harmony? _harmony;

		public static MassFixStructurePlugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Initialize(((BaseUnityPlugin)this).Config);
			((Component)this).gameObject.AddComponent<MassRepairRunner>();
			try
			{
				_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.unclebug.massfixstructure");
				Log.LogInfo((object)"MassFixStructure v1.0.1 successfully initialized and patched.");
				Log.LogInfo((object)"Special thanks to streamer DaymonMontage! Twitch: https://www.twitch.tv/daymonmontage | Hub: https://daymonmontage.github.io/daymon-site/");
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("Failed to patch {0}: {1}", "MassFixStructure", arg));
			}
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Log.LogInfo((object)"MassFixStructure unpatched and unloaded.");
		}
	}
}
namespace MassFixStructure.Patches
{
	[HarmonyPatch(typeof(Player), "Repair")]
	public static class PlayerRepairPatch
	{
		private static readonly Func<Player, Piece, bool>? s_checkCanRemovePieceDelegate;

		static PlayerRepairPatch()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Player), "CheckCanRemovePiece", new Type[1] { typeof(Piece) }, (Type[])null);
				if (methodInfo != null)
				{
					s_checkCanRemovePieceDelegate = AccessTools.MethodDelegate<Func<Player, Piece, bool>>(methodInfo, (object)null, true);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not bind CheckCanRemovePiece delegate: " + ex.Message));
				}
			}
		}

		[HarmonyPrefix]
		public static bool Prefix(Player __instance, ItemData toolItem, Piece repairPiece)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated())
			{
				return true;
			}
			if (!ModConfig.ModEnabled.Value)
			{
				return true;
			}
			if (!((Character)__instance).InPlaceMode())
			{
				return true;
			}
			if (ModConfig.Activation.Value == ActivationMode.HoldModifierKey && !Input.GetKey(ModConfig.ModifierKey.Value))
			{
				return true;
			}
			Piece hoveringPiece = __instance.GetHoveringPiece();
			if ((Object)(object)hoveringPiece == (Object)null)
			{
				return true;
			}
			int num = ModConfig.MaxRepairsPerSwing.Value;
			float num2 = ModConfig.SearchRadius.Value;
			bool flag = ModConfig.RequireWorkbench.Value;
			if (NetworkManager.ServerHasMod)
			{
				num = Math.Min(num, NetworkManager.ServerMaxRepairs);
				num2 = Math.Min(num2, NetworkManager.ServerSearchRadius);
				flag = flag || NetworkManager.ServerRequireWorkbench;
			}
			if (flag)
			{
				if (s_checkCanRemovePieceDelegate != null)
				{
					if (!s_checkCanRemovePieceDelegate(__instance, hoveringPiece))
					{
						return false;
					}
				}
				else if ((Object)(object)hoveringPiece.m_craftingStation != (Object)null && !__instance.NoCostCheat() && !Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(hoveringPiece.m_craftingStation.m_name, ((Component)__instance).transform.position)) && !ZoneSystem.instance.GetGlobalKey((GlobalKeys)27))
				{
					((Character)__instance).Message((MessageType)2, "$msg_missingstation", 0, (Sprite)null, false);
					return false;
				}
			}
			if (!PrivateArea.CheckAccess(((Component)hoveringPiece).transform.position, 0f, true, false))
			{
				return true;
			}
			if (toolItem == null)
			{
				return true;
			}
			if (ModConfig.PreventToolBreak.Value && toolItem.m_shared.m_useDurability && toolItem.m_durability <= 1f)
			{
				((Character)__instance).Message((MessageType)2, "$msg_toolbroken", 0, (Sprite)null, false);
				return false;
			}
			if ((Object)(object)MassRepairRunner.Instance != (Object)null && MassRepairRunner.Instance.IsRunning)
			{
				return false;
			}
			WearNTear component = ((Component)hoveringPiece).GetComponent<WearNTear>();
			if ((Object)(object)component == (Object)null)
			{
				return true;
			}
			List<WearNTear> list = StructureGraphTraverser.FindPiecesToRepair(__instance, component, ModConfig.Mode.Value, num2, num, ModConfig.MaxSearchVisitedNodes.Value, flag);
			if (list.Count == 0)
			{
				if (ModConfig.ShowHudNotification.Value)
				{
					((Character)__instance).Message((MessageType)1, hoveringPiece.m_name + " $msg_doesnotneedrepair", 0, (Sprite)null, false);
				}
				return false;
			}
			if (NetworkManager.ServerHasMod && (Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && NetworkManager.SendBatchRepair(__instance, toolItem, hoveringPiece, list))
			{
				return false;
			}
			MassRepairRunner massRepairRunner = MassRepairRunner.Instance;
			if ((Object)(object)massRepairRunner == (Object)null && (Object)(object)MassFixStructurePlugin.Instance != (Object)null)
			{
				massRepairRunner = ((Component)MassFixStructurePlugin.Instance).gameObject.AddComponent<MassRepairRunner>();
			}
			if ((Object)(object)massRepairRunner != (Object)null)
			{
				massRepairRunner.ExecuteRepair(__instance, toolItem, hoveringPiece, list);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(ZRoutedRpc))]
	public static class ZRoutedRpcPatch
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		public static void Constructor_Postfix(ZRoutedRpc __instance, bool server)
		{
			try
			{
				NetworkManager.ServerHasMod = server;
				NetworkManager.RegisterRPCs(__instance);
			}
			catch (Exception arg)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Failed to register RPCs in ZRoutedRpc constructor: {arg}");
				}
			}
		}

		[HarmonyPatch("AddPeer")]
		[HarmonyPostfix]
		public static void AddPeer_Postfix(ZNetPeer peer)
		{
			try
			{
				NetworkManager.OnPeerConnected(peer);
			}
			catch (Exception arg)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Failed to handle OnPeerConnected: {arg}");
				}
			}
		}
	}
}
namespace MassFixStructure.Network
{
	public static class NetworkManager
	{
		public const string RPC_SERVER_HELLO = "MassFix_ServerHello";

		public const string RPC_CLIENT_HELLO = "MassFix_ClientHello";

		public const string RPC_BATCH_REPAIR = "MassFix_BatchRepair";

		public const string RPC_SYNC_REPAIRS = "MassFix_SyncRepairs";

		private static readonly Dictionary<long, float> s_peerLastRepairTime;

		private const float MIN_REPAIR_INTERVAL = 0.8f;

		private static readonly Action<WearNTear, float, bool>? s_setHealthVisualDelegate;

		private static readonly Action<WearNTear>? s_clearCachedSupportDelegate;

		private static readonly FieldRef<WearNTear, float>? s_healthPercentageField;

		private static readonly List<PrivateArea>? s_allPrivateAreas;

		private static readonly Func<PrivateArea, bool>? s_areaIsEnabledDelegate;

		private static readonly Func<PrivateArea, Vector3, float, bool>? s_areaIsInsideDelegate;

		private static readonly Func<PrivateArea, long, bool>? s_areaIsPermittedDelegate;

		private static readonly FieldRef<PrivateArea, Piece>? s_areaPieceField;

		public static bool ServerHasMod { get; set; }

		public static int ServerMaxRepairs { get; private set; }

		public static float ServerSearchRadius { get; private set; }

		public static bool ServerRequireWorkbench { get; private set; }

		static NetworkManager()
		{
			ServerHasMod = false;
			ServerMaxRepairs = 200;
			ServerSearchRadius = 30f;
			ServerRequireWorkbench = true;
			s_peerLastRepairTime = new Dictionary<long, float>();
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(WearNTear), "SetHealthVisual", new Type[2]
				{
					typeof(float),
					typeof(bool)
				}, (Type[])null);
				if (methodInfo != null)
				{
					s_setHealthVisualDelegate = AccessTools.MethodDelegate<Action<WearNTear, float, bool>>(methodInfo, (object)null, true);
				}
				MethodInfo methodInfo2 = AccessTools.Method(typeof(WearNTear), "ClearCachedSupport", (Type[])null, (Type[])null);
				if (methodInfo2 != null)
				{
					s_clearCachedSupportDelegate = AccessTools.MethodDelegate<Action<WearNTear>>(methodInfo2, (object)null, true);
				}
				s_healthPercentageField = AccessTools.FieldRefAccess<WearNTear, float>("m_healthPercentage");
				FieldInfo fieldInfo = AccessTools.Field(typeof(PrivateArea), "m_allAreas");
				if (fieldInfo != null)
				{
					s_allPrivateAreas = fieldInfo.GetValue(null) as List<PrivateArea>;
				}
				MethodInfo methodInfo3 = AccessTools.Method(typeof(PrivateArea), "IsEnabled", (Type[])null, (Type[])null);
				if (methodInfo3 != null)
				{
					s_areaIsEnabledDelegate = AccessTools.MethodDelegate<Func<PrivateArea, bool>>(methodInfo3, (object)null, true);
				}
				MethodInfo methodInfo4 = AccessTools.Method(typeof(PrivateArea), "IsInside", new Type[2]
				{
					typeof(Vector3),
					typeof(float)
				}, (Type[])null);
				if (methodInfo4 != null)
				{
					s_areaIsInsideDelegate = AccessTools.MethodDelegate<Func<PrivateArea, Vector3, float, bool>>(methodInfo4, (object)null, true);
				}
				MethodInfo methodInfo5 = AccessTools.Method(typeof(PrivateArea), "IsPermitted", new Type[1] { typeof(long) }, (Type[])null);
				if (methodInfo5 != null)
				{
					s_areaIsPermittedDelegate = AccessTools.MethodDelegate<Func<PrivateArea, long, bool>>(methodInfo5, (object)null, true);
				}
				s_areaPieceField = AccessTools.FieldRefAccess<PrivateArea, Piece>("m_piece");
			}
			catch (Exception ex)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not bind cached delegates in NetworkManager: " + ex.Message));
				}
			}
		}

		public static void RegisterRPCs(ZRoutedRpc routedRpc)
		{
			if (routedRpc != null)
			{
				routedRpc.Register<ZPackage>("MassFix_ServerHello", (Action<long, ZPackage>)RPC_HandleServerHello);
				routedRpc.Register<ZPackage>("MassFix_ClientHello", (Action<long, ZPackage>)RPC_HandleClientHello);
				routedRpc.Register<ZPackage>("MassFix_BatchRepair", (Action<long, ZPackage>)RPC_HandleBatchRepair);
				routedRpc.Register<ZPackage>("MassFix_SyncRepairs", (Action<long, ZPackage>)RPC_HandleSyncRepairs);
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"Registered MassFixStructure routed RPCs.");
				}
			}
		}

		public static void OnPeerConnected(ZNetPeer peer)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			if (peer == null || ZRoutedRpc.instance == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			if (ZNet.instance.IsServer())
			{
				ZPackage val = new ZPackage();
				val.Write(ModConfig.MaxRepairsPerSwing.Value);
				val.Write(ModConfig.SearchRadius.Value);
				val.Write(ModConfig.RequireWorkbench.Value);
				val.Write(0.8f);
				ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "MassFix_ServerHello", new object[1] { val });
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Sent ServerHello to peer {peer.m_uid}");
				}
			}
			else
			{
				ZPackage val2 = new ZPackage();
				val2.Write("1.0.1");
				ZRoutedRpc.instance.InvokeRoutedRPC("MassFix_ClientHello", new object[1] { val2 });
			}
		}

		public static long GetServerPeerID()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return 0L;
			}
			if (ZNet.instance.IsServer())
			{
				return ZNet.GetUID();
			}
			return ZNet.instance.GetServerPeer()?.m_uid ?? 0;
		}

		public static bool SendBatchRepair(Player player, ItemData toolItem, Piece originPiece, List<WearNTear> piecesToRepair)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Expected O, but got Unknown
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			if (piecesToRepair == null || piecesToRepair.Count == 0 || ZRoutedRpc.instance == null)
			{
				return false;
			}
			player.FaceLookDirection();
			if (toolItem.m_shared.m_attack != null)
			{
				ZSyncAnimation zAnim = ((Character)player).GetZAnim();
				if (zAnim != null)
				{
					zAnim.SetTrigger(toolItem.m_shared.m_attack.m_attackAnimation);
				}
			}
			if (ModConfig.SoundMode.Value == PlaySoundMode.SingleAtOrigin && (Object)(object)originPiece != (Object)null && originPiece.m_placeEffect != null)
			{
				originPiece.m_placeEffect.Create(((Component)originPiece).transform.position, ((Component)originPiece).transform.rotation, (Transform)null, 1f, -1, ((Character)player).GetZDOID());
			}
			CostMode value = ModConfig.Cost.Value;
			if (value == CostMode.VanillaPerSwing || value == CostMode.PerPieceScaled)
			{
				float num = MassRepairRunner.GetPlayerBuildStamina(player);
				float num2 = (toolItem.m_shared.m_useDurability ? (toolItem.m_shared.m_useDurabilityDrain * Game.m_durabilityRate) : 0f);
				if (value == CostMode.PerPieceScaled && piecesToRepair.Count > 1)
				{
					int num3 = piecesToRepair.Count - 1;
					num += num * ModConfig.PerPieceStaminaRatio.Value * (float)num3;
					num2 += num2 * ModConfig.PerPieceDurabilityRatio.Value * (float)num3;
				}
				((Character)player).UseStamina(num);
				if (toolItem.m_shared.m_attack != null)
				{
					((Character)player).UseEitr(toolItem.m_shared.m_attack.m_attackEitr);
				}
				if (toolItem.m_shared.m_useDurability)
				{
					toolItem.m_durability -= num2;
				}
			}
			List<(ZDOID, float)> list = new List<(ZDOID, float)>(piecesToRepair.Count);
			for (int i = 0; i < piecesToRepair.Count; i++)
			{
				WearNTear val = piecesToRepair[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				ZDO zDO = component.GetZDO();
				if (zDO != null)
				{
					if (component.IsOwner())
					{
						zDO.Set(ZDOVars.s_health, val.m_health);
						ApplyClientHealthVisual(val, val.m_health);
					}
					list.Add((zDO.m_uid, val.m_health));
				}
			}
			if (list.Count == 0)
			{
				return false;
			}
			ZPackage val2 = new ZPackage();
			val2.Write(player.GetPlayerID());
			val2.Write(list.Count);
			for (int j = 0; j < list.Count; j++)
			{
				val2.Write(list[j].Item1);
				val2.Write(list[j].Item2);
			}
			ZRoutedRpc.instance.InvokeRoutedRPC("MassFix_BatchRepair", new object[1] { val2 });
			if (ModConfig.ShowHudNotification.Value)
			{
				((Character)player).Message((MessageType)1, $"MassFix: Repaired {list.Count} pieces (Server Synced)", 0, (Sprite)null, false);
			}
			return true;
		}

		private static void RPC_HandleServerHello(long sender, ZPackage pkg)
		{
			if (pkg == null)
			{
				return;
			}
			try
			{
				ServerMaxRepairs = pkg.ReadInt();
				ServerSearchRadius = pkg.ReadSingle();
				ServerRequireWorkbench = pkg.ReadBool();
				pkg.ReadSingle();
				ServerHasMod = true;
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"[MassFixStructure] Handshake complete with server. Server limits: MaxRepairs={ServerMaxRepairs}, Radius={ServerSearchRadius}m, RequireWorkbench={ServerRequireWorkbench}. Custom Batch RPC mode enabled!");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = MassFixStructurePlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Failed to read ServerHello: {arg}");
				}
			}
		}

		private static void RPC_HandleClientHello(long sender, ZPackage pkg)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ZRoutedRpc.instance != null)
			{
				ZPackage val = new ZPackage();
				val.Write(ModConfig.MaxRepairsPerSwing.Value);
				val.Write(ModConfig.SearchRadius.Value);
				val.Write(ModConfig.RequireWorkbench.Value);
				val.Write(0.8f);
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "MassFix_ServerHello", new object[1] { val });
			}
		}

		private static void RPC_HandleBatchRepair(long sender, ZPackage pkg)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || pkg == null || ZDOMan.instance == null)
			{
				return;
			}
			float time = Time.time;
			if (s_peerLastRepairTime.TryGetValue(sender, out var value) && time - value < 0.8f)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)$"[MassFix] Peer {sender} repair throttled (interval: {time - value:F2}s < {0.8f}s).");
				}
				return;
			}
			s_peerLastRepairTime[sender] = time;
			long playerId = pkg.ReadLong();
			int num = pkg.ReadInt();
			int value2 = ModConfig.MaxRepairsPerSwing.Value;
			if (num <= 0 || num > 1000)
			{
				return;
			}
			List<(ZDOID, float)> list = new List<(ZDOID, float)>(Math.Min(num, value2));
			for (int i = 0; i < num; i++)
			{
				ZDOID val = pkg.ReadZDOID();
				float num2 = pkg.ReadSingle();
				if (list.Count >= value2)
				{
					continue;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(val);
				if (zDO != null && CheckServerWardAccess(zDO.GetPosition(), playerId) && (zDO.GetFloat(ZDOVars.s_health, num2) < num2 - 0.01f || zDO.GetOwner() != ZDOMan.GetSessionID()))
				{
					if (zDO.IsOwner())
					{
						zDO.Set(ZDOVars.s_health, num2);
					}
					list.Add((val, num2));
				}
			}
			if (list.Count > 0 && ZRoutedRpc.instance != null)
			{
				ZPackage val2 = new ZPackage();
				val2.Write(list.Count);
				for (int j = 0; j < list.Count; j++)
				{
					val2.Write(list[j].Item1);
					val2.Write(list[j].Item2);
				}
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "MassFix_SyncRepairs", new object[1] { val2 });
				ManualLogSource log2 = MassFixStructurePlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"[MassFix Server] Processed batch repair from peer {sender}: {list.Count} pieces restored in 1 atomic packet.");
				}
			}
		}

		private static bool CheckServerWardAccess(Vector3 point, long playerId)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (s_allPrivateAreas == null || s_allPrivateAreas.Count == 0)
			{
				return true;
			}
			if (s_areaIsEnabledDelegate == null || s_areaIsInsideDelegate == null || s_areaIsPermittedDelegate == null)
			{
				return true;
			}
			bool flag = false;
			bool flag2 = false;
			for (int i = 0; i < s_allPrivateAreas.Count; i++)
			{
				PrivateArea val = s_allPrivateAreas[i];
				if (!((Object)(object)val == (Object)null) && s_areaIsEnabledDelegate(val) && s_areaIsInsideDelegate(val, point, 0f))
				{
					flag = true;
					Piece val2 = ((s_areaPieceField != null) ? s_areaPieceField.Invoke(val) : ((Component)val).GetComponent<Piece>());
					if ((Object)(object)val2 != (Object)null && val2.GetCreator() == playerId)
					{
						flag2 = true;
						break;
					}
					if (playerId != 0L && s_areaIsPermittedDelegate(val, playerId))
					{
						flag2 = true;
						break;
					}
				}
			}
			return !flag || flag2;
		}

		private static void RPC_HandleSyncRepairs(long sender, ZPackage pkg)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()) || pkg == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			try
			{
				int num = pkg.ReadInt();
				for (int i = 0; i < num; i++)
				{
					ZDOID val = pkg.ReadZDOID();
					float num2 = pkg.ReadSingle();
					GameObject val2 = ZNetScene.instance.FindInstance(val);
					if ((Object)(object)val2 != (Object)null)
					{
						ZNetView component = val2.GetComponent<ZNetView>();
						if ((Object)(object)component != (Object)null && component.IsValid() && component.IsOwner())
						{
							component.GetZDO().Set(ZDOVars.s_health, num2);
						}
						WearNTear component2 = val2.GetComponent<WearNTear>();
						if ((Object)(object)component2 != (Object)null)
						{
							ApplyClientHealthVisual(component2, num2);
						}
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Error in RPC_HandleSyncRepairs: " + ex.Message));
				}
			}
		}

		private static void ApplyClientHealthVisual(WearNTear wnt, float health)
		{
			float num = ((wnt.m_health > 0f) ? Mathf.Clamp01(health / wnt.m_health) : 1f);
			if (s_healthPercentageField != null)
			{
				s_healthPercentageField.Invoke(wnt) = num;
			}
			s_clearCachedSupportDelegate?.Invoke(wnt);
			s_setHealthVisualDelegate?.Invoke(wnt, num, arg3: false);
		}
	}
}
namespace MassFixStructure.Core
{
	public enum ActivationMode
	{
		AlwaysOnRepair,
		HoldModifierKey
	}
	public enum CostMode
	{
		VanillaPerSwing,
		PerPieceScaled,
		Free
	}
	public class MassRepairRunner : MonoBehaviour
	{
		private static readonly Func<Player, float>? s_getBuildStaminaDelegate;

		public static MassRepairRunner Instance { get; private set; }

		public bool IsRunning { get; private set; }

		static MassRepairRunner()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Player), "GetBuildStamina", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					s_getBuildStaminaDelegate = AccessTools.MethodDelegate<Func<Player, float>>(methodInfo, (object)null, true);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not bind GetBuildStamina delegate: " + ex.Message));
				}
			}
		}

		private void Awake()
		{
			Instance = this;
		}

		public static float GetPlayerBuildStamina(Player player)
		{
			if (s_getBuildStaminaDelegate != null && (Object)(object)player != (Object)null)
			{
				return s_getBuildStaminaDelegate(player);
			}
			return 5f;
		}

		public void ExecuteRepair(Player player, ItemData toolItem, Piece originPiece, List<WearNTear> piecesToRepair)
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated())
			{
				return;
			}
			if (piecesToRepair == null || piecesToRepair.Count == 0)
			{
				if (ModConfig.ShowHudNotification.Value && (Object)(object)player != (Object)null && (Object)(object)originPiece != (Object)null)
				{
					((Character)player).Message((MessageType)1, originPiece.m_name + " $msg_doesnotneedrepair", 0, (Sprite)null, false);
				}
				return;
			}
			player.FaceLookDirection();
			if (toolItem.m_shared.m_attack != null)
			{
				ZSyncAnimation zAnim = ((Character)player).GetZAnim();
				if (zAnim != null)
				{
					zAnim.SetTrigger(toolItem.m_shared.m_attack.m_attackAnimation);
				}
			}
			if (ModConfig.SoundMode.Value == PlaySoundMode.SingleAtOrigin && (Object)(object)originPiece != (Object)null && originPiece.m_placeEffect != null)
			{
				originPiece.m_placeEffect.Create(((Component)originPiece).transform.position, ((Component)originPiece).transform.rotation, (Transform)null, 1f, -1, ((Character)player).GetZDOID());
			}
			CostMode value = ModConfig.Cost.Value;
			if (value == CostMode.VanillaPerSwing || value == CostMode.PerPieceScaled)
			{
				((Character)player).UseStamina(GetPlayerBuildStamina(player));
				if (toolItem.m_shared.m_attack != null)
				{
					((Character)player).UseEitr(toolItem.m_shared.m_attack.m_attackEitr);
				}
				if (toolItem.m_shared.m_useDurability)
				{
					toolItem.m_durability -= toolItem.m_shared.m_useDurabilityDrain * Game.m_durabilityRate;
				}
			}
			bool value2 = ModConfig.StaggerBatchesOverFrames.Value;
			int value3 = ModConfig.BatchSizePerFrame.Value;
			if (!value2 || piecesToRepair.Count <= value3)
			{
				RunImmediate(player, toolItem, piecesToRepair, value);
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(RunBatched(player, toolItem, piecesToRepair, value3, value));
			}
		}

		private void RunImmediate(Player player, ItemData toolItem, List<WearNTear> pieces, CostMode costMode)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			bool toolBrokenHalt = false;
			float num2 = GetPlayerBuildStamina(player) * ModConfig.PerPieceStaminaRatio.Value;
			float num3 = (toolItem.m_shared.m_useDurability ? (toolItem.m_shared.m_useDurabilityDrain * Game.m_durabilityRate) : 0f) * ModConfig.PerPieceDurabilityRatio.Value;
			for (int i = 0; i < pieces.Count; i++)
			{
				WearNTear val = pieces[i];
				if ((Object)(object)val == (Object)null || !Object.op_Implicit((Object)(object)val))
				{
					continue;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid() || !PrivateArea.CheckAccess(((Component)val).transform.position, 0f, false, false))
				{
					continue;
				}
				if (ModConfig.PreventToolBreak.Value && toolItem.m_shared.m_useDurability && toolItem.m_durability <= 1f)
				{
					toolBrokenHalt = true;
					break;
				}
				if (!val.Repair())
				{
					continue;
				}
				num++;
				if (costMode == CostMode.PerPieceScaled && i > 0)
				{
					if (num2 > 0f)
					{
						((Character)player).UseStamina(num2);
					}
					if (num3 > 0f && toolItem.m_shared.m_useDurability)
					{
						toolItem.m_durability -= num3;
					}
				}
			}
			ShowCompletionHud(player, num, toolBrokenHalt);
		}

		private IEnumerator RunBatched(Player player, ItemData toolItem, List<WearNTear> pieces, int batchSize, CostMode costMode)
		{
			IsRunning = true;
			int repairedCount = 0;
			bool toolBrokenHalt = false;
			float extraStamina = GetPlayerBuildStamina(player) * ModConfig.PerPieceStaminaRatio.Value;
			float extraDurability = (toolItem.m_shared.m_useDurability ? (toolItem.m_shared.m_useDurabilityDrain * Game.m_durabilityRate) : 0f) * ModConfig.PerPieceDurabilityRatio.Value;
			int processedInCurrentFrame = 0;
			try
			{
				for (int i = 0; i < pieces.Count; i++)
				{
					if ((Object)(object)player == (Object)null)
					{
						break;
					}
					if (((Character)player).IsDead())
					{
						break;
					}
					if (!((Humanoid)player).IsItemEquiped(toolItem))
					{
						break;
					}
					WearNTear val = pieces[i];
					if ((Object)(object)val == (Object)null || !Object.op_Implicit((Object)(object)val))
					{
						continue;
					}
					ZNetView component = ((Component)val).GetComponent<ZNetView>();
					if ((Object)(object)component == (Object)null || !component.IsValid() || !PrivateArea.CheckAccess(((Component)val).transform.position, 0f, false, false))
					{
						continue;
					}
					if (ModConfig.PreventToolBreak.Value && toolItem.m_shared.m_useDurability && toolItem.m_durability <= 1f)
					{
						toolBrokenHalt = true;
						break;
					}
					if (val.Repair())
					{
						repairedCount++;
						if (costMode == CostMode.PerPieceScaled && i > 0)
						{
							if (extraStamina > 0f)
							{
								((Character)player).UseStamina(extraStamina);
							}
							if (extraDurability > 0f && toolItem.m_shared.m_useDurability)
							{
								toolItem.m_durability -= extraDurability;
							}
						}
					}
					processedInCurrentFrame++;
					if (processedInCurrentFrame >= batchSize)
					{
						processedInCurrentFrame = 0;
						yield return null;
					}
				}
			}
			finally
			{
				IsRunning = false;
			}
			ShowCompletionHud(player, repairedCount, toolBrokenHalt);
		}

		private void ShowCompletionHud(Player? player, int repairedCount, bool toolBrokenHalt)
		{
			if ((!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsDedicated()) && !((Object)(object)player == (Object)null) && ModConfig.ShowHudNotification.Value)
			{
				if (toolBrokenHalt)
				{
					((Character)player).Message((MessageType)2, $"MassFix: Stopped to protect tool durability! ({repairedCount} repaired)", 0, (Sprite)null, false);
				}
				else if (repairedCount > 0)
				{
					((Character)player).Message((MessageType)1, $"MassFix: Repaired {repairedCount} pieces", 0, (Sprite)null, false);
				}
				else
				{
					((Character)player).Message((MessageType)1, "$msg_doesnotneedrepair", 0, (Sprite)null, false);
				}
			}
		}
	}
	public enum PlaySoundMode
	{
		SingleAtOrigin,
		Muted
	}
	public enum RepairMode
	{
		Connected,
		ConnectedSameCategory,
		Radius
	}
	public static class StructureGraphTraverser
	{
		private static readonly Queue<WearNTear> s_queue;

		private static readonly HashSet<WearNTear> s_visited;

		private static readonly Collider[] s_overlapBuffer;

		private static int s_pieceMask;

		private static readonly Vector3 s_contactMargin;

		private static readonly Func<Player, Piece, bool>? s_checkCanRemovePieceDelegate;

		private static int PieceMask
		{
			get
			{
				if (s_pieceMask == 0)
				{
					s_pieceMask = LayerMask.GetMask(new string[5] { "piece", "piece_nonsolid", "Default", "static_solid", "Default_small" });
					if (s_pieceMask == 0)
					{
						s_pieceMask = LayerMask.GetMask(new string[2] { "piece", "piece_nonsolid" });
					}
					if (s_pieceMask == 0)
					{
						s_pieceMask = LayerMask.GetMask(new string[1] { "piece" });
					}
					if (s_pieceMask == 0)
					{
						int num = LayerMask.NameToLayer("piece");
						if (num >= 0)
						{
							s_pieceMask |= 1 << num;
						}
						int num2 = LayerMask.NameToLayer("piece_nonsolid");
						if (num2 >= 0)
						{
							s_pieceMask |= 1 << num2;
						}
					}
				}
				return s_pieceMask;
			}
		}

		static StructureGraphTraverser()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			s_queue = new Queue<WearNTear>(512);
			s_visited = new HashSet<WearNTear>(1024);
			s_overlapBuffer = (Collider[])(object)new Collider[1024];
			s_contactMargin = new Vector3(0.18f, 0.18f, 0.18f);
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Player), "CheckCanRemovePiece", new Type[1] { typeof(Piece) }, (Type[])null);
				if (methodInfo != null)
				{
					s_checkCanRemovePieceDelegate = AccessTools.MethodDelegate<Func<Player, Piece, bool>>(methodInfo, (object)null, true);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MassFixStructurePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not bind CheckCanRemovePiece delegate: " + ex.Message));
				}
			}
		}

		public static List<WearNTear> FindPiecesToRepair(Player player, WearNTear originWnt, RepairMode mode, float maxRadius, int maxRepairs, int maxVisitedNodes, bool requireWorkbench)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			List<WearNTear> list = new List<WearNTear>(Math.Min(maxRepairs, 256));
			if ((Object)(object)originWnt == (Object)null || (Object)(object)player == (Object)null)
			{
				return list;
			}
			s_queue.Clear();
			s_visited.Clear();
			Vector3 position = ((Component)originWnt).transform.position;
			Piece component = ((Component)originWnt).GetComponent<Piece>();
			PieceCategory? targetCategory = (((Object)(object)component != (Object)null) ? new PieceCategory?(component.m_category) : ((PieceCategory?)null));
			if (mode == RepairMode.Radius)
			{
				FindPiecesInRadius(player, position, maxRadius, maxRepairs, requireWorkbench, list);
			}
			else
			{
				bool sameCategoryOnly = mode == RepairMode.ConnectedSameCategory && targetCategory.HasValue;
				FindPiecesConnected(player, originWnt, position, maxRadius, maxRepairs, maxVisitedNodes, requireWorkbench, sameCategoryOnly, targetCategory, list);
			}
			return list;
		}

		private static void FindPiecesInRadius(Player player, Vector3 originPos, float radius, int maxRepairs, bool requireWorkbench, List<WearNTear> results)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			int num = Physics.OverlapSphereNonAlloc(originPos, radius, s_overlapBuffer, PieceMask);
			for (int i = 0; i < num; i++)
			{
				Collider val = s_overlapBuffer[i];
				if ((Object)(object)val == (Object)null || val.isTrigger || (Object)(object)val.attachedRigidbody != (Object)null)
				{
					continue;
				}
				WearNTear componentInParent = ((Component)val).GetComponentInParent<WearNTear>();
				if (!((Object)(object)componentInParent == (Object)null) && s_visited.Add(componentInParent) && NeedsRepair(componentInParent) && HasRepairPermission(player, componentInParent, requireWorkbench))
				{
					results.Add(componentInParent);
					if (results.Count >= maxRepairs)
					{
						break;
					}
				}
			}
		}

		private static void FindPiecesConnected(Player player, WearNTear originWnt, Vector3 originPos, float maxRadius, int maxRepairs, int maxVisitedNodes, bool requireWorkbench, bool sameCategoryOnly, PieceCategory? targetCategory, List<WearNTear> results)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: 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)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: 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_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			s_visited.Add(originWnt);
			s_queue.Enqueue(originWnt);
			if (NeedsRepair(originWnt) && HasRepairPermission(player, originWnt, requireWorkbench))
			{
				results.Add(originWnt);
			}
			Vector3 val4 = default(Vector3);
			while (s_queue.Count > 0 && s_visited.Count < maxVisitedNodes && results.Count < maxRepairs)
			{
				WearNTear val = s_queue.Dequeue();
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Collider[] componentsInChildren = ((Component)val).GetComponentsInChildren<Collider>(false);
				if (componentsInChildren == null || componentsInChildren.Length == 0)
				{
					continue;
				}
				foreach (Collider val2 in componentsInChildren)
				{
					if ((Object)(object)val2 == (Object)null || val2.isTrigger || (Object)(object)val2.attachedRigidbody != (Object)null)
					{
						continue;
					}
					BoxCollider val3 = (BoxCollider)(object)((val2 is BoxCollider) ? val2 : null);
					Vector3 val5;
					Vector3 val6;
					Quaternion val7;
					if (val3 != null)
					{
						Transform transform = ((Component)val3).transform;
						Vector3 lossyScale = transform.lossyScale;
						((Vector3)(ref val4))..ctor(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.y), Mathf.Abs(lossyScale.z));
						val5 = transform.TransformPoint(val3.center);
						val6 = Vector3.Scale(val3.size * 0.5f, val4) + s_contactMargin;
						val7 = transform.rotation;
					}
					else
					{
						Bounds bounds = val2.bounds;
						val5 = ((Bounds)(ref bounds)).center;
						val6 = ((Bounds)(ref bounds)).extents + s_contactMargin;
						val7 = Quaternion.identity;
					}
					int num = Physics.OverlapBoxNonAlloc(val5, val6, s_overlapBuffer, val7, PieceMask);
					for (int j = 0; j < num; j++)
					{
						Collider val8 = s_overlapBuffer[j];
						if ((Object)(object)val8 == (Object)null || val8.isTrigger || (Object)(object)val8.attachedRigidbody != (Object)null)
						{
							continue;
						}
						WearNTear componentInParent = ((Component)val8).GetComponentInParent<WearNTear>();
						if ((Object)(object)componentInParent == (Object)null || !s_visited.Add(componentInParent) || Vector3.Distance(originPos, ((Component)componentInParent).transform.position) > maxRadius)
						{
							continue;
						}
						if (sameCategoryOnly)
						{
							Piece component = ((Component)componentInParent).GetComponent<Piece>();
							if ((Object)(object)component == (Object)null || component.m_category != targetCategory.Value)
							{
								continue;
							}
						}
						s_queue.Enqueue(componentInParent);
						if (NeedsRepair(componentInParent) && HasRepairPermission(player, componentInParent, requireWorkbench))
						{
							results.Add(componentInParent);
							if (results.Count >= maxRepairs)
							{
								return;
							}
						}
					}
				}
			}
		}

		public static bool NeedsRepair(WearNTear wnt)
		{
			if ((Object)(object)wnt == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)wnt).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return false;
			}
			return zDO.GetFloat(ZDOVars.s_health, wnt.m_health) < wnt.m_health - 0.01f;
		}

		public static bool HasRepairPermission(Player player, WearNTear wnt, bool requireWorkbench)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)wnt == (Object)null || (Object)(object)player == (Object)null)
			{
				return false;
			}
			if (!PrivateArea.CheckAccess(((Component)wnt).transform.position, 0f, false, false))
			{
				return false;
			}
			if (requireWorkbench && !player.NoCostCheat())
			{
				Piece component = ((Component)wnt).GetComponent<Piece>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.m_craftingStation != (Object)null && ((Object)(object)ZoneSystem.instance == (Object)null || !ZoneSystem.instance.GetGlobalKey((GlobalKeys)27)))
				{
					string name = component.m_craftingStation.m_name;
					if (!Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(name, ((Component)component).transform.position)) && !Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(name, ((Component)player).transform.position)))
					{
						return false;
					}
				}
			}
			return true;
		}
	}
}
namespace MassFixStructure.Configuration
{
	public static class ModConfig
	{
		public static ConfigEntry<bool> ModEnabled;

		public static ConfigEntry<RepairMode> Mode;

		public static ConfigEntry<ActivationMode> Activation;

		public static ConfigEntry<KeyCode> ModifierKey;

		public static ConfigEntry<int> MaxRepairsPerSwing;

		public static ConfigEntry<float> SearchRadius;

		public static ConfigEntry<int> MaxSearchVisitedNodes;

		public static ConfigEntry<bool> RequireWorkbench;

		public static ConfigEntry<bool> StaggerBatchesOverFrames;

		public static ConfigEntry<int> BatchSizePerFrame;

		public static ConfigEntry<CostMode> Cost;

		public static ConfigEntry<float> PerPieceStaminaRatio;

		public static ConfigEntry<float> PerPieceDurabilityRatio;

		public static ConfigEntry<bool> PreventToolBreak;

		public static ConfigEntry<PlaySoundMode> SoundMode;

		public static ConfigEntry<bool> ShowHudNotification;

		public static void Initialize(ConfigFile config)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			ModEnabled = config.Bind<bool>("1 - General", "ModEnabled", true, "Master toggle for the MassFixStructure mod.");
			Mode = config.Bind<RepairMode>("1 - General", "RepairMode", RepairMode.Connected, "Algorithm used to find pieces to repair:\n- Connected: Traverses physically touching structural pieces (recommended).\n- ConnectedSameCategory: Connected BFS restricted to the same piece category (e.g. only Building or Furniture).\n- Radius: All damaged pieces within SearchRadius.");
			Activation = config.Bind<ActivationMode>("1 - General", "ActivationMode", ActivationMode.AlwaysOnRepair, "When mass repair triggers:\n- AlwaysOnRepair: Every hammer repair action repairs the structure.\n- HoldModifierKey: Only triggers when holding the ModifierKey (otherwise standard single repair).");
			ModifierKey = config.Bind<KeyCode>("1 - General", "ModifierKey", (KeyCode)304, "Key to hold for mass repair when ActivationMode is set to HoldModifierKey.");
			MaxRepairsPerSwing = config.Bind<int>("2 - Search & Limits", "MaxRepairsPerSwing", 200, new ConfigDescription("Maximum number of damaged pieces to fix in a single repair action.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), Array.Empty<object>()));
			SearchRadius = config.Bind<float>("2 - Search & Limits", "SearchRadius", 30f, new ConfigDescription("Maximum distance (in meters) from the targeted piece to include in the repair search.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 100f), Array.Empty<object>()));
			MaxSearchVisitedNodes = config.Bind<int>("2 - Search & Limits", "MaxSearchVisitedNodes", 1000, new ConfigDescription("Safety limit on the number of piece nodes visited during connected graph traversal.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 5000), Array.Empty<object>()));
			RequireWorkbench = config.Bind<bool>("2 - Search & Limits", "RequireWorkbench", true, "If true, repairs will respect workbench/crafting station coverage required by the piece.");
			StaggerBatchesOverFrames = config.Bind<bool>("3 - Performance & Network", "StaggerBatchesOverFrames", true, "If true, spreads piece repairs across consecutive frames to prevent server/network packet loss on large structures.");
			BatchSizePerFrame = config.Bind<int>("3 - Performance & Network", "BatchSizePerFrame", 20, new ConfigDescription("Number of pieces repaired per physics/render frame when batching is active.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>()));
			Cost = config.Bind<CostMode>("4 - Costs & Protection", "CostMode", CostMode.VanillaPerSwing, "How stamina and hammer durability are consumed:\n- VanillaPerSwing: Standard single swing cost for the whole cluster.\n- PerPieceScaled: Extra small stamina and durability cost per additional piece repaired.\n- Free: No stamina or tool durability consumed.");
			PerPieceStaminaRatio = config.Bind<float>("4 - Costs & Protection", "PerPieceStaminaRatio", 0.05f, new ConfigDescription("Multiplier for additional stamina consumed per extra piece if CostMode is PerPieceScaled (e.g. 0.05 = 5% of base swing stamina).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			PerPieceDurabilityRatio = config.Bind<float>("4 - Costs & Protection", "PerPieceDurabilityRatio", 0.05f, new ConfigDescription("Multiplier for additional durability drained per extra piece if CostMode is PerPieceScaled.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			PreventToolBreak = config.Bind<bool>("4 - Costs & Protection", "PreventToolBreak", true, "If true, aborts repair early if the hammer durability falls to 1.0 or below, preventing it from breaking.");
			SoundMode = config.Bind<PlaySoundMode>("5 - Feedback & UI", "SoundMode", PlaySoundMode.SingleAtOrigin, "Audio and visual particle feedback for mass repair.");
			ShowHudNotification = config.Bind<bool>("5 - Feedback & UI", "ShowHudNotification", true, "Show a consolidated HUD message (e.g. 'MassFix: Repaired 42 pieces') upon completion.");
		}
	}
}