Decompiled source of Better Arrow Flight v0.1.15

plugins/BetterArrowFlight.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using AzNean.SotfCommon;
using Ballistics;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BetterArrowFlight.Logic;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Microsoft.CodeAnalysis;
using Sons.Inventory;
using Sons.Weapon;
using TheForest.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BetterArrowFlight")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.15.0")]
[assembly: AssemblyInformationalVersion("0.1.15+04f969363884d50e104bc4139452770beb67c5b6")]
[assembly: AssemblyProduct("BetterArrowFlight")]
[assembly: AssemblyTitle("BetterArrowFlight")]
[assembly: AssemblyVersion("0.1.15.0")]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AzNean.SotfCommon
{
	internal static class ModLog
	{
		private static ManualLogSource _log;

		private static ConfigEntry<bool> _full;

		private static readonly HashSet<string> _once = new HashSet<string>();

		private static readonly Dictionary<(int, string), int> _state = new Dictionary<(int, string), int>();

		internal static bool Full => _full.Value;

		internal static void Init(ManualLogSource log, ConfigEntry<bool> full)
		{
			_log = log;
			_full = full;
		}

		internal static void Trace(string message)
		{
			if (_full.Value)
			{
				_log.LogInfo((object)message);
			}
		}

		internal static bool Changed(int id, string what, int state)
		{
			if (!_full.Value || (_state.TryGetValue((id, what), out var value) && value == state))
			{
				return false;
			}
			_state[(id, what)] = state;
			return true;
		}

		internal static void Once(string key, string message, LogLevel level = (LogLevel)16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_once.Add(key))
			{
				_log.Log(level, (object)message);
			}
		}
	}
}
namespace BetterArrowFlight
{
	public class BowWatcher : MonoBehaviour
	{
		private static readonly Tuner Tuner = new Tuner();

		private int _heldId;

		private RangedWeapon _bow;

		private float _nextLookup;

		private float _nextCheck;

		private IntPtr _tunedInfo;

		private int _tunedVersion;

		private float _tunedSpeed;

		public BowWatcher(IntPtr ptr)
			: base(ptr)
		{
		}

