Decompiled source of TacticalDamageScaling v1.0.1

TacticalDamageScaling.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Landfall.TABS;
using Microsoft.CodeAnalysis;
using UnityEngine;
using VelocityDamageRealistic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("TacticalDamageScaling")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TacticalDamageScaling")]
[assembly: AssemblyTitle("TacticalDamageScaling")]
[assembly: AssemblyVersion("1.0.0.0")]
[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;
		}
	}
}
[HarmonyPatch(typeof(PushStick), "Update")]
internal static class PushStickResistancePatch
{
	[HarmonyTranspiler]
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		MethodInfo forceWithPosition = AccessTools.Method(typeof(PushStickResistanceHelpers), "AddPushForceWithPosition", (Type[])null, (Type[])null);
		MethodInfo forceWithoutPosition = AccessTools.Method(typeof(PushStickResistanceHelpers), "AddPushForce", (Type[])null, (Type[])null);
		MethodInfo velocitySetter = AccessTools.Method(typeof(PushStickResistanceHelpers), "SetPushVelocity", (Type[])null, (Type[])null);
		foreach (CodeInstruction instruction in instructions)
		{
			MethodInfo calledMethod = instruction.operand as MethodInfo;
			if (calledMethod != null)
			{
				ParameterInfo[] parameters = calledMethod.GetParameters();
				if (calledMethod.DeclaringType == typeof(WilhelmPhysicsFunctions) && calledMethod.Name == "AddForceWithMinWeight")
				{
					if (parameters.Length == 5)
					{
						instruction.operand = forceWithPosition;
					}
					else if (parameters.Length == 4)
					{
						instruction.operand = forceWithoutPosition;
					}
				}
				else if (calledMethod.DeclaringType == typeof(Rigidbody) && calledMethod.Name == "set_velocity")
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = velocitySetter;
				}
			}
			yield return instruction;
		}
	}
}
internal static class PushStickResistanceHelpers
{
	private static Unit GetTargetUnit(Rigidbody rig)
	{
		if ((Object)(object)rig == (Object)null)
		{
			return null;
		}
		return ((Component)rig).GetComponentInParent<Unit>();
	}

	private static float GetResistance(Rigidbody rig)
	{
		Unit targetUnit = GetTargetUnit(rig);
		if ((Object)(object)targetUnit == (Object)null)
		{
			return 0f;
		}
		return UnitResistanceCalculator.GetUnitCostScore(targetUnit);
	}

	public static void AddPushForceWithPosition(Rigidbody rig, Vector3 force, Vector3 position, ForceMode forceMode, float minWeight)
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)rig == (Object)null))
		{
			Unit targetUnit = GetTargetUnit(rig);
			if ((Object)(object)targetUnit != (Object)null)
			{
				force *= UnitResistanceProfile.GetForceMultiplier(targetUnit, ResistanceSource.PushPull);
			}
			WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, position, forceMode, minWeight);
		}
	}

	public static void AddPushForce(Rigidbody rig, Vector3 force, ForceMode forceMode, float minWeight)
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)rig == (Object)null))
		{
			Unit targetUnit = GetTargetUnit(rig);
			if ((Object)(object)targetUnit != (Object)null)
			{
				force *= UnitResistanceProfile.GetForceMultiplier(targetUnit, ResistanceSource.PushPull);
			}
			WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, forceMode, minWeight);
		}
	}

	public static void SetPushVelocity(Rigidbody rig, Vector3 velocity)
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: 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)
		//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_0042: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)rig == (Object)null))
		{
			float resistance = GetResistance(rig);
			if (resistance > 0f)
			{
				Vector3 velocity2 = rig.velocity;
				velocity = velocity2 + (velocity - velocity2) * (1f - resistance);
			}
			rig.velocity = velocity;
		}
	}
}
[HarmonyPatch]
internal static class TelekinesisResistancePatch
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(Telekanesis), "Pull", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(Telekanesis), "Throw", (Type[])null, (Type[])null);
	}

	[HarmonyTranspiler]
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		MethodInfo forceMethod = AccessTools.Method(typeof(TelekinesisResistanceHelpers), "AddTelekinesisForce", (Type[])null, (Type[])null);
		MethodInfo dragMethod = AccessTools.Method(typeof(TelekinesisResistanceHelpers), "AddTelekinesisDrag", (Type[])null, (Type[])null);
		foreach (CodeInstruction instruction in instructions)
		{
			MethodInfo calledMethod = instruction.operand as MethodInfo;
			if (calledMethod != null)
			{
				if (calledMethod.DeclaringType == typeof(WilhelmPhysicsFunctions) && calledMethod.Name == "AddForceWithMinWeight" && calledMethod.GetParameters().Length == 4)
				{
					yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					instruction.operand = forceMethod;
				}
				else if (calledMethod.DeclaringType == typeof(Rigidbody) && calledMethod.Name == "AddForce" && calledMethod.GetParameters().Length == 2)
				{
					yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					instruction.opcode = OpCodes.Call;
					instruction.operand = dragMethod;
				}
			}
			yield return instruction;
		}
	}
}
internal static class TelekinesisResistanceHelpers
{
	private static Unit GetTargetUnit(Rigidbody rig)
	{
		if ((Object)(object)rig == (Object)null)
		{
			return null;
		}
		return ((Component)rig).GetComponentInParent<Unit>();
	}

	private static float GetResistance(Rigidbody rig)
	{
		Unit targetUnit = GetTargetUnit(rig);
		if ((Object)(object)targetUnit == (Object)null)
		{
			return 0f;
		}
		return UnitResistanceCalculator.GetUnitCostScore(targetUnit);
	}

	public static void AddTelekinesisForce(Rigidbody rig, Vector3 force, ForceMode forceMode, float minWeight, Telekanesis spell)
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)rig == (Object)null))
		{
			Unit targetUnit = GetTargetUnit(rig);
			if ((Object)(object)targetUnit != (Object)null)
			{
				force *= UnitResistanceProfile.GetForceMultiplier(targetUnit, ResistanceSource.Telekinesis);
			}
			WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, forceMode, minWeight);
		}
	}

	public static void AddTelekinesisDrag(Rigidbody rig, Vector3 force, ForceMode forceMode, Telekanesis spell)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)rig == (Object)null))
		{
			float resistance = GetResistance(rig);
			force *= 1f + resistance;
			rig.AddForce(force, forceMode);
		}
	}
}
namespace VelocityDamageRealistic
{
	internal static class CollisionDamageContext
	{
		[ThreadStatic]
		private static Unit currentAttacker;

		public static Unit CurrentAttacker => currentAttacker;

		public static Unit Set(Unit attacker)
		{
			Unit result = currentAttacker;
			if ((Object)(object)attacker != (Object)null)
			{
				currentAttacker = attacker;
			}
			return result;
		}

		public static void Restore(Unit previous)
		{
			currentAttacker = previous;
		}
	}
	internal static class ChickenSticksContextPatch
	{
		private static void Prefix(object __instance, out Unit __state)
		{
			__state = CollisionDamageContext.CurrentAttacker;
			Component val = (Component)((__instance is Component) ? __instance : null);
			if (!((Object)(object)val == (Object)null))
			{
				Unit component = ((Component)val.transform.root).GetComponent<Unit>();
				if ((Object)(object)component != (Object)null)
				{
					CollisionDamageContext.Set(component);
				}
			}
		}

