Decompiled source of H44 Marksman Rework v1.0.0

H44_Marksman_Rework.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using EntityStates;
using EntityStates.Railgunner.Scope;
using EntityStates.Railgunner.Weapon;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using RoR2;
using RoR2.HudOverlay;
using RoR2.Skills;
using RoR2.UI;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("H44_Marksman_Rework")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("H44_Marksman_Rework")]
[assembly: AssemblyTitle("H44_Marksman_Rework")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.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 ExamplePlugin
{
	public class H44ViewerTag : MonoBehaviour
	{
	}
	[BepInPlugin("Sweptuu.H44_Marksman_Rework", "H44_Marksman_Rework", "1.0.0")]
	public class ExamplePlugin : BaseUnityPlugin
	{
		private delegate void orig_ModifyBullet(FireSnipeLight self, BulletAttack bulletAttack);

		private delegate void orig_SetDisplayedTargets(SniperTargetViewer self, IReadOnlyList<HurtBox> targets);

		private delegate void orig_Fire(BulletAttack self);

		private delegate bool orig_IsSniperTargetHit(in BulletHit hitInfo);

		public const string PluginGUID = "Sweptuu.H44_Marksman_Rework";

		public const string PluginAuthor = "Sweptuu";

		public const string PluginName = "H44_Marksman_Rework";

		public const string PluginVersion = "1.0.0";

		private const float WeakPointRange = 40f;

		private const float PrimaryDamageCoefficient = 2.5f;

		private static SkillDef snipeLightDef;

		private static GameObject scopedCrosshair;

		private static GameObject h44OverlayPrefab;

		private static readonly Dictionary<CharacterBody, OverrideRequest> crosshairRequests = new Dictionary<CharacterBody, OverrideRequest>();

		private static readonly Dictionary<CharacterBody, OverlayController> weakPointOverlays = new Dictionary<CharacterBody, OverlayController>();

		private static readonly List<HurtBox> filteredTargets = new List<HurtBox>();

		private static readonly FieldInfo viewerDictField = typeof(SniperTargetViewer).GetField("hurtBoxToVisualizer", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly HashSet<HurtBox> currentTargetSet = new HashSet<HurtBox>();

		private static readonly List<object> staleKeys = new List<object>();

		private static FieldInfo keyHurtBoxField;

		private static bool keyFieldSearched;

		private static readonly ConditionalWeakTable<BulletAttack, object> h44Bullets = new ConditionalWeakTable<BulletAttack, object>();

		private static bool firingH44Bullet;

		private static bool loggedFireConfig;

		private static Hook modifyBulletHook;

		private static Hook viewerHook;

		private static Hook fireHook;

		private static Hook sniperHitHook;

		public void Awake()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			Log.Init(((BaseUnityPlugin)this).Logger);
			RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(Setup));
			Language.onCurrentLanguageChanged += ApplyDescription;
			CharacterBody.onBodyStartGlobal += OnBodyStart;
			CharacterBody.onBodyDestroyGlobal += OnBodyDestroy;
			MethodInfo method = typeof(FireSnipeLight).GetMethod("ModifyBullet", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				modifyBulletHook = new Hook((MethodBase)method, typeof(ExamplePlugin).GetMethod("ModifyBullet_Hook", BindingFlags.Static | BindingFlags.NonPublic));
				Log.Info("FireSnipeLight.ModifyBullet hooked");
			}
			else
			{
				Log.Error("FireSnipeLight.ModifyBullet not found");
			}
			MethodInfo method2 = typeof(SniperTargetViewer).GetMethod("SetDisplayedTargets", BindingFlags.Instance | BindingFlags.NonPublic);
			if (method2 != null)
			{
				viewerHook = new Hook((MethodBase)method2, typeof(ExamplePlugin).GetMethod("SetDisplayedTargets_Hook", BindingFlags.Static | BindingFlags.NonPublic));
				Log.Info("SniperTargetViewer.SetDisplayedTargets hooked");
			}
			else
			{
				Log.Error("SniperTargetViewer.SetDisplayedTargets not found");
			}
			if (viewerDictField == null)
			{
				Log.Error("SniperTargetViewer.hurtBoxToVisualizer not found, markers may not reappear");
			}
			MethodInfo method3 = typeof(BulletAttack).GetMethod("Fire", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
			if (method3 != null)
			{
				fireHook = new Hook((MethodBase)method3, typeof(ExamplePlugin).GetMethod("Fire_Hook", BindingFlags.Static | BindingFlags.NonPublic));
				Log.Info("BulletAttack.Fire hooked");
			}
			else
			{
				Log.Error("BulletAttack.Fire not found");
			}
			MethodInfo method4 = typeof(BulletAttack).GetMethod("IsSniperTargetHit", BindingFlags.Static | BindingFlags.NonPublic);
			if (method4 != null)
			{
				sniperHitHook = new Hook((MethodBase)method4, typeof(ExamplePlugin).GetMethod("IsSniperTargetHit_Hook", BindingFlags.Static | BindingFlags.NonPublic));
				Log.Info("BulletAttack.IsSniperTargetHit hooked");
			}
			else
			{
				Log.Error("BulletAttack.IsSniperTargetHit not found");
			}
		}

		private static void Fire_Hook(orig_Fire orig, BulletAttack self)
		{
			bool flag = firingH44Bullet;
			firingH44Bullet = h44Bullets.TryGetValue(self, out var _);
			try
			{
				orig(self);
			}
			finally
			{
				firingH44Bullet = flag;
			}
		}

		private static bool IsSniperTargetHit_Hook(orig_IsSniperTargetHit orig, in BulletHit hitInfo)
		{
			bool flag = orig(in hitInfo);
			if (flag && firingH44Bullet && hitInfo.distance > 40f)
			{
				return false;
			}
			return flag;
		}

		private static void ModifyBullet_Hook(orig_ModifyBullet orig, FireSnipeLight self, BulletAttack bulletAttack)
		{
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Expected O, but got Unknown
			h44Bullets.GetOrCreateValue(bulletAttack);
			CharacterBody val = (Object.op_Implicit((Object)(object)bulletAttack.owner) ? bulletAttack.owner.GetComponent<CharacterBody>() : null);
			bool flag = Object.op_Implicit((Object)(object)val) && val.damage > 0f;
			float damage = (bulletAttack.damage = (flag ? (val.damage * 2.5f) : bulletAttack.damage));
			EntityStateMachine val2 = null;
			string customName = null;
			if (Object.op_Implicit((Object)(object)bulletAttack.owner))
			{
				EntityStateMachine[] components = bulletAttack.owner.GetComponents<EntityStateMachine>();
				foreach (EntityStateMachine val3 in components)
				{
					if (val3.customName == "Reload")
					{
						val2 = val3;
						break;
					}
				}
			}
			if (Object.op_Implicit((Object)(object)val2))
			{
				customName = val2.customName;
				val2.customName = "H44_HiddenReload";
			}
			try
			{
				orig(self, bulletAttack);
			}
			finally
			{
				if (Object.op_Implicit((Object)(object)val2))
				{
					val2.customName = customName;
				}
			}
			if (flag)
			{
				bulletAttack.damage = damage;
			}
			DamageTypeCombo damageType = bulletAttack.damageType;
			damageType.damageSource = (DamageSource)1;
			bulletAttack.damageType = damageType;
			if (!loggedFireConfig && flag)
			{
				loggedFireConfig = true;
				Log.Info($"H44 fire config: useSecondaryStocks={((BaseFireSnipe)self).useSecondaryStocks}, queueReload={((BaseFireSnipe)self).queueReload}, critDamageMultiplier={((BaseFireSnipe)self).critDamageMultiplier}, canAddIncrasePrimaryDamage={val.canAddIncrasePrimaryDamage}");
			}
			ModifyOutgoingDamageCallback original = bulletAttack.modifyOutgoingDamageCallback;
			bulletAttack.modifyOutgoingDamageCallback = (ModifyOutgoingDamageCallback)delegate(BulletAttack ba, ref BulletHit hit, DamageInfo damageInfo)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Invalid comparison between Unknown and I4
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				if (hit.isSniperHit && hit.distance > 40f)
				{
					hit.isSniperHit = false;
					if (!ba.isCrit)
					{
						damageInfo.crit = false;
					}
					if ((int)damageInfo.damageColorIndex == 12)
					{
						damageInfo.damageColorIndex = (DamageColorIndex)0;
					}
				}
				ModifyOutgoingDamageCallback obj = original;
				if (obj != null)
				{
					obj.Invoke(ba, ref hit, damageInfo);
				}
			};
		}

		private static void SetDisplayedTargets_Hook(orig_SetDisplayedTargets orig, SniperTargetViewer self, IReadOnlyList<HurtBox> targets)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			HUD componentInParent = ((Component)self).GetComponentInParent<HUD>();
			CharacterBody val = ((Object.op_Implicit((Object)(object)componentInParent) && Object.op_Implicit((Object)(object)componentInParent.targetMaster)) ? componentInParent.targetMaster.GetBody() : null);
			if (Object.op_Implicit((Object)(object)val) && IsH44Equipped(val))
			{
				bool flag = (Object)(object)((Component)self).GetComponent<H44ViewerTag>() != (Object)null;
				float num = 1600f;
				Vector3 corePosition = val.corePosition;
				filteredTargets.Clear();
				for (int i = 0; i < targets.Count; i++)
				{
					HurtBox val2 = targets[i];
					Vector3 val3 = ((Component)val2).transform.position - corePosition;
					float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
					if (flag ? (sqrMagnitude <= num) : (sqrMagnitude > num))
					{
						filteredTargets.Add(val2);
					}
				}
				targets = filteredTargets;
			}
			orig(self, targets);
			PurgeStaleEntries(self, targets);
		}

		private static void PurgeStaleEntries(SniperTargetViewer viewer, IReadOnlyList<HurtBox> displayed)
		{
			if (viewerDictField == null || !(viewerDictField.GetValue(viewer) is IDictionary { Count: not 0 } dictionary))
			{
				return;
			}
			if (!keyFieldSearched)
			{
				{
					IDictionaryEnumerator dictionaryEnumerator = dictionary.GetEnumerator();
					try
					{
						if (dictionaryEnumerator.MoveNext())
						{
							DictionaryEntry dictionaryEntry = (DictionaryEntry)dictionaryEnumerator.Current;
							keyFieldSearched = true;
							FieldInfo[] fields = dictionaryEntry.Key.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
							foreach (FieldInfo fieldInfo in fields)
							{
								if (typeof(HurtBox).IsAssignableFrom(fieldInfo.FieldType))
								{
									keyHurtBoxField = fieldInfo;
									break;
								}
							}
							Log.Info((keyHurtBoxField != null) ? ("Viewer key field found: " + keyHurtBoxField.Name) : "Viewer key field NOT found, markers may not reappear");
						}
					}
					finally
					{
						IDisposable disposable = dictionaryEnumerator as IDisposable;
						if (disposable != null)
						{
							disposable.Dispose();
						}
					}
				}
			}
			if (keyHurtBoxField == null)
			{
				return;
			}
			currentTargetSet.Clear();
			for (int j = 0; j < displayed.Count; j++)
			{
				currentTargetSet.Add(displayed[j]);
			}
			staleKeys.Clear();
			foreach (DictionaryEntry item in dictionary)
			{
				object? value = keyHurtBoxField.GetValue(item.Key);
				HurtBox val = (HurtBox)((value is HurtBox) ? value : null);
				if (!Object.op_Implicit((Object)(object)val) || !currentTargetSet.Contains(val))
				{
					staleKeys.Add(item.Key);
				}
			}
			for (int k = 0; k < staleKeys.Count; k++)
			{
				dictionary.Remove(staleKeys[k]);
			}
		}

		private static bool IsH44Equipped(CharacterBody body)
		{
			GenericSkill val = (Object.op_Implicit((Object)(object)body.skillLocator) ? body.skillLocator.primary : null);
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)snipeLightDef))
			{
				return (Object)(object)val.baseSkill == (Object)(object)snipeLightDef;
			}
			return false;
		}

		private void Setup()
		{
			AddSnipeLightVariant();
			GrabScopedCrosshairAndViewer();
			ApplyDescription();
		}

		private static void ApplyDescription()
		{
			if (!Object.op_Implicit((Object)(object)snipeLightDef))
			{
				return;
			}
			string skillDescriptionToken = snipeLightDef.skillDescriptionToken;
			string text = Language.GetString(skillDescriptionToken);
			if (!string.IsNullOrEmpty(text) && !(text == skillDescriptionToken))
			{
				string text2 = text.Replace("400%", "250%");
				if (!text2.Contains("40m"))
				{
					text2 += " Highlight <style=cIsDamage>Weak Points</style> within a <style=cIsDamage>40m</style> radius.";
				}
				Language.currentLanguage.SetStringByToken(skillDescriptionToken, text2);
			}
		}

		private void AddSnipeLightVariant()
		{
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Expected O, but got Unknown
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = BodyCatalog.FindBodyPrefab("RailgunnerBody");
			SkillDef[] array = Resources.FindObjectsOfTypeAll<SkillDef>();
			foreach (SkillDef val2 in array)
			{
				if (val2.skillName == "SnipeLight")
				{
					snipeLightDef = val2;
					break;
				}
			}
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)snipeLightDef))
			{
				Log.Error("Setup failed: RailgunnerBody or SnipeLight not found");
				return;
			}
			GenericSkill val3 = null;
			UnlockableDef val4 = null;
			GenericSkill[] components = val.GetComponents<GenericSkill>();
			foreach (GenericSkill val5 in components)
			{
				if (val5.skillName == "FirePistol")
				{
					val3 = val5;
				}
				else
				{
					if (!(val5.skillName == "FireFMJ"))
					{
						continue;
					}
					List<Variant> list = new List<Variant>();
					Variant[] variants = val5.skillFamily.variants;
					foreach (Variant val6 in variants)
					{
						if (Object.op_Implicit((Object)(object)val6.skillDef) && val6.skillDef.skillName == "ScopeLight")
						{
							val4 = val6.unlockableDef;
						}
						else
						{
							list.Add(val6);
						}
					}
					val5.skillFamily.variants = list.ToArray();
					Log.Info("Removed ScopeLight from the secondary slot");
				}
			}
			if ((Object)(object)val3 == (Object)null)
			{
				Log.Error("Primary slot FirePistol not found");
				return;
			}
			SkillFamily skillFamily = val3.skillFamily;
			Array.Resize(ref skillFamily.variants, skillFamily.variants.Length + 1);
			Variant[] variants2 = skillFamily.variants;
			int num = skillFamily.variants.Length - 1;
			Variant val7 = new Variant
			{
				skillDef = snipeLightDef,
				unlockableDef = val4
			};
			((Variant)(ref val7)).viewableNode = new Node(snipeLightDef.skillNameToken, false, (Node)null);
			variants2[num] = val7;
			Log.Info("Added SnipeLight as a primary variant (unlock: " + (Object.op_Implicit((Object)(object)val4) ? val4.cachedName : "none") + ")");
		}

		private void GrabScopedCrosshairAndViewer()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			EntityState obj = EntityStateCatalog.InstantiateState(typeof(ActiveScopeLight));
			BaseScopeState val = (BaseScopeState)(object)((obj is BaseScopeState) ? obj : null);
			if (val == null)
			{
				Log.Error("Could not instantiate ActiveScopeLight");
				return;
			}
			scopedCrosshair = val.crosshairOverridePrefab;
			Log.Info(Object.op_Implicit((Object)(object)scopedCrosshair) ? "Got scoped crosshair" : "Scoped crosshair not found");
			SniperTargetViewer val2 = (Object.op_Implicit((Object)(object)val.scopeOverlayPrefab) ? val.scopeOverlayPrefab.GetComponentInChildren<SniperTargetViewer>(true) : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				Log.Error("SniperTargetViewer not found in the scope overlay prefab");
				return;
			}
			GameObject val3 = new GameObject("H44WeakPointHolder");
			val3.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)val3);
			h44OverlayPrefab = new GameObject("H44WeakPointOverlay", new Type[1] { typeof(RectTransform) });
			h44OverlayPrefab.transform.SetParent(val3.transform, false);
			Stretch(h44OverlayPrefab.GetComponent<RectTransform>());
			GameObject obj2 = Object.Instantiate<GameObject>(((Component)val2).gameObject, h44OverlayPrefab.transform, false);
			obj2.AddComponent<H44ViewerTag>();
			Stretch(obj2.GetComponent<RectTransform>());
			Log.Info("Created H44 weak point overlay prefab");
		}

		private static void Stretch(RectTransform rect)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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)
			if (Object.op_Implicit((Object)(object)rect))
			{
				rect.anchorMin = Vector2.zero;
				rect.anchorMax = Vector2.one;
				rect.offsetMin = Vector2.zero;
				rect.offsetMax = Vector2.zero;
			}
		}

		private void OnBodyStart(CharacterBody body)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)snipeLightDef) || body.baseNameToken != "RAILGUNNER_BODY_NAME")
			{
				return;
			}
			GenericSkill val = (Object.op_Implicit((Object)(object)body.skillLocator) ? body.skillLocator.primary : null);
			if (Object.op_Implicit((Object)(object)val) && !((Object)(object)val.skillDef != (Object)(object)snipeLightDef))
			{
				if (Object.op_Implicit((Object)(object)scopedCrosshair))
				{
					crosshairRequests[body] = CrosshairUtils.RequestOverrideForBody(body, scopedCrosshair, (OverridePriority)1);
				}
				if (Object.op_Implicit((Object)(object)h44OverlayPrefab))
				{
					weakPointOverlays[body] = HudOverlayManager.AddOverlay(((Component)body).gameObject, new OverlayCreationParams
					{
						prefab = h44OverlayPrefab,
						childLocatorEntry = "ScopeContainer"
					});
				}
			}
		}

		private void OnBodyDestroy(CharacterBody body)
		{
			if (crosshairRequests.TryGetValue(body, out var value))
			{
				if (value != null)
				{
					value.Dispose();
				}
				crosshairRequests.Remove(body);
			}
			if (!weakPointOverlays.TryGetValue(body, out var value2))
			{
				return;
			}
			try
			{
				if (value2 != null)
				{
					HudOverlayManager.RemoveOverlay(value2);
				}
			}
			catch (Exception ex)
			{
				Log.Warning("Removing weak point overlay failed: " + ex.Message);
			}
			weakPointOverlays.Remove(body);
		}
	}
	internal static class Log
	{
		private static ManualLogSource _logSource;

		internal static void Init(ManualLogSource logSource)
		{
			_logSource = logSource;
		}

		internal static void Debug(object data)
		{
			_logSource.LogDebug(data);
		}

		internal static void Error(object data)
		{
			_logSource.LogError(data);
		}

		internal static void Fatal(object data)
		{
			_logSource.LogFatal(data);
		}

		internal static void Info(object data)
		{
			_logSource.LogInfo(data);
		}

		internal static void Message(object data)
		{
			_logSource.LogMessage(data);
		}

		internal static void Warning(object data)
		{
			_logSource.LogWarning(data);
		}
	}
}