Decompiled source of BatterySquat v1.1.1

BatterySquat.dll

Decompiled 6 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace BatterySquat;

[BepInPlugin("com.Aartyns.batterysquat", "BatterySquat", "1.1.1")]
[BepInProcess("REPO.exe")]
public class BatterySquatPlugin : BaseUnityPlugin
{
	public const string Guid = "com.Aartyns.batterysquat";

	public const string PluginName = "BatterySquat";

	public const string Version = "1.1.1";

	public static ConfigEntry<bool> CfgEnabled;

	public static ConfigEntry<float> CfgStaminaCost;

	public static ConfigEntry<int> CfgBarsPerSquat;

	public static ConfigEntry<bool> CfgRequireEnoughStamina;

	public static ConfigEntry<bool> CfgAllowClientCharge;

	public static ConfigEntry<bool> CfgRequireHostMod;

	public static ConfigEntry<byte> CfgEventCode;

	public static ConfigEntry<bool> CfgVerbose;

	private Harmony harmony;

	private bool eventHooked;

	private const int ProtocolVersion = 1;

	private const float HelloInterval = 2f;

	private const float ProbeInterval = 3f;

	private const float HelloTimeout = 4.5f;

	private static float lastHelloSent = -999f;

	private static float lastProbeSent = -999f;

	private static float hostHelloStamp = -999f;

	private static int hostProtocolVersion;

	private static float roomEnterStamp = -999f;

	private static bool warnedMissingHost;

	private static readonly Dictionary<int, float> lastChargeTime = new Dictionary<int, float>();

	internal static BatterySquatPlugin Instance { get; private set; }

	internal static ManualLogSource Log { get; private set; }