		private void Update()
		{
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			RangedWeapon val = HeldBow();
			if ((Object)(object)val == (Object)null || Time.unscaledTime < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.unscaledTime + Plugin.CheckSeconds.Value;
			Ammo ammo = val.GetAmmo();
			object obj;
			if (ammo == null)
			{
				obj = null;
			}
			else
			{
				AmmoProperties properties = ammo._properties;
				obj = ((properties != null) ? properties.ProjectileInfo : null);
			}
			ProjectileInfo val2 = (ProjectileInfo)obj;
			if (val2 == null)
			{
				if (_tunedInfo != IntPtr.Zero)
				{
					ModLog.Trace("No arrow loaded in the bow");
				}
				_tunedInfo = IntPtr.Zero;
				return;
			}
			if (((Il2CppObjectBase)val2).Pointer == _tunedInfo && _tunedVersion == Plugin.SettingsVersion)
			{
				if (Math.Abs(((BulletInfo)val2).maxSpeed - _tunedSpeed) < 0.01f)
				{
					return;
				}
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(85, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Arrow item ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(ammo._type);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(": launch speed back to ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<float>(((BulletInfo)val2).maxSpeed);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" (tuned ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<float>(_tunedSpeed);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("): arrows flew as in the game; tuned again.");
				}
				logger.LogWarning(val3);
			}
			_tunedInfo = ((Il2CppObjectBase)val2).Pointer;
			_tunedVersion = Plugin.SettingsVersion;
			_tunedSpeed = Apply((BulletInfo)(object)val2, ammo._type);
		}

		private RangedWeapon HeldBow()
		{
			if (!LocalPlayer.IsInWorld)
			{
				return null;
			}
			ItemInstance rightHandItem = LocalPlayer.Inventory.RightHandItem;
			GameObject val = ((rightHandItem != null) ? rightHandItem.ItemObject : null);
			if ((Object)(object)val == (Object)null)
			{
				_heldId = 0;
				_bow = null;
				return null;
			}
			int instanceID = ((Object)val).GetInstanceID();
			if (instanceID != _heldId || ((Object)(object)_bow == (Object)null && Time.unscaledTime >= _nextLookup))
			{
				_heldId = instanceID;
				_nextLookup = Time.unscaledTime + Plugin.LookupSeconds.Value;
				_bow = (((Object)(object)val.GetComponentInChildren<BowWeaponController>(true) != (Object)null) ? val.GetComponentInChildren<RangedWeapon>(true) : null);
				if (ModLog.Changed(instanceID, "bow", ((Object)(object)_bow != (Object)null) ? 1 : 0))
				{
					ModLog.Trace("Held " + ((Object)val).name + ": " + (((Object)(object)_bow != (Object)null) ? "bow found" : "no bow (yet)"));
				}
			}
			if (!((Object)(object)_bow != (Object)null))
			{
				return null;
			}
			return _bow;
		}

		private static float Apply(BulletInfo info, int arrowItem)
		{
			bool value = Plugin.Enabled.Value;
			float speedMultiplier = (value ? Plugin.SpeedMultiplier.Value : 1f);
			float dragMultiplier = (value ? Plugin.DragMultiplier.Value : 1f);
			float maxSpeed = info.maxSpeed;
			float dragCoefficient = info.dragCoefficient;
			(float, float) values = Tuner.Tune(((Il2CppObjectBase)info).Pointer, maxSpeed, dragCoefficient, speedMultiplier, dragMultiplier);
			Tuner.TryOriginal(((Il2CppObjectBase)info).Pointer, out (float, float) original);
			Write(info, values);
			ModLog.Trace($"Arrow item {arrowItem} tuned (enabled {value}): speed {maxSpeed} -> {values.Item1} (game's {original.Item1}), air drag {dragCoefficient} -> {values.Item2} (game's {original.Item2}), weight {info.weight}");
			return info.maxSpeed;
		}

		private static void Write(BulletInfo info, (float Speed, float Drag) values)
		{
			info.maxSpeed = values.Speed;
			info.dragCoefficient = values.Drag;
			info.precalculateDrag();
		}
	}
	[BepInPlugin("aznan.sotf.betterarrowflight", "BetterArrowFlight", "0.1.15")]
	public class Plugin : BasePlugin
	{
		internal const string Version = "0.1.15";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> SpeedMultiplier;

		internal static ConfigEntry<float> DragMultiplier;

		internal static ConfigEntry<float> CheckSeconds;

		internal static ConfigEntry<float> LookupSeconds;

		internal static ConfigEntry<bool> FullLogging;

		internal static int SettingsVersion = 1;

		public override void Load()
		{
			//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_0133: Expected O, but got Unknown
			//IL_0133: 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_0151: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			Tuner.SelfCheck();
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "True = bow arrows fly with the settings below. False = they fly as in the game (changes apply while you play).");
			SpeedMultiplier = ((BasePlugin)this).Config.Bind<float>("Arrows", "SpeedMultiplier", 1.5f, "Arrow launch speed, times the game's own. Faster arrows drop less and reach further. 1 = the game's own. Suggested: 0.5 to 4. Must be above 0.");
			DragMultiplier = ((BasePlugin)this).Config.Bind<float>("Arrows", "AirDragMultiplier", 0.5f, "How much the air slows arrows down, times the game's own. Lower keeps them fast over distance, so they drop less at long range. 1 = the game's own, 0 = no slowing at all. Suggested: 0 to 2. Cannot be below 0.");
			CheckSeconds = ((BasePlugin)this).Config.Bind<float>("Performance", "CheckSeconds", 0.1f, "While the bow is in your hand, seconds between two checks of which arrow is loaded (a newly chosen arrow type is tuned within this delay). Suggested: 0.02 to 1; 0 = every frame.");
			LookupSeconds = ((BasePlugin)this).Config.Bind<float>("Performance", "LookupSeconds", 0.5f, "While the item in your hand shows no bow yet (just equipped, or not a bow), seconds between two new looks. Suggested: 0.1 to 5; 0 = every frame.");
			FullLogging = ((BasePlugin)this).Config.Bind<bool>("Debug", "FullLogging", false, "True = the BepInEx log gets every step useful to diagnose a problem (bow found, arrow loaded, values before and after tuning). False = only loading, version and errors.");
			ModLog.Init(Logger, FullLogging);
			Validate();
			((BasePlugin)this).Config.SettingChanged += delegate
			{
				SettingsVersion++;
				Validate();
			};
			ClassInjector.RegisterTypeInIl2Cpp<BowWatcher>();
			GameObject val = new GameObject("BetterArrowFlight");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<BowWatcher>();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(25, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("BetterArrowFlight ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>("0.1.15");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" loaded");
			}
			logger.LogInfo(val2);
		}

		private static void Validate()
		{
			if (SpeedMultiplier.Value <= 0f)
			{
				Refuse(SpeedMultiplier, "must be above 0");
			}
			if (DragMultiplier.Value < 0f)
			{
				Refuse(DragMultiplier, "cannot be below 0");
			}
		}

		private static void Refuse(ConfigEntry<float> entry, string why)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(24, 4, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((ConfigEntryBase)entry).Definition.Key);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" = ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(entry.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" refused (");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(why);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("); back to ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(((ConfigEntryBase)entry).DefaultValue);
			}
			logger.LogWarning(val);
			entry.Value = (float)((ConfigEntryBase)entry).DefaultValue;
		}
	}
}
namespace BetterArrowFlight.Logic
{
	public sealed class Tuner
	{
		private readonly Dictionary<IntPtr, (float Speed, float Drag)> _originals = new Dictionary<IntPtr, (float, float)>();

		public bool TryOriginal(IntPtr id, out (float Speed, float Drag) original)
		{
			return _originals.TryGetValue(id, out original);
		}

		public (float Speed, float Drag) Tune(IntPtr id, float currentSpeed, float currentDrag, float speedMultiplier, float dragMultiplier)
		{
			if (!_originals.TryGetValue(id, out (float, float) value))
			{
				value = (_originals[id] = (currentSpeed, currentDrag));
			}
			return (Speed: value.Item1 * speedMultiplier, Drag: value.Item2 * dragMultiplier);
		}

		public static void SelfCheck()
		{
			Tuner tuner = new Tuner();
			(float, float) tuple = tuner.Tune((IntPtr)1, 40f, 2f, 1.5f, 0.5f);
			(float, float) tuple2 = tuner.Tune((IntPtr)1, tuple.Item1, tuple.Item2, 1.5f, 0.5f);
			(float, float) tuple3 = tuner.Tune((IntPtr)1, tuple.Item1, tuple.Item2, 1f, 1f);
			(float, float) tuple4 = tuple;
			if (tuple4.Item1 == 60f && tuple4.Item2 == 1f)
			{
				tuple4 = tuple2;
				(float, float) tuple5 = tuple;
				if (tuple4.Item1 == tuple5.Item1 && tuple4.Item2 == tuple5.Item2)
				{
					tuple5 = tuple3;
					if (tuple5.Item1 == 40f && tuple5.Item2 == 2f)
					{
						return;
					}
				}
			}
			throw new InvalidOperationException("BetterArrowFlight Tuner self-check failed");
		}
	}
}