		private static Exception Finalizer(Exception __exception, Unit __state)
		{
			CollisionDamageContext.Restore(__state);
			return __exception;
		}
	}
	[HarmonyPatch(typeof(CollisionWeapon), "OnCollisionEnter")]
	internal static class CollisionWeaponContextPatch
	{
		private static readonly FieldInfo OwnUnitField = AccessTools.Field(typeof(CollisionWeapon), "ownUnit");

		private static readonly FieldInfo ConnectedDataField = AccessTools.Field(typeof(CollisionWeapon), "connectedData");

		private static readonly Type HoldableType = AccessTools.TypeByName("Holdable");

		private static readonly FieldInfo HolderDataField = ((HoldableType == null) ? null : AccessTools.Field(HoldableType, "holderData"));

		private static void Prefix(CollisionWeapon __instance, out Unit __state)
		{
			__state = CollisionDamageContext.CurrentAttacker;
			Unit val = null;
			if (OwnUnitField != null)
			{
				object? value = OwnUnitField.GetValue(__instance);
				val = (Unit)((value is Unit) ? value : null);
			}
			if ((Object)(object)val == (Object)null)
			{
				TeamHolder component = ((Component)__instance).GetComponent<TeamHolder>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.spawner != (Object)null)
				{
					val = component.spawner.GetComponentInParent<Unit>();
				}
			}
			if ((Object)(object)val == (Object)null && ConnectedDataField != null)
			{
				object? value2 = ConnectedDataField.GetValue(__instance);
				DataHandler val2 = (DataHandler)((value2 is DataHandler) ? value2 : null);
				if ((Object)(object)val2 != (Object)null)
				{
					val = val2.unit;
				}
			}
			if ((Object)(object)val == (Object)null && HoldableType != null && HolderDataField != null)
			{
				Component component2 = ((Component)__instance).GetComponent(HoldableType);
				if ((Object)(object)component2 != (Object)null)
				{
					object? value3 = HolderDataField.GetValue(component2);
					DataHandler val3 = (DataHandler)((value3 is DataHandler) ? value3 : null);
					if ((Object)(object)val3 != (Object)null)
					{
						val = val3.unit;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)__instance).GetComponentInParent<Unit>();
			}
			if ((Object)(object)val != (Object)null)
			{
				CollisionDamageContext.Set(val);
			}
		}