	private void Awake()
	{
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Expected O, but got Unknown
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Expected O, but got Unknown
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		CfgEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "总开关。false 时蹲下不再补充物品电量,也不消耗体力。");
		CfgStaminaCost = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Stamina Cost", 10f, new ConfigDescription("每次下蹲消耗的体力点数(原版体力上限 EnergyStart 为 100)。", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
		CfgBarsPerSquat = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Bars Per Squat", 1, new ConfigDescription("每次下蹲为手持物品补充的电池格数(1 格 = 100 / batteryBars,默认物品 6 格)。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 6), Array.Empty<object>()));
		CfgRequireEnoughStamina = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Require Enough Stamina", true, "true = 体力不足 Stamina Cost 时完全不触发(不充能、不扣体力);false = 有多少扣多少,照样充能。");
		CfgAllowClientCharge = ((BaseUnityPlugin)this).Config.Bind<bool>("Multiplayer", "Allow Client Charge", true, "true = 非主机玩家下蹲时通过 Photon 事件请求主机加电;false = 只有主机/单人下蹲才生效。");
		CfgRequireHostMod = ((BaseUnityPlugin)this).Config.Bind<bool>("Multiplayer", "Require Host Installed", true, "true = 客机必须确认主机也装了本模组才生效(主机没装则客机蹲下不扣体力、不充能);false = 客机无条件生效。");
		CfgEventCode = ((BaseUnityPlugin)this).Config.Bind<byte>("Multiplayer", "Event Code", (byte)209, new ConfigDescription("本模组占用的 Photon 事件码基址,连续占用 EventCode、+1、+2、+3(充能请求 / 充能回执 / 客机探测 / 主机心跳)。100~250,避开其它联机模组已用值。", (AcceptableValueBase)(object)new AcceptableValueRange<byte>((byte)100, (byte)250), Array.Empty<object>()));
		CfgVerbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Advanced", "Verbose Log", false, "输出详细日志,排查触发/充能失败原因时打开。");
		harmony = new Harmony("com.Aartyns.batterysquat");
		TryPatch();
		TryHookPhoton();
		Log.LogInfo((object)("BatterySquat 1.1.1 loaded. cost=" + CfgStaminaCost.Value + " stamina, bars=" + CfgBarsPerSquat.Value));
	}

	private void TryPatch()
	{
		try
		{
			harmony.PatchAll(typeof(BatterySquatPlugin).Assembly);
			Log.LogInfo((object)"Harmony patched PlayerController.FixedUpdate.");
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Harmony patch failed: " + ex));
		}
	}

	private void TryHookPhoton()
	{
		if (eventHooked)
		{
			return;
		}
		try
		{
			if (PhotonNetwork.NetworkingClient != null)
			{
				PhotonNetwork.NetworkingClient.EventReceived -= OnEvent;
				PhotonNetwork.NetworkingClient.EventReceived += OnEvent;
				eventHooked = true;
				if (CfgVerbose.Value)
				{
					Log.LogInfo((object)"Photon EventReceived hooked.");
				}
			}
		}
		catch (Exception ex)
		{
			if (CfgVerbose.Value)
			{
				Log.LogWarning((object)("Hook photon event failed: " + ex.Message));
			}
		}
	}

	private void Update()
	{
		TryHookPhoton();
		TickHandshake();
	}

	private void TickHandshake()
	{
		try
		{
			if (!PhotonNetwork.InRoom)
			{
				ResetPeerState();
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				if (unscaledTime - lastHelloSent >= 2f)
				{
					lastHelloSent = unscaledTime;
					SendHello();
				}
				warnedMissingHost = false;
				return;
			}
			if (roomEnterStamp < 0f)
			{
				roomEnterStamp = unscaledTime;
			}
			bool flag = HostSupportsCharge();
			if (!flag && unscaledTime - lastProbeSent >= 3f)
			{
				lastProbeSent = unscaledTime;
				SendProbe();
			}
			if (!flag && !warnedMissingHost && unscaledTime - roomEnterStamp > 5f)
			{
				warnedMissingHost = true;
				Log.LogWarning((object)"主机未安装 BatterySquat(或协议版本不符),客机侧本模组不生效。");
			}
			else if (flag && warnedMissingHost)
			{
				warnedMissingHost = false;
				Log.LogInfo((object)"已与主机建立握手,客机侧本模组生效。");
			}
			float num = PendingCharge.Expire();
			if (num > 0f)
			{
				RefundStamina(num);
			}
		}
		catch (Exception ex)
		{
			if (CfgVerbose.Value)
			{
				Log.LogWarning((object)("TickHandshake error: " + ex.Message));
			}
		}
	}

	private void ResetPeerState()
	{
		lastHelloSent = -999f;
		lastProbeSent = -999f;
		hostHelloStamp = -999f;
		roomEnterStamp = -999f;
		hostProtocolVersion = 0;
		warnedMissingHost = false;
	}

	private static void SendHello()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		object[] array = new object[1] { 1 };
		RaiseEventOptions val = new RaiseEventOptions();
		val.Receivers = (ReceiverGroup)0;
		PhotonNetwork.RaiseEvent((byte)(CfgEventCode.Value + 3), (object)array, val, SendOptions.SendReliable);
	}

	private static void SendProbe()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		object[] array = new object[1] { 1 };
		RaiseEventOptions val = new RaiseEventOptions();
		val.Receivers = (ReceiverGroup)2;
		PhotonNetwork.RaiseEvent((byte)(CfgEventCode.Value + 2), (object)array, val, SendOptions.SendReliable);
		if (CfgVerbose.Value)
		{
			Log.LogInfo((object)"Probe host for BatterySquat presence.");
		}
	}

	internal static bool HostSupportsCharge()
	{
		if (!CfgRequireHostMod.Value)
		{
			return true;
		}
		if (!PhotonNetwork.InRoom)
		{
			return true;
		}
		if (SemiFunc.IsMasterClientOrSingleplayer())
		{
			return true;
		}
		if (Time.unscaledTime - hostHelloStamp > 4.5f)
		{
			return false;
		}
		return hostProtocolVersion == 1;
	}

	private void OnDestroy()
	{
		try
		{
			if (eventHooked && PhotonNetwork.NetworkingClient != null)
			{
				PhotonNetwork.NetworkingClient.EventReceived -= OnEvent;
			}
		}
		catch (Exception)
		{
		}
		eventHooked = false;
		try
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
		catch (Exception)
		{
		}
	}

	private static void OnEvent(EventData photonEvent)
	{
		try
		{
			if (photonEvent != null)
			{
				byte value = CfgEventCode.Value;
				byte b = (byte)(value + 1);
				byte b2 = (byte)(value + 2);
				byte b3 = (byte)(value + 3);
				if (photonEvent.Code == value)
				{
					HandleChargeRequest(photonEvent);
				}
				else if (photonEvent.Code == b)
				{
					HandleChargeReceipt(photonEvent);
				}
				else if (photonEvent.Code == b2)
				{
					HandleHostProbe(photonEvent);
				}
				else if (photonEvent.Code == b3)
				{
					HandleHostHello(photonEvent);
				}
			}
		}
		catch (Exception ex)
		{
			if (CfgVerbose.Value)
			{
				Log.LogWarning((object)("OnEvent error: " + ex.Message));
			}
		}
	}

	private static void HandleHostProbe(EventData photonEvent)
	{
		if (SemiFunc.IsMasterClientOrSingleplayer())
		{
			SendHello();
		}
	}

	private static void HandleHostHello(EventData photonEvent)
	{
		if (SemiFunc.IsMasterClientOrSingleplayer())
		{
			return;
		}
		int num = 0;
		if (photonEvent.CustomData is object[] array && array.Length >= 1)
		{
			try
			{
				num = Convert.ToInt32(array[0]);
			}
			catch (Exception)
			{
				num = 0;
			}
		}
		hostProtocolVersion = num;
		hostHelloStamp = Time.unscaledTime;
		if (CfgVerbose.Value)
		{
			Log.LogInfo((object)("Host hello received, protocol=" + num));
		}
	}

	private static void HandleChargeRequest(EventData photonEvent)
	{
		if (!SemiFunc.IsMasterClientOrSingleplayer() || !(photonEvent.CustomData is object[] array) || array.Length < 1)
		{
			return;
		}
		int num = Convert.ToInt32(array[0]);
		PhotonView val = PhotonView.Find(num);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		ItemBattery componentInChildren = ((Component)val).GetComponentInChildren<ItemBattery>(true);
		if ((Object)(object)componentInChildren == (Object)null || componentInChildren.batteryLife >= 99.999f)
		{
			ReplyCharge(num, 0f);
			return;
		}
		float unscaledTime = Time.unscaledTime;
		if (lastChargeTime.TryGetValue(num, out var value) && unscaledTime - value < 0.2f)
		{
			ReplyCharge(num, 0f);
			return;
		}
		lastChargeTime[num] = unscaledTime;
		float num2 = 100f / (float)Mathf.Max(1, componentInChildren.batteryBars) * (float)Mathf.Max(1, CfgBarsPerSquat.Value);
		float charged = componentInChildren.ReceiveCharge(num2);
		if (CfgVerbose.Value)
		{
			Log.LogInfo((object)("Charge request viewID=" + num + " charged=" + charged));
		}
		ReplyCharge(num, charged);
	}

	private static void ReplyCharge(int viewID, float charged)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		object[] array = new object[2] { viewID, charged };
		RaiseEventOptions val = new RaiseEventOptions();
		val.Receivers = (ReceiverGroup)1;
		PhotonNetwork.RaiseEvent((byte)(CfgEventCode.Value + 1), (object)array, val, SendOptions.SendReliable);
	}

	private static void HandleChargeReceipt(EventData photonEvent)
	{
		if (SemiFunc.IsMasterClientOrSingleplayer() || !(photonEvent.CustomData is object[] array) || array.Length < 2)
		{
			return;
		}
		int id = Convert.ToInt32(array[0]);
		if (Convert.ToSingle(array[1]) <= 0.001f)
		{
			float num = PendingCharge.Take(id);
			if (num > 0f)
			{
				RefundStamina(num);
			}
		}
	}

	private static void RefundStamina(float amount)
	{
		PlayerController instance = PlayerController.instance;
		if (!((Object)(object)instance == (Object)null))
		{
			instance.EnergyCurrent = Mathf.Min(instance.EnergyStart, instance.EnergyCurrent + amount);
			if (CfgVerbose.Value)
			{
				Log.LogInfo((object)("Stamina refunded: " + amount));
			}
		}
	}

	internal static void RaiseChargeRequest(ItemBattery battery, float staminaCost)
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		if (CfgAllowClientCharge.Value && !((Object)(object)battery == (Object)null) && HostSupportsCharge() && PhotonNetwork.InRoom)
		{
			PhotonView component = ((Component)battery).GetComponent<PhotonView>();
			if (!((Object)(object)component == (Object)null))
			{
				PendingCharge.Set(component.ViewID, staminaCost);
				object[] array = new object[1] { component.ViewID };
				RaiseEventOptions val = new RaiseEventOptions();
				val.Receivers = (ReceiverGroup)2;
				PhotonNetwork.RaiseEvent(CfgEventCode.Value, (object)array, val, SendOptions.SendReliable);
			}
		}
	}

	internal static void Verbose(string msg)
	{
		if (CfgVerbose.Value)
		{
			Log.LogInfo((object)msg);
		}
	}
}
internal static class PendingCharge
{
	private static int viewID;

