Decompiled source of FallDamage v1.0.0

Mods/FallDamage.dll

Decompiled 18 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BoneLib;
using BoneLib.BoneMenu;
using FallDamage;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Marrow;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Main), "FallDamage", "1.0.0", "kamonkus", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 FallDamage
{
	public static class FallManager
	{
		private const float SafeSpeed = 7.5f;

		private const float LethalSpeed = 22f;

		private const float MinSpeedDrop = 2.5f;

		private const float LandingWindow = 0.08f;

		private const float Cooldown = 0.6f;

		private const float StartDelay = 2.5f;

		private const BindingFlags BF = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static Rigidbody _rb;

		private static PropertyInfo _velProp;

		private static bool _velSearched;

		private static float _nextFind;

		private static float _readyAt;

		private static float _peak;

		private static float _peakTime;

		private static float _landingUntil;

		private static float _minDown;

		private static float _cooldownUntil;

		private static bool _dumped;

		private static bool _loggedNoHealth;

		private static bool _loggedBody;

		public static void OnLevelLoaded()
		{
			_rb = null;
			_nextFind = 0f;
			_peak = 0f;
			_landingUntil = 0f;
			_readyAt = Time.realtimeSinceStartup + 2.5f;
		}

		public static void OnLevelUnloaded()
		{
			_rb = null;
			_peak = 0f;
			_landingUntil = 0f;
			_readyAt = float.MaxValue;
		}

		public static void ResetTracking()
		{
			_peak = 0f;
			_landingUntil = 0f;
		}

		public static void FixedTick()
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!Settings.Enabled || realtimeSinceStartup < _readyAt)
			{
				ResetTracking();
				return;
			}
			if (!TryGetVy(out var vy))
			{
				ResetTracking();
				return;
			}
			float num = Mathf.Max(0f, 0f - vy);
			if (_landingUntil > 0f)
			{
				if (num < _minDown)
				{
					_minDown = num;
				}
				if (realtimeSinceStartup >= _landingUntil)
				{
					float impact = _peak - _minDown;
					float peak = _peak;
					_peak = 0f;
					_landingUntil = 0f;
					Resolve(impact, peak);
				}
			}
			else
			{
				if (num > _peak)
				{
					_peak = num;
					_peakTime = realtimeSinceStartup;
				}
				if (_peak >= 5.25f && num < _peak - 2.5f)
				{
					_landingUntil = realtimeSinceStartup + 0.08f;
					_minDown = num;
				}
				else if (num < 0.5f && realtimeSinceStartup - _peakTime > 0.25f)
				{
					_peak = 0f;
				}
			}
		}

		private static void Resolve(float impact, float peakWas)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < _cooldownUntil || impact <= 7.5f)
			{
				return;
			}
			float num = (impact - 7.5f) / 14.5f;
			if (num < 0f)
			{
				num = 0f;
			}
			float multiplier = Settings.Multiplier;
			if (multiplier <= 0.001f)
			{
				return;
			}
			_cooldownUntil = realtimeSinceStartup + 0.6f;
			try
			{
				object obj = FindHealth();
				if (obj == null)
				{
					if (!_loggedNoHealth)
					{
						_loggedNoHealth = true;
						MelonLogger.Warning("[FallDamage] Player health object was not found - damage cannot be applied.");
					}
					return;
				}
				if (!_dumped)
				{
					DumpHealthType(obj);
				}
				object obj2 = Get(obj, "healthMode");
				if (obj2 != null && obj2.ToString().ToLowerInvariant().Contains("invinc"))
				{
					return;
				}
				float num2 = ToFloat(Get(obj, "max_Health"), 100f);
				if (num2 <= 0.01f)
				{
					num2 = 100f;
				}
				float num3 = ToFloat(Get(obj, "curr_Health"), num2);
				if (num3 <= 0f)
				{
					return;
				}
				object obj3 = Get(obj, "deathIsImminent");
				if (obj3 is bool && (bool)obj3)
				{
					return;
				}
				object obj4 = Get(obj, "alive");
				if (!(obj4 is bool) || (bool)obj4)
				{
					float num4 = num * multiplier * num2;
					if (!(num4 < 0.01f))
					{
						string text = Deal(obj, num4, num3);
						MelonLogger.Msg("[FallDamage] Landing: lost " + impact.ToString("F1") + " m/s (peak " + peakWas.ToString("F1") + " m/s), damage " + num4.ToString("F1") + " of " + num2.ToString("F0") + " via " + (text ?? "NOTHING (failed)"));
					}
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[FallDamage] Resolve error: " + ex);
			}
		}

		private static string Deal(object health, float amount, float curHp)
		{
			Type type = health.GetType();
			try
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (!string.Equals(methodInfo.Name, "TakeDamage", StringComparison.OrdinalIgnoreCase))
					{
						continue;
					}
					ParameterInfo[] parameters = methodInfo.GetParameters();
					if (parameters.Length == 1 && parameters[0].ParameterType == typeof(float))
					{
						methodInfo.Invoke(health, new object[1] { amount });
						if (Applied(health, curHp))
						{
							return "TakeDamage(float)";
						}
					}
				}
			}
			catch (Exception e)
			{
				MelonLogger.Warning("[FallDamage] TakeDamage(float) failed: " + Short(e));
			}
			try
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo2 in methods)
				{
					if (!string.Equals(methodInfo2.Name, "TakeDamage", StringComparison.OrdinalIgnoreCase))
					{
						continue;
					}
					ParameterInfo[] parameters2 = methodInfo2.GetParameters();
					if (parameters2.Length != 2 || !(parameters2[0].ParameterType == typeof(float)) || !parameters2[1].ParameterType.IsValueType)
					{
						continue;
					}
					object obj = BuildAttack(parameters2[1].ParameterType, amount);
					if (obj != null)
					{
						methodInfo2.Invoke(health, new object[2] { amount, obj });
						if (Applied(health, curHp))
						{
							return "TakeDamage(float, " + parameters2[1].ParameterType.Name + ")";
						}
					}
				}
			}
			catch (Exception e2)
			{
				MelonLogger.Warning("[FallDamage] TakeDamage(float, Attack) failed: " + Short(e2));
			}
			float value = Mathf.Max(0.01f, curHp - amount);
			if (!Set(health, "curr_Health", value))
			{
				return null;
			}
			return "curr_Health (no kill)";
		}

		private static bool Applied(object health, float before)
		{
			object obj = Get(health, "alive");
			if (obj is bool && !(bool)obj)
			{
				return true;
			}
			return ToFloat(Get(health, "curr_Health"), before) < before - 0.001f;
		}

		private static object BuildAttack(Type type, float amount)
		{
			try
			{
				object obj = Activator.CreateInstance(type);
				SetBoxed(obj, "damage", amount);
				PropertyInfo property = type.GetProperty("attackType", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.PropertyType.IsEnum)
				{
					string[] array = new string[3] { "Blunt", "Piercing", "None" };
					foreach (string value in array)
					{
						if (Enum.IsDefined(property.PropertyType, value))
						{
							property.SetValue(obj, Enum.Parse(property.PropertyType, value), null);
							break;
						}
					}
				}
				return obj;
			}
			catch (Exception e)
			{
				MelonLogger.Warning("[FallDamage] Could not build Attack: " + Short(e));
				return null;
			}
		}

		private static void SetBoxed(object o, string name, float value)
		{
			Type type = o.GetType();
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null && property.CanWrite)
			{
				property.SetValue(o, Convert.ChangeType(value, property.PropertyType), null);
				return;
			}
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				field.SetValue(o, Convert.ChangeType(value, field.FieldType));
			}
		}

		private static string Short(Exception e)
		{
			Exception ex = e.InnerException ?? e;
			return ex.GetType().Name + ": " + ex.Message;
		}

		private static object FindHealth()
		{
			RigManager rigManager = Player.RigManager;
			if ((Object)(object)rigManager == (Object)null)
			{
				return null;
			}
			object obj = Get(rigManager, "health");
			if (obj != null)
			{
				return obj;
			}
			PropertyInfo[] properties = ((object)rigManager).GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				try
				{
					if (propertyInfo.PropertyType.Name.IndexOf("Health", StringComparison.OrdinalIgnoreCase) >= 0 && propertyInfo.GetIndexParameters().Length == 0)
					{
						object value = propertyInfo.GetValue(rigManager, null);
						if (value != null)
						{
							return value;
						}
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static void DumpHealthType(object health)
		{
			_dumped = true;
			try
			{
				Type type = health.GetType();
				MelonLogger.Msg("[FallDamage] Health type: " + type.FullName + " (base: " + ((type.BaseType != null) ? type.BaseType.Name : "-") + ")");
				string text = "";
				PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (PropertyInfo propertyInfo in properties)
				{
					string text2 = "";
					try
					{
						if (propertyInfo.GetIndexParameters().Length == 0)
						{
							Type propertyType = propertyInfo.PropertyType;
							if (propertyType.IsPrimitive || propertyType.IsEnum || propertyType == typeof(string))
							{
								text2 = "=" + Convert.ToString(propertyInfo.GetValue(health, null));
							}
						}
					}
					catch
					{
					}
					text = text + propertyInfo.PropertyType.Name + " " + propertyInfo.Name + text2 + "; ";
				}
				MelonLogger.Msg("[FallDamage] props: " + text);
				string text3 = "";
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (!methodInfo.IsSpecialName && !(methodInfo.DeclaringType == typeof(object)))
					{
						string text4 = "";
						ParameterInfo[] parameters = methodInfo.GetParameters();
						foreach (ParameterInfo parameterInfo in parameters)
						{
							text4 = text4 + parameterInfo.ParameterType.Name + " " + parameterInfo.Name + ", ";
						}
						text3 = text3 + methodInfo.Name + "(" + text4 + "); ";
					}
				}
				MelonLogger.Msg("[FallDamage] methods: " + text3);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[FallDamage] Dump failed: " + ex.Message);
			}
		}

		private static bool TryGetVy(out float vy)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: 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)
			vy = 0f;
			Rigidbody body = GetBody();
			if ((Object)(object)body == (Object)null)
			{
				return false;
			}
			if (!_velSearched)
			{
				_velSearched = true;
				_velProp = typeof(Rigidbody).GetProperty("velocity") ?? typeof(Rigidbody).GetProperty("linearVelocity");
				if (_velProp == null)
				{
					MelonLogger.Error("[FallDamage] Rigidbody velocity property not found.");
				}
			}
			if (_velProp == null)
			{
				return false;
			}
			Vector3 val = (Vector3)_velProp.GetValue(body, null);
			vy = val.y;
			return true;
		}

		private static Rigidbody GetBody()
		{
			if ((Object)(object)_rb != (Object)null)
			{
				return _rb;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < _nextFind)
			{
				return null;
			}
			_nextFind = realtimeSinceStartup + 1f;
			try
			{
				PhysicsRig physicsRig = Player.PhysicsRig;
				if ((Object)(object)physicsRig == (Object)null)
				{
					return null;
				}
				Il2CppArrayBase<Rigidbody> componentsInChildren = ((Component)physicsRig).GetComponentsInChildren<Rigidbody>(true);
				if (componentsInChildren == null || componentsInChildren.Length == 0)
				{
					return null;
				}
				Rigidbody val = null;
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Rigidbody val2 = componentsInChildren[i];
					if (!((Object)(object)val2 == (Object)null) && ((Object)val2).name.IndexOf("pelvis", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						val = val2;
						break;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					for (int j = 0; j < componentsInChildren.Length; j++)
					{
						Rigidbody val3 = componentsInChildren[j];
						if (!((Object)(object)val3 == (Object)null) && ((Object)(object)val == (Object)null || val3.mass > val.mass))
						{
							val = val3;
						}
					}
				}
				_rb = val;
				if ((Object)(object)_rb != (Object)null && !_loggedBody)
				{
					_loggedBody = true;
					MelonLogger.Msg("[FallDamage] Tracking body: " + ((Object)_rb).name + " (mass " + _rb.mass.ToString("F1") + ")");
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[FallDamage] GetBody failed: " + ex.Message);
			}
			return _rb;
		}

		private static object Get(object o, string name)
		{
			if (o == null)
			{
				return null;
			}
			try
			{
				Type type = o.GetType();
				PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.GetIndexParameters().Length == 0)
				{
					return property.GetValue(o, null);
				}
				FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field.GetValue(o);
				}
			}
			catch
			{
			}
			return null;
		}

		private static bool Set(object o, string name, float value)
		{
			if (o == null)
			{
				return false;
			}
			try
			{
				Type type = o.GetType();
				PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.CanWrite)
				{
					property.SetValue(o, value, null);
					return true;
				}
				FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					field.SetValue(o, value);
					return true;
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[FallDamage] Set " + name + " failed: " + ex.Message);
			}
			return false;
		}

		private static float ToFloat(object o, float def)
		{
			if (o == null)
			{
				return def;
			}
			try
			{
				return Convert.ToSingle(o);
			}
			catch
			{
				return def;
			}
		}
	}
	public class Main : MelonMod
	{
		private float _nextErrorLog;

		public override void OnInitializeMelon()
		{
			Settings.Init();
			Hooking.OnLevelLoaded += delegate
			{
				FallManager.OnLevelLoaded();
			};
			Hooking.OnLevelUnloaded += FallManager.OnLevelUnloaded;
			Settings.BuildMenu();
			MelonLogger.Msg("FallDamage loaded.");
		}

		public override void OnFixedUpdate()
		{
			try
			{
				FallManager.FixedTick();
			}
			catch (Exception e)
			{
				LogErr(e);
			}
		}

		public override void OnUpdate()
		{
			try
			{
				Settings.Tick();
			}
			catch (Exception e)
			{
				LogErr(e);
			}
		}

		private void LogErr(Exception e)
		{
			if (Time.realtimeSinceStartup > _nextErrorLog)
			{
				_nextErrorLog = Time.realtimeSinceStartup + 5f;
				MelonLogger.Error("[FallDamage] tick error: " + e);
			}
		}
	}
	public static class Settings
	{
		public const float DefaultMultiplier = 1f;

		public static bool Enabled = true;

		public static float Multiplier = 1f;

		private static MelonPreferences_Category _cat;

		private static MelonPreferences_Entry<bool> _enabledEntry;

		private static MelonPreferences_Entry<float> _multEntry;

		private static BoolElement _enabledEl;

		private static FloatElement _multEl;

		private static bool _suppress;

		private static float _saveAt = -1f;

		public static void Init()
		{
			_cat = MelonPreferences.CreateCategory("FallDamage");
			_enabledEntry = _cat.CreateEntry<bool>("Enabled", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_multEntry = _cat.CreateEntry<float>("DamageMultiplier", 1f, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			Enabled = _enabledEntry.Value;
			Multiplier = Mathf.Clamp(_multEntry.Value, 0f, 10f);
		}

		public static void BuildMenu()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			Page obj = Page.Root.CreatePage("FallDamage", Color.red, 0, true);
			_enabledEl = obj.CreateBool("Enabled", Color.white, Enabled, (Action<bool>)delegate(bool v)
			{
				if (!_suppress)
				{
					Enabled = v;
					if (!v)
					{
						FallManager.ResetTracking();
					}
					Dirty();
				}
			});
			_multEl = obj.CreateFloat("Damage multiplier", Color.yellow, Multiplier, 0.1f, 0f, 10f, (Action<float>)delegate(float v)
			{
				if (!_suppress)
				{
					Multiplier = Mathf.Round(v * 100f) / 100f;
					Dirty();
				}
			});
			obj.CreateFunction("Reset multiplier to 1.0", Color.cyan, (Action)delegate
			{
				Multiplier = 1f;
				_suppress = true;
				try
				{
					_multEl.Value = 1f;
				}
				finally
				{
					_suppress = false;
				}
				Dirty();
			});
		}

		private static void Dirty()
		{
			_saveAt = Time.realtimeSinceStartup + 1.5f;
		}

		public static void Tick()
		{
			if (_saveAt > 0f && Time.realtimeSinceStartup >= _saveAt)
			{
				_saveAt = -1f;
				try
				{
					_enabledEntry.Value = Enabled;
					_multEntry.Value = Multiplier;
					MelonPreferences.Save();
				}
				catch (Exception ex)
				{
					MelonLogger.Warning("[FallDamage] Could not save settings: " + ex.Message);
				}
			}
		}
	}
}