		private static Exception Finalizer(Exception __exception, Unit __state)
		{
			CollisionDamageContext.Restore(__state);
			return __exception;
		}
	}
	[HarmonyPatch(typeof(HealthHandler), "TakeDamage")]
	internal static class CollisionDamageOwnerPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static void Prefix(ref Unit damager)
		{
			if (!((Object)(object)damager != (Object)null))
			{
				Unit currentAttacker = CollisionDamageContext.CurrentAttacker;
				if ((Object)(object)currentAttacker != (Object)null)
				{
					damager = currentAttacker;
				}
			}
		}
	}
	[HarmonyPatch(typeof(CollisionWeapon), "OnCollisionEnter")]
	internal static class CollisionWeaponResistancePatch
	{
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo forceMethod = AccessTools.Method(typeof(CollisionWeaponResistanceHelpers), "AddMeleeForce", (Type[])null, (Type[])null);
			MethodInfo velocityMethod = AccessTools.Method(typeof(CollisionWeaponResistanceHelpers), "SetMeleeVelocity", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				MethodInfo calledMethod = instruction.operand as MethodInfo;
				if (calledMethod != null)
				{
					if (calledMethod.DeclaringType == typeof(WilhelmPhysicsFunctions) && calledMethod.Name == "AddForceWithMinWeight" && calledMethod.GetParameters().Length == 4)
					{
						instruction.opcode = OpCodes.Call;
						instruction.operand = forceMethod;
					}
					else if (calledMethod.DeclaringType == typeof(Rigidbody) && calledMethod.Name == "set_velocity")
					{
						instruction.opcode = OpCodes.Call;
						instruction.operand = velocityMethod;
					}
				}
				yield return instruction;
			}
		}
	}
	internal static class CollisionWeaponResistanceHelpers
	{
		public static void AddMeleeForce(Rigidbody rig, Vector3 force, ForceMode forceMode, float minWeight)
		{
			//IL_0034: 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)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					float forceMultiplier = UnitResistanceProfile.GetForceMultiplier(componentInParent, ResistanceSource.Melee);
					force *= forceMultiplier;
				}
				WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, forceMode, minWeight);
			}
		}

		public static void SetMeleeVelocity(Rigidbody rig, Vector3 velocity)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					float unitCostScore = UnitResistanceCalculator.GetUnitCostScore(componentInParent);
					Vector3 velocity2 = rig.velocity;
					velocity = velocity2 + (velocity - velocity2) * (1f - unitCostScore);
				}
				rig.velocity = velocity;
			}
		}
	}
	[HarmonyPatch(typeof(ChangeTargetingType), "SetTargetFriendlyFor")]
	public static class CupidCharmScalingPatch
	{
		private class State
		{
			public float OriginalStopTime = 0f;

			public bool HasOriginalStopTime = false;

			public float ImmunityEndTime = 0f;
		}

		private static readonly bool DebugMode = false;

		private static readonly ConditionalWeakTable<ChangeTargetingType, State> _states = new ConditionalWeakTable<ChangeTargetingType, State>();

		[HarmonyPrefix]
		public static bool Prefix(ChangeTargetingType __instance, ref float f)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return true;
				}
				Unit component = ((Component)((Component)__instance).transform.root).GetComponent<Unit>();
				if ((Object)(object)component == (Object)null || (Object)(object)component.unitBlueprint == (Object)null)
				{
					return true;
				}
				float num = component.unitBlueprint.GetUnitCost(true);
				if (num <= 500f)
				{
					return true;
				}
				State value = _states.GetValue(__instance, (ChangeTargetingType _) => new State());
				float time = Time.time;
				if (time < value.ImmunityEndTime)
				{
					if (DebugMode)
					{
						Debug.Log((object)$"[VDR][CHARM] {((Object)component).name}(G:{num:F0}) đang MIỄN NHIỄM. Đã chặn Charm!");
					}
					return false;
				}
				float num2 = Mathf.InverseLerp(500f, 6000f, num);
				float num3 = Mathf.Pow(1f - num2, 3f);
				num3 = Mathf.Max(num3, 0.01f);
				f *= num3;
				if (__instance.stopAttacks)
				{
					if (__instance.setStopToEffectTime)
					{
						__instance.stopAttacksFor = f;
					}
					else
					{
						if (!value.HasOriginalStopTime)
						{
							value.OriginalStopTime = __instance.stopAttacksFor;
							value.HasOriginalStopTime = true;
						}
						__instance.stopAttacksFor = value.OriginalStopTime * num3;
					}
				}
				float num4 = Mathf.Lerp(1.5f, 5f, num2);
				float num5 = f * num4;
				num5 = Mathf.Max(num5, 2f);
				value.ImmunityEndTime = time + f + num5;
				if (DebugMode)
				{
					Debug.Log((object)($"[VDR][CHARM] {((Object)component).name}(G:{num:F0}) | " + $"Bị mê hoặc: {f:F2}s | Hồi phục: {num5:F2}s | " + $"Tổng miễn nhiễm: {f + num5:F2}s"));
				}
			}
			catch (Exception ex)
			{
				if (DebugMode)
				{
					Debug.LogWarning((object)("[VDR] Lỗi trong CupidCharmScalingPatch: " + ex));
				}
			}
			return true;
		}
	}
	public static class PriceScaling
	{
		public const float Sensitivity = 0.6f;

		public const float MaxFactor = 2.5f;

		public const float HighTierStart = 6000f;

		public const float HighTierFull = 7000f;

		public const float HighTierBonus = 0.5f;

		public const float HighTierDamageRef = 0.1f;

		private static readonly float L = Mathf.Log(2.5f);

		public static float Multiplier(float attackerCost, float victimCost, float baseDamage = 0f)
		{
			if (attackerCost <= 0f || victimCost <= 0f)
			{
				return 1f;
			}
			float num = 0.6f * Mathf.Log(attackerCost / victimCost);
			float num2 = Mathf.Exp(L * (float)Math.Tanh(num / L));
			num2 *= HighTier(attackerCost, baseDamage);
			if (float.IsNaN(num2) || float.IsInfinity(num2) || num2 <= 0f)
			{
				return 1f;
			}
			return num2;
		}

		private static float HighTier(float cost, float baseDamage)
		{
			float num = Mathf.Clamp01((cost - 6000f) / 1000f);
			float num2 = num * num * (3f - 2f * num);
			if (num2 <= 0f)
			{
				return 1f;
			}
			float num3 = 1f;
			if (baseDamage > 0f)
			{
				float num4 = baseDamage / (0.1f * cost);
				num3 = 1f / (1f + num4 * num4);
			}
			return 1f + 0.5f * num2 * num3;
		}
	}
	[HarmonyPatch(typeof(HealthHandler), "TakeDamage")]
	[HarmonyBefore(new string[] { "me.fern.damageIndicator" })]
	public static class DamageScalingPatch
	{
		private static readonly bool DebugMode = false;

		private static bool _hasLoggedVersion = false;

		private const float BurnDamageThreshold = 150f;

		private const float UnownedPriceExponent = 0.7f;

		private const float BurnRefHP = 1700f;

		private const float BurnHPExponent = 0.65f;

		private const float BurnDurabilityExponent = 2f;

		private const float MaxBurnMultiplier = 2.5f;

		private const float ExplosionVirtualCostMin = 600f;

		private const float ExplosionVirtualCostMax = 1200f;

		private const float MaxExplosionMultiplier = 1.5f;

		private const bool EnableSpecialBuffs = false;

		private static readonly Dictionary<string, float> SpecialUnitBuffs = new Dictionary<string, float> { { "crow", 2.5f } };

		private static readonly FieldRef<HealthHandler, DataHandler> GetDataHandlerRef = AccessTools.FieldRefAccess<HealthHandler, DataHandler>("data");

		[HarmonyPrefix]
		public static bool Prefix(HealthHandler __instance, ref float damage, Unit damager, DamageType damageType)
		{
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!_hasLoggedVersion && DebugMode)
				{
					_hasLoggedVersion = true;
					Debug.Log((object)"[VDR 6.7] BURN EXP 2.0 INITIALIZED.");
				}
				if ((Object)(object)__instance == (Object)null || damage <= 0f)
				{
					return true;
				}
				if (float.IsNaN(damage) || float.IsInfinity(damage))
				{
					return true;
				}
				if (DoTExecutionContextPatch.IsProcessingDoT)
				{
					return true;
				}
				Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent == (Object)null)
				{
					return true;
				}
				if (!TryGetUnitCost(componentInParent, out var cost))
				{
					return true;
				}
				DataHandler val = GetDataHandlerRef.Invoke(__instance);
				float num = damage;
				if ((Object)(object)damager == (Object)null)
				{
					float num2 = 1f;
					float num3 = (((Object)(object)val != (Object)null) ? val.maxHealth : 0f);
					float num5;
					float num7;
					if (num < 150f)
					{
						float num4 = Mathf.Clamp01((num - 20f) / 280f);
						num5 = Mathf.Lerp(300f, 5000f, num4);
						if (num5 <= 0f || cost <= 0f)
						{
							return true;
						}
						if (num3 > 0f && !float.IsNaN(num3) && !float.IsInfinity(num3))
						{
							num2 = Mathf.Pow(num3 / 1700f, 0.65f);
						}
						float num6 = Mathf.Pow(num5 / cost, 0.7f);
						num7 = Mathf.Min(num6 * num2, 2.5f);
						num7 *= Durability.Factor(componentInParent, cost, val, 2f);
					}
					else
					{
						float num8 = Mathf.Clamp01((num - 150f) / 350f);
						num5 = Mathf.Lerp(600f, 1200f, num8);
						if (num5 <= 0f || cost <= 0f)
						{
							return true;
						}
						float num9 = PriceScaling.Multiplier(num5, cost);
						num7 = Mathf.Min(num9, 1.5f);
						num7 *= Durability.Factor(componentInParent, cost, val);
					}
					float num10 = num * num7;
					if (float.IsNaN(num10) || float.IsInfinity(num10) || num10 < 0f)
					{
						return true;
					}
					damage = num10;
					if (DebugMode)
					{
						string text = ((num < 150f) ? "BURN" : "EXPLOSION");
						Debug.Log((object)$"[VDR 6.7][{text}] {((Object)componentInParent).name}(Cost:{cost:F0}, HP:{num3:F0}) | Virtual:{num5:F0} | Final x{num7:F3} | Type:{damageType} | Final:{damage:F1}");
					}
					return true;
				}
				if ((Object)(object)componentInParent == (Object)(object)damager)
				{
					return true;
				}
				if (!TryGetUnitCost(damager, out var cost2))
				{
					return true;
				}
				float num11 = PriceScaling.Multiplier(cost2, cost, num);
				float num12 = 1f;
				bool flag = false;
				float num13 = Durability.Factor(componentInParent, cost, val);
				float num14 = num * num11 * num12 * num13;
				if (float.IsNaN(num14) || float.IsInfinity(num14) || num14 < 0f)
				{
					return true;
				}
				damage = num14;
				if (DebugMode)
				{
					string text2 = ((num12 > 1f) ? $" | Special x{num12:F2}" : "");
					string text3 = ((cost2 >= 6000f) ? " | HIGH-TIER" : "");
					Debug.Log((object)$"[VDR 6.7][DIRECT] {((Object)damager).name}(Cost:{cost2:F0}, D:{num:F1}) -> {((Object)componentInParent).name}(Cost:{cost:F0}) | Mult x{num11:F3}{text2}{text3} | Dur x{num13:F3} | Type:{damageType} | Final:{damage:F1}");
				}
			}
			catch (Exception ex)
			{
				if (DebugMode)
				{
					Debug.LogWarning((object)("[VDR 6.7] Error: " + ex));
				}
			}
			return true;
		}

		private static bool TryGetUnitCost(Unit unit, out float cost)
		{
			cost = 0f;
			if ((Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null)
			{
				return false;
			}
			try
			{
				uint unitCost = unit.unitBlueprint.GetUnitCost(true);
				if (unitCost == 0)
				{
					return false;
				}
				cost = unitCost;
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(DamageOverTimeEffect), "AddDamage")]
	public static class DoTScalingPatch
	{
		public struct PatchState
		{
			public bool Modified;

			public float OriginalDamagePerStack;
		}

		private static readonly bool DebugMode = false;

		private const float StackDiminishing = 0.25f;

		private static readonly FieldRef<DamageOverTimeEffect, Unit> GetUnitRef = AccessTools.FieldRefAccess<DamageOverTimeEffect, Unit>("unit");

		private static readonly FieldRef<DamageOverTimeEffect, float> GetDamageToDoRef = AccessTools.FieldRefAccess<DamageOverTimeEffect, float>("damageToDo");

		private static readonly FieldRef<DamageOverTimeEffect, float> GetDamageDealtRef = AccessTools.FieldRefAccess<DamageOverTimeEffect, float>("damageDealtSinceLastStack");

		private static readonly FieldRef<DamageOverTimeEffect, float> GetDamageMultiplierRef = AccessTools.FieldRefAccess<DamageOverTimeEffect, float>("damageMultiplier");

		[HarmonyPrefix]
		public static void Prefix(DamageOverTimeEffect __instance, out PatchState __state)
		{
			__state = default(PatchState);
			try
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				TeamHolder componentInParent = ((Component)__instance).GetComponentInParent<TeamHolder>();
				Unit val = GetUnitRef.Invoke(__instance);
				if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent.spawner == (Object)null || (Object)(object)val == (Object)null)
				{
					return;
				}
				Unit component = componentInParent.spawner.GetComponent<Unit>();
				if ((Object)(object)component == (Object)null || (Object)(object)component == (Object)(object)val || !TryGetUnitCost(component, out var cost) || !TryGetUnitCost(val, out var cost2))
				{
					return;
				}
				float damagePerStack = __instance.damagePerStack;
				if (!(damagePerStack <= 0f))
				{
					float num = PriceScaling.Multiplier(cost, cost2);
					float num2 = GetDamageToDoRef.Invoke(__instance);
					float num3 = GetDamageDealtRef.Invoke(__instance);
					float num4 = Mathf.Max(0f, num2 - num3);
					float num5 = num4 / damagePerStack;
					float num6 = 1f / (1f + 0.25f * Mathf.Max(0f, num5));
					DataHandler component2 = ((Component)val).GetComponent<DataHandler>();
					float num7 = Durability.Factor(val, cost2, component2);
					float num8 = num * num6 * num7;
					__state.OriginalDamagePerStack = damagePerStack;
					__state.Modified = true;
					__instance.damagePerStack = damagePerStack * num8;
					if (!DebugMode)
					{
					}
				}
			}
			catch (Exception ex)
			{
				if (DebugMode)
				{
					Debug.LogWarning((object)("[VDR] DoT Error: " + ex));
				}
			}
		}

		[HarmonyFinalizer]
		public static Exception Finalizer(DamageOverTimeEffect __instance, PatchState __state, Exception __exception)
		{
			if (__state.Modified && (Object)(object)__instance != (Object)null)
			{
				__instance.damagePerStack = __state.OriginalDamagePerStack;
			}
			return __exception;
		}

		private static bool TryGetUnitCost(Unit unit, out float cost)
		{
			cost = 0f;
			if ((Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null)
			{
				return false;
			}
			try
			{
				uint unitCost = unit.unitBlueprint.GetUnitCost(true);
				if (unitCost == 0)
				{
					return false;
				}
				cost = unitCost;
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(DamageOverTimeEffect), "Update")]
	internal static class DoTExecutionContextPatch
	{
		private struct ContextState
		{
			public bool PreviousState;
		}

		internal static bool IsProcessingDoT;

		[HarmonyPrefix]
		private static void Prefix(out ContextState __state)
		{
			__state = new ContextState
			{
				PreviousState = IsProcessingDoT
			};
			IsProcessingDoT = true;
		}

		[HarmonyPostfix]
		private static void Postfix(ContextState __state)
		{
			IsProcessingDoT = __state.PreviousState;
		}
	}
	public static class Durability
	{
		public const float HPPerGold = 0.5f;

		public const float Exponent = 0.7f;

		public const float MinFactor = 0.25f;

		public const float CostStart = 1500f;

		public const float CostFull = 6000f;

		private static readonly HashSet<int> logged = new HashSet<int>();

		public static float Factor(Unit victim, float victimCost, DataHandler data, float exponent = 0.7f)
		{
			float hp = 0f;
			string reason;
			float result = Compute(victim, victimCost, data, exponent, out reason, out hp);
			if ((Object)(object)victim != (Object)null && logged.Count < 400 && logged.Add(((Object)victim).GetInstanceID()))
			{
				Debug.Log((object)("[VDR][DUR] " + ((Object)victim).name + " cost=" + victimCost.ToString("F0") + " hp=" + hp.ToString("F0") + " isRider=" + victim.IsRider + " factor=" + result.ToString("F3") + " (" + reason + ")"));
			}
			return result;
		}

		private static float Compute(Unit victim, float cost, DataHandler data, float exponent, out string reason, out float hp)
		{
			hp = 0f;
			if ((Object)(object)victim == (Object)null)
			{
				reason = "victim null";
				return 1f;
			}
			if ((Object)(object)data == (Object)null)
			{
				reason = "data null";
				return 1f;
			}
			hp = data.maxHealth;
			if (victim.IsRider)
			{
				reason = "rider, skipped";
				return 1f;
			}
			if (!(hp > 0f) || float.IsInfinity(hp))
			{
				reason = "bad hp";
				return 1f;
			}
			float num = 0.5f * cost;
			if (num <= 0f)
			{
				reason = "bad cost";
				return 1f;
			}
			float num2 = hp / num;
			if (num2 >= 1f)
			{
				reason = "hp ok";
				return 1f;
			}
			float num3 = Mathf.Clamp01((cost - 1500f) / 4500f);
			float num4 = num3 * num3 * (3f - 2f * num3);
			float num5 = Mathf.Pow(num2, exponent * num4);
			if (float.IsNaN(num5) || float.IsInfinity(num5))
			{
				reason = "nan";
				return 1f;
			}
			reason = "applied";
			return Mathf.Max(0.25f, num5);
		}
	}
	public static class EffectResistanceProfile
	{
		private const float MinResistance = 0.05f;

		private const float MaxResistance = 0.8f;

		private const float CostExponent = 0.7f;

		private const float HPReference = 10000f;

		private const float HPFullPenalty = 16000f;

		private const float MaxHPPenalty = 0.001f;

		public static float GetResistance(Unit unit)
		{
			float unitCostScore = UnitResistanceCalculator.GetUnitCostScore(unit);
			float num = 1f - Mathf.Pow(1f - Mathf.Clamp01(unitCostScore), 0.7f);
			float num2 = 0f;
			if ((Object)(object)unit != (Object)null && (Object)(object)unit.data != (Object)null)
			{
				num2 = unit.data.maxHealth;
			}
			float num3 = Mathf.Clamp01((num2 - 10000f) / 6000f);
			float num4 = 1f - 0.001f * num3;
			float num5 = 0.05f + 0.75f * num * num4;
			return Mathf.Clamp(num5, 0.05f, 0.8f);
		}

		public static float GetRemainingEffectMultiplier(Unit unit)
		{
			return 1f - GetResistance(unit);
		}
	}
	[HarmonyPatch(typeof(Explosion), "Explode")]
	internal static class ExplosionResistancePatch
	{
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo outwardMethod = AccessTools.Method(typeof(ExplosionResistanceHelpers), "AddExplosionForce", (Type[])null, (Type[])null);
			MethodInfo forwardMethod = AccessTools.Method(typeof(ExplosionResistanceHelpers), "AddForwardForce", (Type[])null, (Type[])null);
			MethodInfo velocityMethod = AccessTools.Method(typeof(ExplosionResistanceHelpers), "SetExplosionVelocity", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				MethodInfo calledMethod = instruction.operand as MethodInfo;
				if (calledMethod != null)
				{
					ParameterInfo[] parameters = calledMethod.GetParameters();
					if (calledMethod.DeclaringType == typeof(WilhelmPhysicsFunctions))
					{
						if (calledMethod.Name == "AddAxplosionForceWithMinWeight" && parameters.Length == 6)
						{
							instruction.operand = outwardMethod;
						}
						else if (calledMethod.Name == "AddForceWithMinWeight" && parameters.Length == 4)
						{
							instruction.operand = forwardMethod;
						}
					}
					else if (calledMethod.DeclaringType == typeof(Rigidbody) && calledMethod.Name == "set_velocity")
					{
						instruction.opcode = OpCodes.Call;
						instruction.operand = velocityMethod;
					}
				}
				yield return instruction;
			}
		}
	}
	internal static class ExplosionResistanceHelpers
	{
		private const float OriginalDamping = 0.9f;

		private const float MaximumDamping = 1f;

		private static float GetResistance(Unit unit)
		{
			return UnitResistanceCalculator.GetUnitCostScore(unit);
		}

		public static void AddExplosionForce(Rigidbody rig, float force, Vector3 position, float radius, ForceMode forceMode, float minWeight)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					float forceMultiplier = UnitResistanceProfile.GetForceMultiplier(componentInParent, ResistanceSource.Explosion);
					force *= forceMultiplier;
				}
				WilhelmPhysicsFunctions.AddAxplosionForceWithMinWeight(rig, force, position, radius, forceMode, minWeight);
			}
		}

		public static void AddForwardForce(Rigidbody rig, Vector3 force, ForceMode forceMode, float minWeight)
		{
			//IL_0034: 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)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					float forceMultiplier = UnitResistanceProfile.GetForceMultiplier(componentInParent, ResistanceSource.Explosion);
					force *= forceMultiplier;
				}
				WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, forceMode, minWeight);
			}
		}

		public static void SetExplosionVelocity(Rigidbody rig, Vector3 velocity)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					float resistance = GetResistance(componentInParent);
					float num = Mathf.Lerp(0.9f, 1f, resistance);
					float num2 = num / 0.9f;
					velocity *= num2;
				}
				rig.velocity = velocity;
			}
		}
	}
	public enum FrostbiteSource
	{
		Unknown,
		MeleeWeapon,
		Skill,
		Projectile
	}
	public static class FrostbiteSourceDetector
	{
		public static FrostbiteSource Detect(string stackTrace)
		{
			if (string.IsNullOrEmpty(stackTrace))
			{
				return FrostbiteSource.Unknown;
			}
			if (stackTrace.Contains("MeleeWeaponFreeze"))
			{
				return FrostbiteSource.MeleeWeapon;
			}
			if (stackTrace.Contains("AddEffectToRandomUnits") || stackTrace.Contains("ExplosionAddFewEffects") || stackTrace.Contains("Explosion"))
			{
				return FrostbiteSource.Skill;
			}
			if (stackTrace.Contains("Projectile") || stackTrace.Contains("Bullet"))
			{
				return FrostbiteSource.Projectile;
			}
			return FrostbiteSource.Unknown;
		}

		public static string GetTag(FrostbiteSource source)
		{
			return "";
		}
	}
	[HarmonyPatch("TGCore.Library.Effect_Frostbite, TGCore", "Add")]
	public static class FrostbiteResistancePatch
	{
		private const float MultiplierMelee = 0.22f;

		private const float MultiplierSkill = 2f;

		private const float MultiplierDefault = 0.25f;

		private const float BaselinePenalty = 0.85f;

		private const float CostStart = 500f;

		private const float CostMax = 6000f;

		private const float MinCostPenalty = 0.5f;

		private const float HpStart = 2000f;

		private const float HpMax = 8000f;

		private const float MinHpPenalty = 0.6f;

		private const float SkillPerHitMultiplier = 0.08f;

		private const float MaxSingleHit = 45f;

		[HarmonyPrefix]
		public static void Prefix(object __instance, ref float a, float ___HealthMultiplier, bool ___Done, object ___Data)
		{
			if (___Data == null || ___HealthMultiplier <= 0f || ___Done)
			{
				return;
			}
			Unit val = null;
			float num = 0f;
			try
			{
				Traverse val2 = Traverse.Create(___Data);
				val = val2.Field("unit").GetValue<Unit>();
				num = val2.Field("maxHealth").GetValue<float>();
			}
			catch
			{
			}
			if (!((Object)(object)val == (Object)null))
			{
				float num2 = a;
				string stackTrace = Environment.StackTrace;
				FrostbiteSource frostbiteSource = FrostbiteSourceDetector.Detect(stackTrace);
				float sourceMultiplier = GetSourceMultiplier(frostbiteSource);
				float num3 = GetUnitCost(val);
				if (num3 <= 0f && num > 0f)
				{
					num3 = num * 0.8f;
				}
				float num4 = 1f;
				if (num3 > 500f)
				{
					float num5 = Mathf.Clamp01((num3 - 500f) / 5500f);
					num4 = Mathf.Lerp(1f, 0.5f, num5);
				}
				float num6 = 1f;
				if (num > 2000f)
				{
					float num7 = Mathf.Clamp01((num - 2000f) / 6000f);
					num6 = Mathf.Lerp(1f, 0.6f, num7);
				}
				float num8 = 0.85f * num4 * num6;
				float resistance = EffectResistanceProfile.GetResistance(val);
				float num9 = num2 * (1f - resistance) * sourceMultiplier * num8;
				if (frostbiteSource == FrostbiteSource.Skill)
				{
					num9 *= 0.08f;
				}
				if (num9 > 45f)
				{
					num9 = 45f;
				}
				a = num9 / ___HealthMultiplier;
			}
		}

		private static float GetUnitCost(Unit unit)
		{
			if ((Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null)
			{
				return 0f;
			}
			try
			{
				return unit.unitBlueprint.GetUnitCost(true);
			}
			catch
			{
				return 0f;
			}
		}

		private static float GetSourceMultiplier(FrostbiteSource source)
		{
			return source switch
			{
				FrostbiteSource.MeleeWeapon => 0.22f, 
				FrostbiteSource.Skill => 2f, 
				_ => 0.25f, 
			};
		}
	}
	internal static class EffectPatchHelper
	{
		private static readonly ConditionalWeakTable<Component, Unit> UnitCache = new ConditionalWeakTable<Component, Unit>();

		private static readonly Dictionary<string, FieldInfo> FieldCache = new Dictionary<string, FieldInfo>();

		public static Unit GetUnit(Component component)
		{
			if ((Object)(object)component == (Object)null)
			{
				return null;
			}
			if (UnitCache.TryGetValue(component, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			Transform root = component.transform.root;
			Unit val = (((Object)(object)root != (Object)null) ? ((Component)root).GetComponentInChildren<Unit>() : null);
			if ((Object)(object)val != (Object)null)
			{
				UnitCache.Remove(component);
				UnitCache.Add(component, val);
			}
			return val;
		}

		public static float GetMultiplier(Unit unit)
		{
			return Mathf.Clamp(EffectResistanceProfile.GetRemainingEffectMultiplier(unit), 0.01f, 1f);
		}

		public static FieldInfo GetField(Type type, string name)
		{
			if (type == null || string.IsNullOrEmpty(name))
			{
				return null;
			}
			string key = type.AssemblyQualifiedName + "|" + name;
			lock (FieldCache)
			{
				if (FieldCache.TryGetValue(key, out var value))
				{
					return value;
				}
				value = AccessTools.Field(type, name);
				FieldCache.Add(key, value);
				return value;
			}
		}

		public static float GetFloat(object instance, string name)
		{
			if (instance == null)
			{
				return 0f;
			}
			FieldInfo field = GetField(instance.GetType(), name);
			if (field == null)
			{
				return 0f;
			}
			return (float)field.GetValue(instance);
		}

		public static void SetFloat(object instance, string name, float value)
		{
			if (instance != null)
			{
				FieldInfo field = GetField(instance.GetType(), name);
				if (field != null)
				{
					field.SetValue(instance, value);
				}
			}
		}

		public static void ApplyReducedAmount(Component instance, float originalAmount)
		{
			Unit unit = GetUnit(instance);
			if (!((Object)(object)unit == (Object)null))
			{
				float multiplier = GetMultiplier(unit);
				float num = GetFloat(instance, "amount");
				SetFloat(instance, "amount", originalAmount + (num - originalAmount) * multiplier);
			}
		}
	}
	[HarmonyPatch(typeof(FearEffect), "DoEffect")]
	internal static class FearDoEffectPatch
	{
		[HarmonyPrefix]
		public static void Prefix(FearEffect __instance, out float __state)
		{
			__state = EffectPatchHelper.GetFloat(__instance, "amount");
		}

		[HarmonyPostfix]
		public static void Postfix(FearEffect __instance, float __state)
		{
			EffectPatchHelper.ApplyReducedAmount((Component)(object)__instance, __state);
		}
	}
	[HarmonyPatch(typeof(FearEffect), "Ping")]
	internal static class FearPingPatch
	{
		[HarmonyPrefix]
		public static void Prefix(FearEffect __instance, out float __state)
		{
			__state = EffectPatchHelper.GetFloat(__instance, "amount");
		}

		[HarmonyPostfix]
		public static void Postfix(FearEffect __instance, float __state)
		{
			EffectPatchHelper.ApplyReducedAmount((Component)(object)__instance, __state);
		}
	}
	[HarmonyPatch(typeof(FearEffect), "Update")]
	internal static class FearUpdatePatch
	{
		[HarmonyPostfix]
		public static void Postfix(FearEffect __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Unit unit = EffectPatchHelper.GetUnit((Component)(object)__instance);
			if ((Object)(object)unit == (Object)null)
			{
				return;
			}
			float multiplier = EffectPatchHelper.GetMultiplier(unit);
			if (!(multiplier >= 1f))
			{
				float num = EffectPatchHelper.GetFloat(__instance, "counter");
				if (num < 7f)
				{
					float num2 = Time.deltaTime * 2f * (1f / multiplier - 1f);
					EffectPatchHelper.SetFloat(__instance, "counter", num + num2);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Effect_IceArrow), "Add")]
	internal static class IceArrowAddPatch
	{
		[HarmonyPrefix]
		public static bool Prefix(Effect_IceArrow __instance, ref float a)
		{
			Unit unit = EffectPatchHelper.GetUnit((Component)(object)__instance);
			if ((Object)(object)unit == (Object)null)
			{
				return true;
			}
			float num = Mathf.Clamp01(EffectResistanceProfile.GetResistance(unit));
			if (num >= 1f)
			{
				return false;
			}
			a *= 1f - num;
			return true;
		}
	}
	internal static class PotionPenaltyStorage
	{
		public sealed class PotionPenaltyState
		{
			public MovementHandler Move;

			public float OriginalMoveMultiplier;

			public StandingHandler Stand;

			public float OriginalStandOffset;

			public bool Restored;
		}

		public static readonly ConditionalWeakTable<PotionEffect, PotionPenaltyState> States = new ConditionalWeakTable<PotionEffect, PotionPenaltyState>();
	}
	[HarmonyPatch(typeof(PotionEffect), "Init")]
	internal static class PotionInitPatch
	{
		[HarmonyPrefix]
		public static void Prefix(PotionEffect __instance, out PotionPenaltyStorage.PotionPenaltyState __state)
		{
			__state = null;
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Unit unit = EffectPatchHelper.GetUnit((Component)(object)__instance);
			if (!((Object)(object)unit == (Object)null))
			{
				__state = PotionPenaltyStorage.States.GetValue(__instance, delegate
				{
					Transform root = ((Component)__instance).transform.root;
					MovementHandler componentInChildren = ((Component)root).GetComponentInChildren<MovementHandler>();
					StandingHandler componentInChildren2 = ((Component)root).GetComponentInChildren<StandingHandler>();
					return new PotionPenaltyStorage.PotionPenaltyState
					{
						Move = componentInChildren,
						OriginalMoveMultiplier = (((Object)(object)componentInChildren != (Object)null) ? componentInChildren.multiplier : 1f),
						Stand = componentInChildren2,
						OriginalStandOffset = (((Object)(object)componentInChildren2 != (Object)null) ? componentInChildren2.selfOffset : 0f)
					};
				});
			}
		}

		[HarmonyPostfix]
		public static void Postfix(PotionEffect __instance, PotionPenaltyStorage.PotionPenaltyState __state)
		{
			if ((Object)(object)__instance == (Object)null || __state == null)
			{
				return;
			}
			Unit unit = EffectPatchHelper.GetUnit((Component)(object)__instance);
			if (!((Object)(object)unit == (Object)null))
			{
				float multiplier = EffectPatchHelper.GetMultiplier(unit);
				float num = 1f - 0.1f * multiplier;
				float num2 = 0.025f * multiplier;
				if ((Object)(object)__state.Move != (Object)null)
				{
					__state.Move.multiplier = __state.OriginalMoveMultiplier * num;
				}
				if ((Object)(object)__state.Stand != (Object)null)
				{
					__state.Stand.selfOffset = __state.OriginalStandOffset + num2;
				}
				EffectPatchHelper.SetFloat(__instance, "removedMove", num);
				EffectPatchHelper.SetFloat(__instance, "removedStand", num2);
				__state.Restored = false;
			}
		}
	}
	[HarmonyPatch(typeof(PotionEffect), "DoEffect")]
	internal static class PotionDoEffectPatch
	{
		[HarmonyPrefix]
		public static void Prefix(PotionEffect __instance, out float __state)
		{
			__state = EffectPatchHelper.GetFloat(__instance, "amount");
		}

		[HarmonyPostfix]
		public static void Postfix(PotionEffect __instance, float __state)
		{
			EffectPatchHelper.ApplyReducedAmount((Component)(object)__instance, __state);
		}
	}
	[HarmonyPatch(typeof(PotionEffect), "Ping")]
	internal static class PotionPingPatch
	{
		[HarmonyPrefix]
		public static void Prefix(PotionEffect __instance, out float __state)
		{
			__state = EffectPatchHelper.GetFloat(__instance, "amount");
		}

		[HarmonyPostfix]
		public static void Postfix(PotionEffect __instance, float __state)
		{
			EffectPatchHelper.ApplyReducedAmount((Component)(object)__instance, __state);
		}
	}
	[HarmonyPatch(typeof(PotionEffect), "Update")]
	internal static class PotionUpdatePatch
	{
		[HarmonyPostfix]
		public static void Postfix(PotionEffect __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Unit unit = EffectPatchHelper.GetUnit((Component)(object)__instance);
			if ((Object)(object)unit == (Object)null)
			{
				return;
			}
			float multiplier = EffectPatchHelper.GetMultiplier(unit);
			if (multiplier < 1f)
			{
				float num = EffectPatchHelper.GetFloat(__instance, "counter");
				if (num <= 10f)
				{
					float num2 = Time.deltaTime * (1f / multiplier - 1f);
					EffectPatchHelper.SetFloat(__instance, "counter", num + num2);
				}
			}
			FieldInfo field = EffectPatchHelper.GetField(typeof(PotionEffect), "done");
			if (!(field == null) && (bool)field.GetValue(__instance) && PotionPenaltyStorage.States.TryGetValue(__instance, out var value) && !value.Restored)
			{
				if ((Object)(object)value.Move != (Object)null)
				{
					value.Move.multiplier = value.OriginalMoveMultiplier;
				}
				if ((Object)(object)value.Stand != (Object)null)
				{
					value.Stand.selfOffset = value.OriginalStandOffset;
				}
				value.Restored = true;
			}
		}
	}
	[HarmonyPatch(typeof(ProjectileHit), "AddForceToTarget")]
	internal static class ProjectileHitResistancePatch
	{
		private const float OriginalVelocityDamping = 0.7f;

		private const float MaximumVelocityDamping = 1f;

		private static void Prefix(Rigidbody rig, ref float m, out float __state)
		{
			__state = 0f;
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if (!((Object)(object)componentInParent == (Object)null))
				{
					__state = UnitResistanceCalculator.GetUnitCostScore(componentInParent);
					float forceMultiplier = UnitResistanceProfile.GetForceMultiplier(componentInParent, ResistanceSource.Projectile);
					m *= forceMultiplier;
				}
			}
		}

		private static void Postfix(Rigidbody rig, float __state)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null) && !(__state <= 0f))
			{
				float num = Mathf.Lerp(0.7f, 1f, __state);
				rig.velocity *= num / 0.7f;
			}
		}
	}
	[HarmonyPatch(typeof(PullStick), "LateUpdate")]
	internal static class PullStickResistancePatch
	{
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo forceMethod = AccessTools.Method(typeof(PullStickResistanceHelpers), "AddPullForce", (Type[])null, (Type[])null);
			MethodInfo velocityMethod = AccessTools.Method(typeof(PullStickResistanceHelpers), "SetPullVelocity", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				MethodInfo calledMethod = instruction.operand as MethodInfo;
				if (calledMethod != null)
				{
					if (calledMethod.DeclaringType == typeof(WilhelmPhysicsFunctions) && calledMethod.Name == "AddForceWithMinWeight" && calledMethod.GetParameters().Length == 4)
					{
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						instruction.opcode = OpCodes.Call;
						instruction.operand = forceMethod;
					}
					else if (calledMethod.DeclaringType == typeof(Rigidbody) && calledMethod.Name == "set_velocity")
					{
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						instruction.opcode = OpCodes.Call;
						instruction.operand = velocityMethod;
					}
				}
				yield return instruction;
			}
		}
	}
	internal static class PullStickResistanceHelpers
	{
		private static readonly FieldInfo StickField = AccessTools.Field(typeof(PullStick), "stick");

		private static readonly FieldInfo TargetRigField = AccessTools.Field(typeof(ProjectileStick), "targetRig");

		private static Rigidbody GetTargetRig(PullStick pullStick)
		{
			if ((Object)(object)pullStick == (Object)null || StickField == null || TargetRigField == null)
			{
				return null;
			}
			object value = StickField.GetValue(pullStick);
			if (value == null)
			{
				return null;
			}
			object? value2 = TargetRigField.GetValue(value);
			return (Rigidbody)((value2 is Rigidbody) ? value2 : null);
		}

		private static bool IsTargetRig(PullStick pullStick, Rigidbody rig)
		{
			if ((Object)(object)rig == (Object)null)
			{
				return false;
			}
			return (Object)(object)GetTargetRig(pullStick) == (Object)(object)rig;
		}

		private static Unit GetTargetUnit(Rigidbody rig)
		{
			if ((Object)(object)rig == (Object)null)
			{
				return null;
			}
			return ((Component)rig).GetComponentInParent<Unit>();
		}

		public static void AddPullForce(Rigidbody rig, Vector3 force, ForceMode forceMode, float minWeight, PullStick pullStick)
		{
			//IL_0040: 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)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)rig == (Object)null)
			{
				return;
			}
			if (IsTargetRig(pullStick, rig))
			{
				Unit targetUnit = GetTargetUnit(rig);
				if ((Object)(object)targetUnit != (Object)null)
				{
					force *= UnitResistanceProfile.GetForceMultiplier(targetUnit, ResistanceSource.PushPull);
				}
			}
			WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, forceMode, minWeight);
		}

		public static void SetPullVelocity(Rigidbody rig, Vector3 velocity, PullStick pullStick)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)rig == (Object)null)
			{
				return;
			}
			if (IsTargetRig(pullStick, rig))
			{
				Unit targetUnit = GetTargetUnit(rig);
				if ((Object)(object)targetUnit != (Object)null)
				{
					float unitCostScore = UnitResistanceCalculator.GetUnitCostScore(targetUnit);
					Vector3 velocity2 = rig.velocity;
					velocity = velocity2 + (velocity - velocity2) * (1f - unitCostScore);
				}
			}
			rig.velocity = velocity;
		}
	}
	[HarmonyPatch(typeof(StunEffect), "DoEffect")]
	internal static class StunEffectPatch
	{
		private sealed class AppliedResistanceState
		{
			public float Multiplier = 1f;
		}

		private static readonly ConditionalWeakTable<StunEffect, AppliedResistanceState> States = new ConditionalWeakTable<StunEffect, AppliedResistanceState>();

		[HarmonyPrefix]
		public static void Prefix(StunEffect __instance, out float __state)
		{
			__state = 1f;
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
			if (!((Object)(object)componentInParent == (Object)null))
			{
				AppliedResistanceState value = States.GetValue(__instance, (StunEffect _) => new AppliedResistanceState());
				__state = value.Multiplier;
				if (__state > 0f && __state < 1f)
				{
					__instance.stunTime /= __state;
				}
			}
		}

		[HarmonyPostfix]
		public static void Postfix(StunEffect __instance, float __state)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
			if (!((Object)(object)componentInParent == (Object)null))
			{
				float num = Mathf.Clamp(EffectResistanceProfile.GetRemainingEffectMultiplier(componentInParent), 0.01f, 1f);
				__instance.stunTime *= num;
				AppliedResistanceState value = States.GetValue(__instance, (StunEffect _) => new AppliedResistanceState());
				value.Multiplier = num;
			}
		}
	}
	public static class UnitResistanceCalculator
	{
		public const float MinCost = 30f;

		public const float MaxCost = 6000f;

		private const float ThresholdResistance = 0.7f;

		private const float RemainingResistance = 0.3f;

		private const float AbsoluteWeight = 0.7f;

		private const float RatioWeight = 0.3f;

		private const float AbsoluteExponent = 0.3f;

		private const float HighCostScale = 6000f;

		public static float CalculateCostScore(float unitCost)
		{
			if (float.IsNaN(unitCost) || float.IsInfinity(unitCost))
			{
				return 0f;
			}
			float num = Mathf.Max(unitCost, 30f);
			if (num <= 6000f)
			{
				float num2 = (num - 30f) / 5970f;
				float num3 = Mathf.Pow(num2, 0.3f);
				float num4 = Mathf.Log(num / 30f) / Mathf.Log(200f);
				float num5 = num3 * 0.7f + num4 * 0.3f;
				return Mathf.Clamp01(num5 * 0.7f);
			}
			float num6 = num - 6000f;
			float num7 = 1f - Mathf.Exp((0f - num6) / 6000f);
			float num8 = 0.7f + 0.3f * num7;
			return Mathf.Clamp01(num8);
		}

		public static float GetUnitCostScore(Unit unit)
		{
			if ((Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null)
			{
				return 0f;
			}
			float unitCost = unit.unitBlueprint.GetUnitCost(false);
			return CalculateCostScore(unitCost);
		}
	}
	public enum ResistanceSource
	{
		Melee,
		Projectile,
		Explosion,
		PushPull,
		Telekinesis,
		Whip
	}
	public static class UnitResistanceProfile
	{
		public static float GetMaxReduction(ResistanceSource source)
		{
			return 1f;
		}

		public static float GetForceMultiplier(Unit unit, ResistanceSource source)
		{
			float unitCostScore = UnitResistanceCalculator.GetUnitCostScore(unit);
			return Mathf.Clamp01(1f - unitCostScore);
		}
	}
	[BepInPlugin("com.tacticaldamage.scaling", "Tactical Damage Scaling", "1.0.0")]
	public class VelocityDamageRealisticPlugin : BaseUnityPlugin
	{
		private Harmony harmony;

		private bool patchesInstalled;

		private bool chickenSticksPatched;

		private void Awake()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[VDR] Plugin initialized.");
			harmony = new Harmony("com.velocitydamage.realistic");
		}

		private void Update()
		{
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Expected O, but got Unknown
			//IL_02d6: Expected O, but got Unknown
			if (!patchesInstalled)
			{
				Type type = AccessTools.TypeByName("TGCore.Library.Effect_Frostbite");
				Type type2 = AccessTools.TypeByName("TGCore.Library.MeleeWeaponFreeze");
				if (type == null || type2 == null)
				{
					return;
				}
				try
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"[VDR] Installing Groups A-C...");
					harmony.CreateClassProcessor(typeof(CollisionWeaponContextPatch)).Patch();
					harmony.CreateClassProcessor(typeof(CollisionDamageOwnerPatch)).Patch();
					harmony.CreateClassProcessor(typeof(CollisionWeaponResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(DamageScalingPatch)).Patch();
					harmony.CreateClassProcessor(typeof(DoTScalingPatch)).Patch();
					harmony.CreateClassProcessor(typeof(DoTExecutionContextPatch)).Patch();
					harmony.CreateClassProcessor(typeof(PushStickResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(PullStickResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(TelekinesisResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(WhipResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(ExplosionResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(ProjectileHitResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(FrostbiteResistancePatch)).Patch();
					harmony.CreateClassProcessor(typeof(CupidCharmScalingPatch)).Patch();
					patchesInstalled = true;
					((BaseUnityPlugin)this).Logger.LogInfo((object)"[VDR] Groups A-C installed successfully.");
				}
				catch (Exception ex)
				{
					patchesInstalled = true;
					((BaseUnityPlugin)this).Logger.LogError((object)"[VDR] Group A-C installation failed! Stopped to prevent lag.");
					((BaseUnityPlugin)this).Logger.LogError((object)ex.ToString());
				}
			}
			if (chickenSticksPatched)
			{
				return;
			}
			try
			{
				Type type3 = AccessTools.TypeByName("HiddenUnits.ChickenSticks");
				if (!(type3 == null))
				{
					MethodBase methodBase = AccessTools.Method(type3, "OnCollisionEnter", (Type[])null, (Type[])null);
					MethodInfo methodInfo = AccessTools.Method(typeof(ChickenSticksContextPatch), "Prefix", (Type[])null, (Type[])null);
					MethodInfo methodInfo2 = AccessTools.Method(typeof(ChickenSticksContextPatch), "Finalizer", (Type[])null, (Type[])null);
					if (!(methodBase == null) && !(methodInfo == null) && !(methodInfo2 == null))
					{
						harmony.Patch(methodBase, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null);
						chickenSticksPatched = true;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"[VDR] ChickenSticks installed.");
					}
				}
			}
			catch (Exception ex2)
			{
				chickenSticksPatched = true;
				((BaseUnityPlugin)this).Logger.LogError((object)"[VDR] ChickenSticks installation failed!");
				((BaseUnityPlugin)this).Logger.LogError((object)ex2.ToString());
			}
		}

		private void OnDestroy()
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	[HarmonyPatch(typeof(Whip), "AddForceToTarget")]
	internal static class WhipResistancePatch
	{
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo replacementMethod = AccessTools.Method(typeof(WhipResistanceHelpers), "AddWhipForce", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				MethodInfo calledMethod = instruction.operand as MethodInfo;
				if (calledMethod != null && calledMethod.DeclaringType == typeof(WilhelmPhysicsFunctions) && calledMethod.Name == "AddForceWithMinWeight" && calledMethod.GetParameters().Length == 4)
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = replacementMethod;
				}
				yield return instruction;
			}
		}
	}
	internal static class WhipResistanceHelpers
	{
		public static void AddWhipForce(Rigidbody rig, Vector3 force, ForceMode forceMode, float minWeight)
		{
			//IL_0034: 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)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)rig == (Object)null))
			{
				Unit componentInParent = ((Component)rig).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					float forceMultiplier = UnitResistanceProfile.GetForceMultiplier(componentInParent, ResistanceSource.Whip);
					force *= forceMultiplier;
				}
				WilhelmPhysicsFunctions.AddForceWithMinWeight(rig, force, forceMode, minWeight);
			}
		}
	}
}