	private static float cost;

	private static float stamp;

	internal static void Set(int id, float value)
	{
		viewID = id;
		cost = value;
		stamp = Time.unscaledTime;
	}

	internal static float Take(int id)
	{
		if (viewID != id || viewID == 0)
		{
			return 0f;
		}
		if (Time.unscaledTime - stamp > 2f)
		{
			viewID = 0;
			return 0f;
		}
		float result = cost;
		viewID = 0;
		cost = 0f;
		return result;
	}

	internal static float Expire()
	{
		if (viewID == 0)
		{
			return 0f;
		}
		if (Time.unscaledTime - stamp <= 1.5f)
		{
			return 0f;
		}
		float result = cost;
		viewID = 0;
		cost = 0f;
		return result;
	}
}
[HarmonyPatch(typeof(PlayerController), "FixedUpdate")]
internal static class PatchPlayerControllerFixedUpdate
{
	private static readonly FieldInfo FI_IsLocal = AccessTools.Field(typeof(PlayerAvatar), "isLocal");

	private static readonly FieldInfo FI_Grabbed = AccessTools.Field(typeof(PhysGrabber), "grabbedPhysGrabObject");

	private static bool prevCrouching;

	private static PlayerAvatar lastAvatar;

	[HarmonyPostfix]
	private static void Postfix(PlayerController __instance)
	{
		try
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			PlayerAvatar playerAvatarScript = __instance.playerAvatarScript;
			if ((Object)(object)playerAvatarScript == (Object)null || !IsLocal(playerAvatarScript))
			{
				return;
			}
			if (playerAvatarScript != lastAvatar)
			{
				lastAvatar = playerAvatarScript;
				prevCrouching = __instance.Crouching;
				return;
			}
			bool crouching = __instance.Crouching;
			bool num = crouching && !prevCrouching;
			prevCrouching = crouching;
			if (!num || !BatterySquatPlugin.CfgEnabled.Value)
			{
				return;
			}
			if (!BatterySquatPlugin.HostSupportsCharge())
			{
				BatterySquatPlugin.Verbose("Host is not running BatterySquat, skipped (no stamina cost).");
				return;
			}
			float num2 = Mathf.Max(0f, BatterySquatPlugin.CfgStaminaCost.Value);
			int num3 = Mathf.Max(1, BatterySquatPlugin.CfgBarsPerSquat.Value);
			PhysGrabber physGrabber = playerAvatarScript.physGrabber;
			if ((Object)(object)physGrabber == (Object)null)
			{
				return;
			}
			PhysGrabObject grabbed = GetGrabbed(physGrabber);
			if ((Object)(object)grabbed == (Object)null)
			{
				return;
			}
			ItemBattery componentInChildren = ((Component)grabbed).GetComponentInChildren<ItemBattery>(true);
			if ((Object)(object)componentInChildren == (Object)null || componentInChildren.batteryLife >= 99.999f)
			{
				return;
			}
			if (__instance.EnergyCurrent < num2 && BatterySquatPlugin.CfgRequireEnoughStamina.Value)
			{
				BatterySquatPlugin.Verbose("Not enough stamina (" + __instance.EnergyCurrent + " < " + num2 + "), skipped.");
				return;
			}
			float num4 = 100f / (float)Mathf.Max(1, componentInChildren.batteryBars) * (float)num3;
			float num5 = Mathf.Min(num2, __instance.EnergyCurrent);
			__instance.EnergyCurrent = Mathf.Max(0f, __instance.EnergyCurrent - num5);
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				float num6 = componentInChildren.ReceiveCharge(num4);
				BatterySquatPlugin.Verbose("Squat charge: item=" + ((Object)componentInChildren).name + " charged=" + num6 + " staminaCost=" + num5);
			}
			else
			{
				BatterySquatPlugin.RaiseChargeRequest(componentInChildren, num5);
				BatterySquatPlugin.Verbose("Squat charge request sent: item=" + ((Object)componentInChildren).name + " staminaCost=" + num5);
			}
		}
		catch (Exception ex)
		{
			if (BatterySquatPlugin.CfgVerbose != null && BatterySquatPlugin.CfgVerbose.Value)
			{
				BatterySquatPlugin.Log.LogWarning((object)("FixedUpdate patch error: " + ex.Message));
			}
		}
	}

	private static bool IsLocal(PlayerAvatar avatar)
	{
		if (FI_IsLocal != null)
		{
			try
			{
				object value = FI_IsLocal.GetValue(avatar);
				if (value is bool)
				{
					return (bool)value;
				}
			}
			catch (Exception)
			{
			}
		}
		return avatar == PlayerAvatar.instance;
	}

	private static PhysGrabObject GetGrabbed(PhysGrabber grabber)
	{
		if (FI_Grabbed == null)
		{
			return null;
		}
		try
		{
			object? value = FI_Grabbed.GetValue(grabber);
			return (PhysGrabObject)((value is PhysGrabObject) ? value : null);
		}
		catch (Exception)
		{
			return null;
		}
	}
}