Decompiled source of ModulUnderbarrelM26MASS v1.0.0

ModulUnderbarrelM26MASS.dll

Decompiled 15 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using FistVR;
using HarmonyLib;
using ModularWorkshop;
using OpenScripts2;
using OtherLoader;
using Sodalite.Api;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public class MagLatchCollisionForwarder : MonoBehaviour
{
	public ModulPhysicalMagReleaseLatch Target;

	private void OnCollisionStay(Collision col)
	{
		if ((Object)(object)Target != (Object)null)
		{
			Target.ReportCollision(col);
		}
	}
}
public class ModulPhysicalMagReleaseLatch : MonoBehaviour, IPartFireArmRequirement
{
	private FVRFireArm _fireArm;

	public HingeJoint Joint;

	public float Threshold = -35f;

	private float timeSinceLastCollision = 6f;

	private Vector3 _connectedAnchor;

	private bool _hasStoredAnchor;

	public FVRFireArm FireArm
	{
		get
		{
			return _fireArm;
		}
		set
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			_fireArm = value;
			if ((Object)(object)Joint == (Object)null)
			{
				Joint = ((Component)this).GetComponentInChildren<HingeJoint>();
			}
			if ((Object)(object)_fireArm != (Object)null && (Object)(object)((FVRPhysicalObject)_fireArm).RootRigidbody != (Object)null && _hasStoredAnchor)
			{
				((Joint)Joint).autoConfigureConnectedAnchor = false;
				((Joint)Joint).connectedAnchor = _connectedAnchor;
				((Joint)Joint).connectedBody = ((FVRPhysicalObject)_fireArm).RootRigidbody;
			}
			else if ((Object)(object)Joint != (Object)null)
			{
				((Joint)Joint).connectedBody = null;
			}
		}
	}

	private void Awake()
	{
		//IL_00ad: 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)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)Joint == (Object)null)
		{
			Joint = ((Component)this).GetComponentInChildren<HingeJoint>();
		}
		if ((Object)(object)Joint != (Object)null)
		{
			MagLatchCollisionForwarder magLatchCollisionForwarder = ((Component)Joint).gameObject.GetComponent<MagLatchCollisionForwarder>();
			if ((Object)(object)magLatchCollisionForwarder == (Object)null)
			{
				magLatchCollisionForwarder = ((Component)Joint).gameObject.AddComponent<MagLatchCollisionForwarder>();
			}
			magLatchCollisionForwarder.Target = this;
		}
		FVRFireArm componentInParent = ((Component)this).GetComponentInParent<FVRFireArm>();
		if ((Object)(object)componentInParent != (Object)null && (Object)(object)((FVRPhysicalObject)componentInParent).RootRigidbody != (Object)null && (Object)(object)Joint != (Object)null)
		{
			Vector3 val = ((Component)Joint).transform.TransformPoint(((Joint)Joint).anchor);
			_connectedAnchor = ((Component)((FVRPhysicalObject)componentInParent).RootRigidbody).transform.InverseTransformPoint(val);
			_hasStoredAnchor = true;
		}
	}

	private void FixedUpdate()
	{
		if (!((Object)(object)_fireArm == (Object)null) && !((Object)(object)Joint == (Object)null))
		{
			if (timeSinceLastCollision < 5f)
			{
				timeSinceLastCollision += Time.deltaTime;
			}
			if ((Object)(object)_fireArm.Magazine != (Object)null && timeSinceLastCollision < 0.03f && Joint.angle < Threshold)
			{
				_fireArm.EjectMag(true);
			}
		}
	}

	public void ReportCollision(Collision col)
	{
		if (!((Object)(object)_fireArm == (Object)null) && !((Object)(object)col.collider.attachedRigidbody == (Object)null) && !((Object)(object)col.collider.attachedRigidbody == (Object)(object)((FVRPhysicalObject)_fireArm).RootRigidbody))
		{
			FVRPhysicalObject component = ((Component)col.collider.attachedRigidbody).gameObject.GetComponent<FVRPhysicalObject>();
			if ((Object)(object)component != (Object)null && ((FVRInteractiveObject)component).IsHeld)
			{
				timeSinceLastCollision = 0f;
			}
		}
	}
}
public class EjectionChanger : MonoBehaviour, IPartFireArmRequirement
{
	[Header("Ejection Config")]
	public Vector3 NewEjectionSpeed;

	public Vector3 NewEjectionSpin;

	private Vector3 _origEjectionSpeed;

	private Vector3 _origEjectionSpin;

	private ClosedBoltWeapon _ejectionFirearm;

	public FVRFireArm FireArm
	{
		get
		{
			return (FVRFireArm)(object)_ejectionFirearm;
		}
		set
		{
			if ((Object)(object)_ejectionFirearm != (Object)null)
			{
				RemoveEjection();
			}
			ClosedBoltWeapon val = (ClosedBoltWeapon)(object)((value is ClosedBoltWeapon) ? value : null);
			if ((Object)(object)val != (Object)null)
			{
				ApplyEjection(val);
			}
			else
			{
				_ejectionFirearm = null;
			}
		}
	}

	private void ApplyEjection(ClosedBoltWeapon firearm)
	{
		//IL_0025: 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_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_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)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		_ejectionFirearm = firearm;
		if (!((Object)(object)_ejectionFirearm == (Object)null))
		{
			_origEjectionSpeed = _ejectionFirearm.EjectionSpeed;
			_origEjectionSpin = _ejectionFirearm.EjectionSpin;
			_ejectionFirearm.EjectionSpeed = NewEjectionSpeed;
			_ejectionFirearm.EjectionSpin = NewEjectionSpin;
			Debug.Log((object)"EjectionChanger: Applying new ejection values.");
		}
	}

	private void RemoveEjection()
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: 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)
		Debug.Log((object)"EjectionChanger: Reverting ejection values.");
		if (!((Object)(object)_ejectionFirearm == (Object)null))
		{
			_ejectionFirearm.EjectionSpeed = _origEjectionSpeed;
			_ejectionFirearm.EjectionSpin = _origEjectionSpin;
			_ejectionFirearm = null;
		}
	}
}
namespace Volks.ModulUnderbarrelM26MASS;

[BepInPlugin("Volks.ModulUnderbarrelM26MASS", "ModulUnderbarrelM26MASS", "1.0.0")]
[BepInProcess("h3vr.exe")]
[Description("Built with MeatKit")]
[BepInDependency("h3vr.otherloader", "1.3.0")]
[BepInDependency("h3vr.cityrobo.ModularWorkshopManager", "1.0.0")]
[BepInDependency("nrgill28.Sodalite", "1.4.2")]
public class ModulUnderbarrelM26MASSPlugin : BaseUnityPlugin
{
	private static readonly string BasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

	internal static ManualLogSource Logger;

	private void Awake()
	{
		Logger = ((BaseUnityPlugin)this).Logger;
		LoadAssets();
	}

	private void LoadAssets()
	{
		Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "Volks.ModulUnderbarrelM26MASS");
		OtherLoader.RegisterDirectLoad(BasePath, "Volks.ModulUnderbarrelM26MASS", "", "", "modulunderbarrelm26_receiver", "");
		GameAPI.PreloadAllAssets(Path.Combine(BasePath, "mw_modulunderbarrelm26mass"));
	}
}
public class ForwardAssist : FVRInteractiveObject
{
	[Header("Animation Settings")]
	public Transform TargetTransform;

	public Vector3 StartPosition;

	public Vector3 EndPosition;

	public Vector3 StartRotation;

	public Vector3 EndRotation;

	public float MoveSpeed = 10f;

	public float ResetDelay = 0.2f;

	[Header("Audio Settings")]
	public AudioEvent PokeAudioEvent;

	public FVRPooledAudioType AudioType = (FVRPooledAudioType)0;

	private float m_animFloat = 0f;

	private bool m_isPoked = false;

	private float m_resetTimer = 0f;

	protected void Awake()
	{
		//IL_0025: 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_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: 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_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		((FVRInteractiveObject)this).Awake();
		if ((Object)(object)TargetTransform == (Object)null)
		{
			TargetTransform = ((Component)this).transform;
		}
		if (StartPosition == Vector3.zero)
		{
			StartPosition = TargetTransform.localPosition;
		}
		if (StartRotation == Vector3.zero)
		{
			StartRotation = TargetTransform.localEulerAngles;
		}
	}

	public override void Poke(FVRViveHand hand)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		if (PokeAudioEvent != null)
		{
			SM.PlayCoreSound(AudioType, PokeAudioEvent, ((Component)this).transform.position);
		}
		m_isPoked = true;
		m_resetTimer = ResetDelay;
	}

	private void Update()
	{
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		if (m_isPoked)
		{
			m_animFloat = Mathf.MoveTowards(m_animFloat, 1f, Time.deltaTime * MoveSpeed);
			m_resetTimer -= Time.deltaTime;
			if (m_resetTimer <= 0f)
			{
				m_isPoked = false;
			}
		}
		else
		{
			m_animFloat = Mathf.MoveTowards(m_animFloat, 0f, Time.deltaTime * MoveSpeed);
		}
		if ((Object)(object)TargetTransform != (Object)null)
		{
			TargetTransform.localPosition = Vector3.Lerp(StartPosition, EndPosition, m_animFloat);
			TargetTransform.localEulerAngles = Vector3.Lerp(StartRotation, EndRotation, m_animFloat);
		}
	}
}
public class ModularSubPartOverride : MonoBehaviour
{
	[Serializable]
	public class SubPartOverrideRule
	{
		[Tooltip("The ModularPartsGroupID of the sub-attachment point to override (e.g. GasBlocks_AR).")]
		public string TargetSubGroupID;

		[Tooltip("The exact Name of the modular part you want to force-select for this sub-point.")]
		public string DesiredPartName;

		[Tooltip("Optional: If specified, this override only triggers if the parent part matches this name. Leave empty to apply to any parent part.")]
		public string OnlyWhenParentPartIs;
	}

	[Tooltip("Enables verbose console logging for debugging.")]
	public bool EnableDebugLogging = false;

	[Tooltip("If true, will not overwrite parts restored from a player's Vault save file.")]
	public bool RespectVaultSaves = true;

	[Tooltip("Rules defining which sub-attachment points to override with your chosen parts.")]
	public SubPartOverrideRule[] Overrides = new SubPartOverrideRule[0];

	private IModularWeapon m_modularWeapon;

	private ModularFVRFireArm m_modularFireArm;

	private ModularFVRPhysicalObject m_modularPhysicalObject;

	private bool m_hasSubscribed;

	private bool m_isApplyingOverride;

	public void Awake()
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Expected O, but got Unknown
		Component val = ((Component)this).GetComponent(typeof(IModularWeapon));
		if ((Object)(object)val == (Object)null)
		{
			val = ((Component)this).GetComponentInChildren(typeof(IModularWeapon));
		}
		if ((Object)(object)val != (Object)null)
		{
			m_modularWeapon = (IModularWeapon)val;
			m_modularFireArm = m_modularWeapon.GetModularFVRFireArm;
		}
		if (m_modularFireArm == null)
		{
			m_modularPhysicalObject = ((Component)this).GetComponent<ModularFVRPhysicalObject>();
			if ((Object)(object)m_modularPhysicalObject == (Object)null)
			{
				m_modularPhysicalObject = ((Component)this).GetComponentInChildren<ModularFVRPhysicalObject>();
			}
		}
		if (m_modularFireArm == null && (Object)(object)m_modularPhysicalObject == (Object)null)
		{
			Debug.LogError((object)"[ModularSubPartOverride] Fatal: Neither IModularWeapon (ModularFVRFireArm) nor ModularFVRPhysicalObject found on GameObject or children!");
		}
		else
		{
			if (m_hasSubscribed)
			{
				return;
			}
			if (m_modularFireArm != null)
			{
				m_modularFireArm.PartAdded += new PartAdded(OnPartAdded);
				m_hasSubscribed = true;
				if (EnableDebugLogging)
				{
					Debug.Log((object)"[ModularSubPartOverride] Subscribed to ModularFVRFireArm.PartAdded event.");
				}
			}
			else if ((Object)(object)m_modularPhysicalObject != (Object)null)
			{
				m_modularPhysicalObject.PartAdded += new PartAdded(OnPartAdded);
				m_hasSubscribed = true;
				if (EnableDebugLogging)
				{
					Debug.Log((object)"[ModularSubPartOverride] Subscribed to ModularFVRPhysicalObject.PartAdded event.");
				}
			}
		}
	}

	public void Start()
	{
		ReconcileExistingSubPoints();
	}

	public void OnDestroy()
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Expected O, but got Unknown
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Expected O, but got Unknown
		if (m_hasSubscribed)
		{
			if (m_modularFireArm != null)
			{
				m_modularFireArm.PartAdded -= new PartAdded(OnPartAdded);
			}
			else if ((Object)(object)m_modularPhysicalObject != (Object)null)
			{
				m_modularPhysicalObject.PartAdded -= new PartAdded(OnPartAdded);
			}
			m_hasSubscribed = false;
		}
	}

	private bool IsWeaponUnvaulted()
	{
		if (m_modularFireArm != null)
		{
			return m_modularFireArm.WasUnvaulted;
		}
		if ((Object)(object)m_modularPhysicalObject != (Object)null)
		{
			return m_modularPhysicalObject.WasUnvaulted;
		}
		return false;
	}

	private List<ModularWeaponPartsAttachmentPoint> GetActiveSubPoints()
	{
		if (m_modularFireArm != null)
		{
			return m_modularFireArm.SubAttachmentPoints;
		}
		if ((Object)(object)m_modularPhysicalObject != (Object)null)
		{
			return m_modularPhysicalObject.SubAttachmentPoints;
		}
		return null;
	}

	private void ReconcileExistingSubPoints()
	{
		List<ModularWeaponPartsAttachmentPoint> activeSubPoints = GetActiveSubPoints();
		if (activeSubPoints == null || activeSubPoints.Count == 0 || (RespectVaultSaves && IsWeaponUnvaulted()))
		{
			return;
		}
		for (int i = 0; i < activeSubPoints.Count; i++)
		{
			ModularWeaponPartsAttachmentPoint val = activeSubPoints[i];
			if (val != null && !string.IsNullOrEmpty(val.ModularPartsGroupID))
			{
				SubPartOverrideRule subPartOverrideRule = FindMatchingRule(val.ModularPartsGroupID, string.Empty);
				if (subPartOverrideRule != null && !string.IsNullOrEmpty(subPartOverrideRule.DesiredPartName) && !string.Equals(val.SelectedModularWeaponPart, subPartOverrideRule.DesiredPartName, StringComparison.OrdinalIgnoreCase))
				{
					ApplySubPartOverride(val, subPartOverrideRule.DesiredPartName);
				}
			}
		}
	}

	private void OnPartAdded(ModularWeaponPartsAttachmentPoint attachmentPoint, ModularWeaponPart newPart)
	{
		if (m_isApplyingOverride || (Object)(object)newPart == (Object)null || (RespectVaultSaves && IsWeaponUnvaulted()) || Overrides == null || Overrides.Length == 0 || newPart.SubAttachmentPoints == null || newPart.SubAttachmentPoints.Length == 0)
		{
			return;
		}
		string parentPartName = string.Empty;
		ModularWeaponPart component = ((Component)newPart).GetComponent<ModularWeaponPart>();
		if ((Object)(object)component != (Object)null)
		{
			parentPartName = component.Name;
		}
		for (int i = 0; i < newPart.SubAttachmentPoints.Length; i++)
		{
			ModularWeaponPartsAttachmentPoint val = newPart.SubAttachmentPoints[i];
			if (val != null && !string.IsNullOrEmpty(val.ModularPartsGroupID))
			{
				SubPartOverrideRule subPartOverrideRule = FindMatchingRule(val.ModularPartsGroupID, parentPartName);
				if (subPartOverrideRule != null && !string.IsNullOrEmpty(subPartOverrideRule.DesiredPartName) && !string.Equals(val.SelectedModularWeaponPart, subPartOverrideRule.DesiredPartName, StringComparison.OrdinalIgnoreCase))
				{
					ApplySubPartOverride(val, subPartOverrideRule.DesiredPartName);
				}
			}
		}
	}

	private SubPartOverrideRule FindMatchingRule(string subGroupID, string parentPartName)
	{
		for (int i = 0; i < Overrides.Length; i++)
		{
			SubPartOverrideRule subPartOverrideRule = Overrides[i];
			if (subPartOverrideRule != null && !string.IsNullOrEmpty(subPartOverrideRule.TargetSubGroupID) && string.Equals(subPartOverrideRule.TargetSubGroupID, subGroupID, StringComparison.OrdinalIgnoreCase))
			{
				if (string.IsNullOrEmpty(subPartOverrideRule.OnlyWhenParentPartIs))
				{
					return subPartOverrideRule;
				}
				if (!string.IsNullOrEmpty(parentPartName) && string.Equals(subPartOverrideRule.OnlyWhenParentPartIs, parentPartName, StringComparison.OrdinalIgnoreCase))
				{
					return subPartOverrideRule;
				}
			}
		}
		return null;
	}

	private void ApplySubPartOverride(ModularWeaponPartsAttachmentPoint subPoint, string targetPartName)
	{
		m_isApplyingOverride = true;
		try
		{
			if (EnableDebugLogging)
			{
				Debug.Log((object)("[ModularSubPartOverride] Overriding sub-point '" + subPoint.ModularPartsGroupID + "' (was '" + subPoint.SelectedModularWeaponPart + "') with: " + targetPartName));
			}
			subPoint.SelectedModularWeaponPart = targetPartName;
			if (m_modularFireArm != null)
			{
				m_modularFireArm.ConfigureModularWeaponPart(subPoint, targetPartName, false, (Dictionary<string, string>)null, (Dictionary<string, string>)null);
			}
			else if ((Object)(object)m_modularPhysicalObject != (Object)null)
			{
				m_modularPhysicalObject.ConfigureModularWeaponPart(subPoint, targetPartName, false, (Dictionary<string, string>)null, (Dictionary<string, string>)null);
			}
			if (EnableDebugLogging)
			{
				Debug.Log((object)("[ModularSubPartOverride] Successfully overridden sub-point '" + subPoint.ModularPartsGroupID + "'."));
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("[ModularSubPartOverride] Error overriding sub-point '" + subPoint.ModularPartsGroupID + "': " + ex.Message));
		}
		finally
		{
			m_isApplyingOverride = false;
		}
	}
}
public class MultipleGroupIDAttachment : MonoBehaviour
{
	[Tooltip("Enables verbose console logging for debugging.")]
	public bool EnableDebugLogging = false;

	[Tooltip("List of additional ModularPartsGroupIDs this part should also belong to.")]
	public string[] AdditionalGroupIDs = new string[0];

	[Tooltip("Specific ModularPartsGroupIDs on the host weapon to replace/disable when this part is attached (e.g. BufferTubes_AR, Grips_AR, Triggers_AR, Selectors_AR).")]
	public string[] RelocatedGroupIDs = new string[0];

	[Tooltip("If enabled, automatically detects any sub-attachment point on this part that shares a group ID with the host weapon's points, replacing the host weapon's slot.")]
	public bool AutoRelocateMatchingSubPoints = true;

	private bool m_isRelocated;

	private List<ModularWeaponPartsAttachmentPoint> m_relocatedPoints = new List<ModularWeaponPartsAttachmentPoint>();

	private List<string> m_originalGroupIDs = new List<string>();

	private List<string> m_originalSelectedParts = new List<string>();

	public void Awake()
	{
		ApplyRelocations();
	}

	public void OnDestroy()
	{
		RevertRelocations();
	}

	private void ApplyRelocations()
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		if (m_isRelocated)
		{
			return;
		}
		IModularWeapon val = null;
		Component componentInParent = ((Component)this).GetComponentInParent(typeof(IModularWeapon));
		if ((Object)(object)componentInParent != (Object)null)
		{
			val = (IModularWeapon)componentInParent;
		}
		ModularFVRPhysicalObject val2 = null;
		if (val == null)
		{
			val2 = ((Component)this).GetComponentInParent<ModularFVRPhysicalObject>();
		}
		List<ModularWeaponPartsAttachmentPoint> list = new List<ModularWeaponPartsAttachmentPoint>();
		if (val != null)
		{
			ModularFVRFireArm getModularFVRFireArm = val.GetModularFVRFireArm;
			if (getModularFVRFireArm != null)
			{
				if (getModularFVRFireArm.ModularBarrelAttachmentPoint != null)
				{
					list.Add(getModularFVRFireArm.ModularBarrelAttachmentPoint);
				}
				if (getModularFVRFireArm.ModularHandguardAttachmentPoint != null)
				{
					list.Add(getModularFVRFireArm.ModularHandguardAttachmentPoint);
				}
				if (getModularFVRFireArm.ModularStockAttachmentPoint != null)
				{
					list.Add(getModularFVRFireArm.ModularStockAttachmentPoint);
				}
			}
			if (val.ModularWeaponPartsAttachmentPoints != null)
			{
				list.AddRange(val.ModularWeaponPartsAttachmentPoints);
			}
			if (val.SubAttachmentPoints != null)
			{
				list.AddRange(val.SubAttachmentPoints);
			}
		}
		else if ((Object)(object)val2 != (Object)null)
		{
			if (val2.ModularWeaponPartsAttachmentPoints != null)
			{
				list.AddRange(val2.ModularWeaponPartsAttachmentPoints);
			}
			if (val2.SubAttachmentPoints != null)
			{
				list.AddRange(val2.SubAttachmentPoints);
			}
		}
		if (list.Count == 0)
		{
			return;
		}
		List<string> list2 = new List<string>();
		ModularWeaponPart component = ((Component)this).GetComponent<ModularWeaponPart>();
		if (RelocatedGroupIDs != null)
		{
			for (int i = 0; i < RelocatedGroupIDs.Length; i++)
			{
				string text = RelocatedGroupIDs[i];
				if (!string.IsNullOrEmpty(text) && !list2.Contains(text))
				{
					list2.Add(text);
				}
			}
		}
		if (AutoRelocateMatchingSubPoints && (Object)(object)component != (Object)null && component.SubAttachmentPoints != null)
		{
			for (int j = 0; j < component.SubAttachmentPoints.Length; j++)
			{
				ModularWeaponPartsAttachmentPoint val3 = component.SubAttachmentPoints[j];
				if (val3 != null && !string.IsNullOrEmpty(val3.ModularPartsGroupID) && !list2.Contains(val3.ModularPartsGroupID))
				{
					list2.Add(val3.ModularPartsGroupID);
				}
			}
		}
		if (list2.Count == 0)
		{
			return;
		}
		for (int k = 0; k < list.Count; k++)
		{
			ModularWeaponPartsAttachmentPoint val4 = list[k];
			if (val4 != null && !string.IsNullOrEmpty(val4.ModularPartsGroupID) && (!((Object)(object)component != (Object)null) || component.SubAttachmentPoints == null || Array.IndexOf(component.SubAttachmentPoints, val4) < 0) && list2.Contains(val4.ModularPartsGroupID))
			{
				RelocateSinglePoint(val4, val, val2);
			}
		}
		if (m_relocatedPoints.Count > 0)
		{
			m_isRelocated = true;
		}
	}

	private void RelocateSinglePoint(ModularWeaponPartsAttachmentPoint targetPoint, IModularWeapon modWeapon, ModularFVRPhysicalObject modPhys)
	{
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Expected O, but got Unknown
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		if (targetPoint == null || m_relocatedPoints.Contains(targetPoint))
		{
			return;
		}
		string modularPartsGroupID = targetPoint.ModularPartsGroupID;
		string selectedModularWeaponPart = targetPoint.SelectedModularWeaponPart;
		m_relocatedPoints.Add(targetPoint);
		m_originalGroupIDs.Add(modularPartsGroupID);
		m_originalSelectedParts.Add(selectedModularWeaponPart);
		if (modWeapon != null && (Object)(object)modWeapon.WorkshopPlatform != (Object)null)
		{
			modWeapon.WorkshopPlatform.RemoveUIFromPoint(targetPoint);
		}
		else if ((Object)(object)modPhys != (Object)null && (Object)(object)modPhys.WorkshopPlatform != (Object)null)
		{
			modPhys.WorkshopPlatform.RemoveUIFromPoint(targetPoint);
		}
		if ((Object)(object)targetPoint.ModularPartPoint != (Object)null)
		{
			GameObject val = new GameObject(modularPartsGroupID + "_TempPoint");
			val.transform.position = targetPoint.ModularPartPoint.position;
			val.transform.rotation = targetPoint.ModularPartPoint.rotation;
			val.transform.parent = targetPoint.ModularPartPoint.parent;
			ModularWeaponPart componentInChildren = ((Component)targetPoint.ModularPartPoint).GetComponentInChildren<ModularWeaponPart>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.DisablePart();
				Object.Destroy((Object)(object)((Component)componentInChildren).gameObject);
			}
			targetPoint.ModularPartPoint = val.transform;
		}
		targetPoint.IsPointDisabled = true;
		targetPoint.ModularPartsGroupID = modularPartsGroupID + "_Relocated";
		if (EnableDebugLogging)
		{
			Debug.Log((object)("[MultipleGroupIDAttachment] Replaced point '" + modularPartsGroupID + "' -> renamed to '" + targetPoint.ModularPartsGroupID + "' and created temporary anchor."));
		}
	}

	private void RevertRelocations()
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		if (!m_isRelocated || m_relocatedPoints.Count == 0)
		{
			return;
		}
		IModularWeapon val = null;
		Component componentInParent = ((Component)this).GetComponentInParent(typeof(IModularWeapon));
		if ((Object)(object)componentInParent != (Object)null)
		{
			val = (IModularWeapon)componentInParent;
		}
		ModularFVRPhysicalObject val2 = null;
		if (val == null)
		{
			val2 = ((Component)this).GetComponentInParent<ModularFVRPhysicalObject>();
		}
		ClosedBoltWeapon componentInParent2 = ((Component)this).GetComponentInParent<ClosedBoltWeapon>();
		if ((Object)(object)componentInParent2 != (Object)null)
		{
			componentInParent2.HasTrigger = false;
			componentInParent2.Trigger = ((Component)componentInParent2).transform;
		}
		for (int i = 0; i < m_relocatedPoints.Count; i++)
		{
			ModularWeaponPartsAttachmentPoint val3 = m_relocatedPoints[i];
			string text = m_originalGroupIDs[i];
			string text2 = m_originalSelectedParts[i];
			if (val3 == null)
			{
				continue;
			}
			val3.ModularPartsGroupID = text;
			val3.IsPointDisabled = false;
			if ((Object)(object)componentInParent2 != (Object)null && componentInParent2.HasTrigger && (Object)(object)componentInParent2.Trigger == (Object)null && (Object)(object)val3.ModularPartPoint != (Object)null)
			{
				componentInParent2.Trigger = val3.ModularPartPoint;
			}
			if (string.IsNullOrEmpty(text2))
			{
				continue;
			}
			val3.SelectedModularWeaponPart = text2;
			try
			{
				if (val != null)
				{
					val.ConfigureModularWeaponPart(val3, text2, false);
				}
				else if ((Object)(object)val2 != (Object)null)
				{
					val2.ConfigureModularWeaponPart(val3, text2, false, (Dictionary<string, string>)null, (Dictionary<string, string>)null);
				}
				ModularWorkshopPlatform val4 = null;
				if (val != null)
				{
					val4 = val.WorkshopPlatform;
				}
				else if ((Object)(object)val2 != (Object)null)
				{
					val4 = val2.WorkshopPlatform;
				}
				if ((Object)(object)val4 != (Object)null)
				{
					EPartType val5 = DeterminePartType(val3, val, val2);
					val4.CreateUIForPoint(val3, val5);
				}
				if (EnableDebugLogging)
				{
					Debug.Log((object)("[MultipleGroupIDAttachment] Synchronously restored point '" + text + "' with part: " + text2));
				}
			}
			catch (Exception ex)
			{
				if (EnableDebugLogging)
				{
					Debug.LogError((object)("[MultipleGroupIDAttachment] Error restoring point '" + text + "': " + ex.Message));
				}
			}
		}
		if ((Object)(object)componentInParent2 != (Object)null && (Object)(object)componentInParent2.Trigger != (Object)null && (Object)(object)componentInParent2.Trigger != (Object)(object)((Component)componentInParent2).transform)
		{
			componentInParent2.HasTrigger = true;
		}
		m_relocatedPoints.Clear();
		m_originalGroupIDs.Clear();
		m_originalSelectedParts.Clear();
		m_isRelocated = false;
	}

	private EPartType DeterminePartType(ModularWeaponPartsAttachmentPoint point, IModularWeapon modWeapon, ModularFVRPhysicalObject modPhys)
	{
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: 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)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		if (modWeapon != null)
		{
			if (!string.IsNullOrEmpty(modWeapon.ModularBarrelPartsID) && string.Equals(point.ModularPartsGroupID, modWeapon.ModularBarrelPartsID, StringComparison.OrdinalIgnoreCase))
			{
				return (EPartType)0;
			}
			if (!string.IsNullOrEmpty(modWeapon.ModularHandguardPartsID) && string.Equals(point.ModularPartsGroupID, modWeapon.ModularHandguardPartsID, StringComparison.OrdinalIgnoreCase))
			{
				return (EPartType)1;
			}
			if (!string.IsNullOrEmpty(modWeapon.ModularStockPartsID) && string.Equals(point.ModularPartsGroupID, modWeapon.ModularStockPartsID, StringComparison.OrdinalIgnoreCase))
			{
				return (EPartType)2;
			}
			if (modWeapon.SubAttachmentPoints != null && modWeapon.SubAttachmentPoints.Contains(point))
			{
				return (EPartType)4;
			}
			return (EPartType)3;
		}
		if ((Object)(object)modPhys != (Object)null && modPhys.SubAttachmentPoints != null && modPhys.SubAttachmentPoints.Contains(point))
		{
			return (EPartType)4;
		}
		return (EPartType)3;
	}
}
[BepInPlugin("com.custom.multiplegroupidattachment", "MultipleGroupIDAttachment", "1.0.0")]
public class MultipleGroupIDPlugin : BaseUnityPlugin
{
	[Tooltip("Enables verbose console logging for debugging.")]
	public bool EnableDebugLogging = false;

	private static MultipleGroupIDPlugin s_instance;

	private bool m_isRunning;

	private HashSet<string> m_registeredPairs = new HashSet<string>();

	public static MultipleGroupIDPlugin Instance => s_instance;

	public void Awake()
	{
		s_instance = this;
		SceneManager.sceneLoaded += OnSceneLoaded;
		TriggerScan();
	}

	public void OnDestroy()
	{
		SceneManager.sceneLoaded -= OnSceneLoaded;
		if ((Object)(object)s_instance == (Object)(object)this)
		{
			s_instance = null;
		}
	}

	private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		TriggerScan();
	}

	public void TriggerScan()
	{
		if (!m_isRunning)
		{
			((MonoBehaviour)this).StartCoroutine(RegistrationRoutine());
		}
	}

	private IEnumerator RegistrationRoutine()
	{
		m_isRunning = true;
		for (float timer = 0f; timer < 20f; timer += 1.5f)
		{
			ProcessRegistrations();
			yield return (object)new WaitForSeconds(1.5f);
		}
		ProcessRegistrations();
		m_isRunning = false;
	}

	private void ProcessRegistrations()
	{
		if (ModularWorkshopManager.ModularWorkshopPartsGroupsDictionary == null)
		{
			return;
		}
		MultipleGroupIDAttachment[] array = Resources.FindObjectsOfTypeAll<MultipleGroupIDAttachment>();
		if (array != null && array.Length > 0)
		{
			foreach (MultipleGroupIDAttachment multipleGroupIDAttachment in array)
			{
				if ((Object)(object)multipleGroupIDAttachment != (Object)null && (Object)(object)((Component)multipleGroupIDAttachment).gameObject != (Object)null && multipleGroupIDAttachment.AdditionalGroupIDs != null && multipleGroupIDAttachment.AdditionalGroupIDs.Length > 0)
				{
					InjectPrefabIntoGroups(((Component)multipleGroupIDAttachment).gameObject, multipleGroupIDAttachment.AdditionalGroupIDs);
				}
			}
		}
		if (ModularWorkshopManager.ModularWorkshopPartsGroupsDictionary.Count <= 0)
		{
			return;
		}
		List<ModularWorkshopPartsDefinition> list = new List<ModularWorkshopPartsDefinition>(ModularWorkshopManager.ModularWorkshopPartsGroupsDictionary.Values);
		for (int j = 0; j < list.Count; j++)
		{
			ModularWorkshopPartsDefinition val = list[j];
			if ((Object)(object)val == (Object)null || val.ModularPrefabs == null)
			{
				continue;
			}
			for (int k = 0; k < val.ModularPrefabs.Count; k++)
			{
				GameObject val2 = val.ModularPrefabs[k];
				if (!((Object)(object)val2 == (Object)null))
				{
					MultipleGroupIDAttachment component = val2.GetComponent<MultipleGroupIDAttachment>();
					if ((Object)(object)component != (Object)null && component.AdditionalGroupIDs != null && component.AdditionalGroupIDs.Length > 0)
					{
						InjectPrefabIntoGroups(val2, component.AdditionalGroupIDs);
					}
				}
			}
		}
	}

	private void InjectPrefabIntoGroups(GameObject prefab, string[] targetGroupIDs)
	{
		ModularWeaponPart component = prefab.GetComponent<ModularWeaponPart>();
		string targetPartName = ((!((Object)(object)component != (Object)null)) ? ((Object)prefab).name : component.Name);
		int instanceID = ((Object)prefab).GetInstanceID();
		foreach (string text in targetGroupIDs)
		{
			if (string.IsNullOrEmpty(text))
			{
				continue;
			}
			string item = instanceID + ":" + text;
			if (m_registeredPairs.Contains(item))
			{
				continue;
			}
			if (ModularWorkshopManager.ModularWorkshopPartsGroupsDictionary.TryGetValue(text, out var value))
			{
				if (!((Object)(object)value != (Object)null) || value.ModularPrefabs == null)
				{
					continue;
				}
				if (IsPartNameAlreadyInGroup(value, targetPartName))
				{
					m_registeredPairs.Add(item);
				}
				else if (!value.ModularPrefabs.Contains(prefab))
				{
					value.ModularPrefabs.Add(prefab);
					m_registeredPairs.Add(item);
					if (EnableDebugLogging)
					{
						Debug.Log((object)("[MultipleGroupIDAttachment] Injected prefab '" + ((Object)prefab).name + "' into existing group: " + text));
					}
				}
				else
				{
					m_registeredPairs.Add(item);
				}
			}
			else
			{
				value = ScriptableObject.CreateInstance<ModularWorkshopPartsDefinition>();
				((Object)value).name = text + "_DynamicDefinition";
				value.ModularPartsGroupID = text;
				value.DisplayName = text;
				value.ModularPrefabs = new List<GameObject>();
				value.ModularPrefabs.Add(prefab);
				ModularWorkshopManager.ModularWorkshopPartsGroupsDictionary.Add(text, value);
				m_registeredPairs.Add(item);
				if (EnableDebugLogging)
				{
					Debug.Log((object)("[MultipleGroupIDAttachment] Created dynamic group '" + text + "' and registered prefab: " + ((Object)prefab).name));
				}
			}
		}
	}

	private bool IsPartNameAlreadyInGroup(ModularWorkshopPartsDefinition def, string targetPartName)
	{
		if ((Object)(object)def == (Object)null || def.ModularPrefabs == null)
		{
			return false;
		}
		for (int i = 0; i < def.ModularPrefabs.Count; i++)
		{
			GameObject val = def.ModularPrefabs[i];
			if (!((Object)(object)val == (Object)null))
			{
				ModularWeaponPart component = val.GetComponent<ModularWeaponPart>();
				if ((Object)(object)component != (Object)null && string.Equals(component.Name, targetPartName, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
		}
		return false;
	}
}
[DefaultExecutionOrder(-200)]
[RequireComponent(typeof(ModularWeaponPart))]
public class IntegratedAttachableFirearmAddon : MonoBehaviour, IPartFireArmRequirement
{
	[Header("Debug Settings")]
	[Tooltip("Enable detailed console logs to track component auto-detection and linking.")]
	public bool EnableDebugLogging = true;

	private FVRFireArm _mainFireArm;

	private AttachableFirearm _underbarrelFirearm;

	private AttachableFirearmPhysicalObject _underbarrelPhysical;

	private AttachableFirearmInterface _underbarrelInterface;

	private bool _needsLayerForce = false;

	public FVRFireArm FireArm
	{
		get
		{
			return _mainFireArm;
		}
		set
		{
			if ((Object)(object)value != (Object)null)
			{
				_mainFireArm = value;
				if (EnableDebugLogging)
				{
					Debug.Log((object)$"[IntegratedAttachableFirearmAddon] Equipping - Main Firearm assigned: {((Object)value).name}");
				}
				if ((Object)(object)_underbarrelFirearm != (Object)null)
				{
					_underbarrelFirearm.OverrideFA = value;
					value.SetIntegratedAttachableFirearm(_underbarrelFirearm);
				}
				((Behaviour)this).enabled = true;
				_needsLayerForce = true;
				return;
			}
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[IntegratedAttachableFirearmAddon] Swapping away - Part unequipped. Starting cleanup.");
			}
			_needsLayerForce = false;
			if ((Object)(object)_underbarrelFirearm != (Object)null)
			{
				_underbarrelFirearm.OverrideFA = null;
			}
			if ((Object)(object)_underbarrelInterface != (Object)null)
			{
				((AttachableForegrip)_underbarrelInterface).OverrideFirearm = null;
			}
			if ((Object)(object)_mainFireArm != (Object)null)
			{
				_mainFireArm.SetIntegratedAttachableFirearm((AttachableFirearm)null);
			}
			if ((Object)(object)_underbarrelPhysical != (Object)null)
			{
				if (EnableDebugLogging)
				{
					Debug.Log((object)$"[IntegratedAttachableFirearmAddon] Swapping away - Destroying unparented physical launcher GameObject: {((Object)((Component)_underbarrelPhysical).gameObject).name}");
				}
				Object.Destroy((Object)(object)((Component)_underbarrelPhysical).gameObject);
				_underbarrelPhysical = null;
			}
			_mainFireArm = null;
		}
	}

	private void Awake()
	{
		//IL_0185: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Expected O, but got Unknown
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0286: Expected O, but got Unknown
		//IL_0371: Unknown result type (might be due to invalid IL or missing references)
		//IL_0378: Expected O, but got Unknown
		_underbarrelFirearm = ((Component)this).GetComponentInChildren<AttachableFirearm>(true);
		_underbarrelPhysical = ((Component)this).GetComponentInChildren<AttachableFirearmPhysicalObject>(true);
		_underbarrelInterface = ((Component)this).GetComponentInChildren<AttachableFirearmInterface>(true);
		if (EnableDebugLogging)
		{
			Debug.Log((object)$"[IntegratedAttachableFirearmAddon] Awake - Underbarrel Firearm: {(Object)(object)_underbarrelFirearm != (Object)null}, Physical: {(Object)(object)_underbarrelPhysical != (Object)null}, Interface: {(Object)(object)_underbarrelInterface != (Object)null}");
		}
		if ((Object)(object)_underbarrelFirearm != (Object)null)
		{
			_underbarrelFirearm.Attachment = _underbarrelPhysical;
			_underbarrelFirearm.Interface = _underbarrelInterface;
		}
		if ((Object)(object)_underbarrelPhysical != (Object)null)
		{
			((FVRFireArmAttachment)_underbarrelPhysical).AttachmentInterface = (FVRFireArmAttachmentInterface)(object)_underbarrelInterface;
		}
		if ((Object)(object)_underbarrelInterface != (Object)null)
		{
			_underbarrelInterface.FA = _underbarrelFirearm;
			((FVRFireArmAttachmentInterface)_underbarrelInterface).Attachment = (FVRFireArmAttachment)(object)_underbarrelPhysical;
		}
		if (EnableDebugLogging)
		{
			Debug.Log((object)"[IntegratedAttachableFirearmAddon] Awake - Unconditionally forced all component cross-references in memory.");
		}
		if ((Object)(object)_underbarrelPhysical != (Object)null && (Object)(object)((FVRInteractiveObject)_underbarrelPhysical).PoseOverride == (Object)null)
		{
			Transform val = ((Component)_underbarrelPhysical).transform.Find("_Pose");
			if ((Object)(object)val == (Object)null)
			{
				foreach (Transform item in ((Component)_underbarrelPhysical).transform)
				{
					Transform val2 = item;
					if (((Object)val2).name.ToLower().Contains("pose"))
					{
						val = val2;
						break;
					}
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				((FVRInteractiveObject)_underbarrelPhysical).PoseOverride = val;
				if (EnableDebugLogging)
				{
					Debug.Log((object)$"[IntegratedAttachableFirearmAddon] Awake - PoseOverride was NULL. Auto-repaired by linking to child: {((Object)val).name}");
				}
			}
		}
		if (!((Object)(object)_underbarrelFirearm != (Object)null))
		{
			return;
		}
		if ((Object)(object)_underbarrelFirearm.MuzzlePos == (Object)null)
		{
			Transform val3 = ((Component)_underbarrelFirearm).transform.Find("_Muzzle");
			if ((Object)(object)val3 == (Object)null)
			{
				foreach (Transform item2 in ((Component)_underbarrelFirearm).transform)
				{
					Transform val4 = item2;
					if (((Object)val4).name.ToLower().Contains("muzzle"))
					{
						val3 = val4;
						break;
					}
				}
			}
			if ((Object)(object)val3 != (Object)null)
			{
				_underbarrelFirearm.MuzzlePos = val3;
				if (EnableDebugLogging)
				{
					Debug.Log((object)$"[IntegratedAttachableFirearmAddon] Awake - MuzzlePos was NULL. Auto-repaired by linking to child: {((Object)val3).name}");
				}
			}
		}
		if (!((Object)(object)_underbarrelFirearm.RecoilingPoseHolder == (Object)null))
		{
			return;
		}
		Transform val5 = ((Component)_underbarrelFirearm).transform.Find("_RecoilHolder");
		if ((Object)(object)val5 == (Object)null)
		{
			foreach (Transform item3 in ((Component)_underbarrelFirearm).transform)
			{
				Transform val6 = item3;
				if (((Object)val6).name.ToLower().Contains("recoil"))
				{
					val5 = val6;
					break;
				}
			}
		}
		if ((Object)(object)val5 != (Object)null)
		{
			_underbarrelFirearm.RecoilingPoseHolder = val5;
			if (EnableDebugLogging)
			{
				Debug.Log((object)$"[IntegratedAttachableFirearmAddon] Awake - RecoilingPoseHolder was NULL. Auto-repaired by linking to child: {((Object)val5).name}");
			}
		}
	}

	private void Update()
	{
		if (!_needsLayerForce || !((Object)(object)_mainFireArm != (Object)null))
		{
			return;
		}
		_needsLayerForce = false;
		int num = LayerMask.NameToLayer("Interactable");
		if (num != -1)
		{
			if ((Object)(object)_underbarrelPhysical != (Object)null)
			{
				SetLayerRecursive(((Component)_underbarrelPhysical).gameObject, num);
			}
			if ((Object)(object)_underbarrelInterface != (Object)null)
			{
				SetLayerRecursive(((Component)_underbarrelInterface).gameObject, num);
			}
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[IntegratedAttachableFirearmAddon] Update - Unconditionally forced 'Interactable' layer recursively down the hierarchies.");
			}
		}
		else if (EnableDebugLogging)
		{
			Debug.LogError((object)"[IntegratedAttachableFirearmAddon] Update - Could not find 'Interactable' layer in Unity.");
		}
	}

	private void SetLayerRecursive(GameObject obj, int layer)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		if ((Object)(object)obj == (Object)null)
		{
			return;
		}
		obj.layer = layer;
		foreach (Transform item in obj.transform)
		{
			Transform val = item;
			if ((Object)(object)val != (Object)null)
			{
				SetLayerRecursive(((Component)val).gameObject, layer);
			}
		}
	}
}
public class SafetyToggle : FVRInteractiveObject
{
	public ClosedBoltWeapon Weapon;

	public Transform SelctorSwitch;

	public Axis Axis;

	public InterpStyle InterpStyle;

	[Tooltip("Index in Weapon.FireSelector_Modes that this secondary toggle will override (e.g. 1)")]
	public int ModeIndexToSub = 1;

	public FireSelectorMode[] Modes;

	[Tooltip("Enable to show debug logs in console.")]
	public bool DebugLogging = false;

	private int CurModeIndex;

	private FireSelectorMode[] _backupModes;

	private FireSelectorMode[] _backupModes2;

	private bool _isGloballySafe;

	public override void Awake()
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected O, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Expected O, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0129: Expected O, but got Unknown
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Unknown result type (might be due to invalid IL or missing references)
		((FVRInteractiveObject)this).Awake();
		if (Modes == null || Modes.Length < 2)
		{
			Modes = (FireSelectorMode[])(object)new FireSelectorMode[2];
			FireSelectorMode[] modes = Modes;
			FireSelectorMode val = new FireSelectorMode();
			val.SelectorPosition = 0f;
			val.ModeType = (FireSelectorModeType)0;
			val.BurstAmount = 0;
			val.ARStyleBurst = false;
			val.EngagementDelay = 0f;
			modes[0] = val;
			FireSelectorMode[] modes2 = Modes;
			val = new FireSelectorMode();
			val.SelectorPosition = 0f;
			val.ModeType = (FireSelectorModeType)1;
			val.BurstAmount = 1;
			val.ARStyleBurst = false;
			val.EngagementDelay = 0f;
			modes2[1] = val;
		}
		if ((Object)(object)Weapon != (Object)null && Weapon.FireSelector_Modes != null && ModeIndexToSub >= 0 && ModeIndexToSub < Weapon.FireSelector_Modes.Length)
		{
			FireSelectorMode val2 = Weapon.FireSelector_Modes[ModeIndexToSub];
			if ((int)val2.ModeType == 0)
			{
				CurModeIndex = 0;
			}
			else
			{
				CurModeIndex = 1;
				FireSelectorMode[] modes3 = Modes;
				FireSelectorMode val = new FireSelectorMode();
				val.SelectorPosition = val2.SelectorPosition;
				val.ModeType = val2.ModeType;
				val.BurstAmount = val2.BurstAmount;
				val.ARStyleBurst = val2.ARStyleBurst;
				val.EngagementDelay = val2.EngagementDelay;
				modes3[1] = val;
			}
			if ((Object)(object)SelctorSwitch != (Object)null)
			{
				((FVRPhysicalObject)Weapon).SetAnimatedComponent(SelctorSwitch, Modes[CurModeIndex].SelectorPosition, InterpStyle, Axis);
			}
		}
	}

	public override void SimpleInteraction(FVRViveHand hand)
	{
		((FVRInteractiveObject)this).SimpleInteraction(hand);
		CycleMode();
	}

	private void CycleMode()
	{
		if (!((Object)(object)Weapon == (Object)null) && Weapon.FireSelector_Modes != null && ModeIndexToSub >= 0 && ModeIndexToSub < Weapon.FireSelector_Modes.Length && Modes != null && Modes.Length >= 2)
		{
			CurModeIndex++;
			if (CurModeIndex >= Modes.Length)
			{
				CurModeIndex = 0;
			}
			if (CurModeIndex == 0)
			{
				EnableGlobalSafe();
			}
			else
			{
				DisableGlobalSafeAndRestore();
			}
			((FVRFireArm)Weapon).PlayAudioEvent((FirearmAudioEventType)15, 1f);
		}
	}

	private void EnableGlobalSafe()
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Expected O, but got Unknown
		//IL_0042: 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_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Expected O, but got Unknown
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_020a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		FireSelectorMode[] fireSelector_Modes = Weapon.FireSelector_Modes;
		_backupModes = (FireSelectorMode[])(object)new FireSelectorMode[fireSelector_Modes.Length];
		for (int i = 0; i < fireSelector_Modes.Length; i++)
		{
			FireSelectorMode[] backupModes = _backupModes;
			int num = i;
			FireSelectorMode val = new FireSelectorMode();
			val.SelectorPosition = fireSelector_Modes[i].SelectorPosition;
			val.ModeType = fireSelector_Modes[i].ModeType;
			val.BurstAmount = fireSelector_Modes[i].BurstAmount;
			val.ARStyleBurst = fireSelector_Modes[i].ARStyleBurst;
			val.EngagementDelay = fireSelector_Modes[i].EngagementDelay;
			backupModes[num] = val;
		}
		if (Weapon.FireSelector_Modes2 != null)
		{
			FireSelectorMode[] fireSelector_Modes2 = Weapon.FireSelector_Modes2;
			_backupModes2 = (FireSelectorMode[])(object)new FireSelectorMode[fireSelector_Modes2.Length];
			for (int j = 0; j < fireSelector_Modes2.Length; j++)
			{
				FireSelectorMode[] backupModes2 = _backupModes2;
				int num2 = j;
				FireSelectorMode val = new FireSelectorMode();
				val.SelectorPosition = fireSelector_Modes2[j].SelectorPosition;
				val.ModeType = fireSelector_Modes2[j].ModeType;
				val.BurstAmount = fireSelector_Modes2[j].BurstAmount;
				val.ARStyleBurst = fireSelector_Modes2[j].ARStyleBurst;
				val.EngagementDelay = fireSelector_Modes2[j].EngagementDelay;
				backupModes2[num2] = val;
			}
		}
		else
		{
			_backupModes2 = null;
		}
		for (int k = 0; k < Weapon.FireSelector_Modes.Length; k++)
		{
			Weapon.FireSelector_Modes[k].ModeType = (FireSelectorModeType)0;
			Weapon.FireSelector_Modes[k].BurstAmount = 0;
		}
		if (Weapon.FireSelector_Modes2 != null)
		{
			for (int l = 0; l < Weapon.FireSelector_Modes2.Length; l++)
			{
				Weapon.FireSelector_Modes2[l].ModeType = (FireSelectorModeType)0;
				Weapon.FireSelector_Modes2[l].BurstAmount = 0;
			}
		}
		if ((Object)(object)SelctorSwitch != (Object)null)
		{
			((FVRPhysicalObject)Weapon).SetAnimatedComponent(SelctorSwitch, Modes[0].SelectorPosition, InterpStyle, Axis);
		}
		Weapon.ResetCamBurst();
		_isGloballySafe = true;
		if (DebugLogging)
		{
			Debug.Log((object)"SafetyToggle: Global safe enabled.");
		}
	}

	private void DisableGlobalSafeAndRestore()
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_0236: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		if (!_isGloballySafe)
		{
			ApplyModeToWeapon(1);
			return;
		}
		if (_backupModes != null)
		{
			int num = Math.Min(_backupModes.Length, Weapon.FireSelector_Modes.Length);
			for (int i = 0; i < num; i++)
			{
				Weapon.FireSelector_Modes[i].ModeType = _backupModes[i].ModeType;
				Weapon.FireSelector_Modes[i].BurstAmount = _backupModes[i].BurstAmount;
				Weapon.FireSelector_Modes[i].ARStyleBurst = _backupModes[i].ARStyleBurst;
				Weapon.FireSelector_Modes[i].EngagementDelay = _backupModes[i].EngagementDelay;
				Weapon.FireSelector_Modes[i].SelectorPosition = _backupModes[i].SelectorPosition;
			}
		}
		if (_backupModes2 != null && Weapon.FireSelector_Modes2 != null)
		{
			int num2 = Math.Min(_backupModes2.Length, Weapon.FireSelector_Modes2.Length);
			for (int j = 0; j < num2; j++)
			{
				Weapon.FireSelector_Modes2[j].ModeType = _backupModes2[j].ModeType;
				Weapon.FireSelector_Modes2[j].BurstAmount = _backupModes2[j].BurstAmount;
				Weapon.FireSelector_Modes2[j].ARStyleBurst = _backupModes2[j].ARStyleBurst;
				Weapon.FireSelector_Modes2[j].EngagementDelay = _backupModes2[j].EngagementDelay;
				Weapon.FireSelector_Modes2[j].SelectorPosition = _backupModes2[j].SelectorPosition;
			}
		}
		if (_backupModes != null && ModeIndexToSub >= 0 && ModeIndexToSub < _backupModes.Length)
		{
			Modes[1].SelectorPosition = _backupModes[ModeIndexToSub].SelectorPosition;
			Modes[1].ModeType = _backupModes[ModeIndexToSub].ModeType;
			Modes[1].BurstAmount = _backupModes[ModeIndexToSub].BurstAmount;
			Modes[1].ARStyleBurst = _backupModes[ModeIndexToSub].ARStyleBurst;
			Modes[1].EngagementDelay = _backupModes[ModeIndexToSub].EngagementDelay;
		}
		if ((Object)(object)SelctorSwitch != (Object)null)
		{
			((FVRPhysicalObject)Weapon).SetAnimatedComponent(SelctorSwitch, Modes[1].SelectorPosition, InterpStyle, Axis);
		}
		Weapon.ResetCamBurst();
		_isGloballySafe = false;
		if (DebugLogging)
		{
			Debug.Log((object)"SafetyToggle: Global safe disabled, original modes restored.");
		}
	}

	private void ApplyModeToWeapon(int modeIndex)
	{
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: 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_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		FireSelectorMode val = Modes[modeIndex];
		if ((Object)(object)SelctorSwitch != (Object)null)
		{
			((FVRPhysicalObject)Weapon).SetAnimatedComponent(SelctorSwitch, val.SelectorPosition, InterpStyle, Axis);
		}
		FireSelectorMode val2 = Weapon.FireSelector_Modes[ModeIndexToSub];
		val2.ModeType = val.ModeType;
		val2.BurstAmount = val.BurstAmount;
		val2.ARStyleBurst = val.ARStyleBurst;
		val2.EngagementDelay = val.EngagementDelay;
		val2.SelectorPosition = val.SelectorPosition;
		if (Weapon.FireSelector_Modes2 != null && ModeIndexToSub >= 0 && ModeIndexToSub < Weapon.FireSelector_Modes2.Length)
		{
			FireSelectorMode val3 = Weapon.FireSelector_Modes2[ModeIndexToSub];
			val3.ModeType = val2.ModeType;
			val3.BurstAmount = val2.BurstAmount;
			val3.ARStyleBurst = val2.ARStyleBurst;
			val3.EngagementDelay = val2.EngagementDelay;
			val3.SelectorPosition = val2.SelectorPosition;
		}
		Weapon.ResetCamBurst();
	}
}
public class AttachableFirearmHelper : MonoBehaviour
{
	[Tooltip("Enables verbose console logging for debugging.")]
	public bool EnableDebugLogging = false;

	[Header("Component References")]
	[Tooltip("Reference to the AttachableFirearm. Automatically found if null.")]
	public AttachableFirearm Attachable;

	[Header("Fix 1: Muzzle Device & Suppressor Registration")]
	[Tooltip("Automatically detects and registers attached suppressors to this weapon and prevents host rifle hijacking.")]
	public bool FixMuzzleDevices = true;

	[Header("Fix 2: Standalone Downward Recoil")]
	[Tooltip("Fixes the native H3VR bug where shooting unattached kicks the muzzle downward into the floor.")]
	public bool FixStandaloneDownwardRecoil = true;

	[Tooltip("Multiplier for standalone vertical recoil. If the gun kicks DOWN, change this to -1.")]
	public float StandaloneRecoilDirection = 1f;

	[Header("Fix 3: Haptics")]
	[Tooltip("Injects vibration into both hands (including AltGrip) and host rifle hands upon firing.")]
	public bool FixHaptics = true;

	[Header("Fix 4: Recoil Redirection")]
	[Tooltip("Forces physical recoil onto the host rifle when the underbarrel is fired directly by off-hand.")]
	public bool FixOffHandRecoil = true;

	[Header("Fix 5: Magazine Release")]
	[Tooltip("Enables controller magazine drop via Thumbstick Click (Streamlined) and Touchpad South (Classic).")]
	public bool FixMagReleaseInput = true;

	[Header("Fix 6: Streamlined Bolt Catch")]
	[Tooltip("Allows holding the bolt catch open in Streamlined mode by pressing Thumbstick Up while racking.")]
	public bool FixStreamlinedBoltCatch = true;

	[Header("Fix 7: AI Perception")]
	[Tooltip("Ensures Sosigs and AI listeners register the gunshot when fired directly by off-hand.")]
	public bool FixAIPerception = true;

	[Header("Fix 8: Alt Grip Bridge")]
	[Tooltip("Allows the underbarrel alt grip to be held when mounted, routing stabilization to the host rifle.")]
	public bool BridgeAltGripToHost = true;

	private AttachableFirearm m_attachable;

	private AttachableClosedBoltWeapon m_closedBoltWeapon;

	private AttachableFirearmPhysicalObject m_physicalObject;

	private MuzzleDevice m_activeMuzzleDevice;

	private float m_lastTimeSinceFired = 1f;

	private bool m_hasFiredThisCycle = false;

	private void Awake()
	{
		if ((Object)(object)Attachable != (Object)null)
		{
			m_attachable = Attachable;
		}
		else
		{
			m_attachable = ((Component)this).GetComponent<AttachableFirearm>();
		}
		if ((Object)(object)m_attachable == (Object)null)
		{
			m_attachable = ((Component)this).GetComponentInParent<AttachableFirearm>();
		}
		if ((Object)(object)m_attachable == (Object)null)
		{
			Debug.LogError((object)"[AttachableFirearmHelper] Missing AttachableFirearm on GameObject or parents!");
			return;
		}
		ref AttachableClosedBoltWeapon closedBoltWeapon = ref m_closedBoltWeapon;
		AttachableFirearm attachable = m_attachable;
		closedBoltWeapon = (AttachableClosedBoltWeapon)(object)((attachable is AttachableClosedBoltWeapon) ? attachable : null);
		m_physicalObject = m_attachable.Attachment;
		if ((Object)(object)m_physicalObject == (Object)null)
		{
			m_physicalObject = ((Component)this).GetComponent<AttachableFirearmPhysicalObject>();
		}
	}

	private void Update()
	{
		if (!((Object)(object)m_attachable == (Object)null))
		{
			FVRFireArm hostFirearm = GetHostFirearm();
			if (BridgeAltGripToHost)
			{
				UpdateAltGripBridge(hostFirearm);
			}
			if (FixMuzzleDevices)
			{
				UpdateMuzzleDevices(hostFirearm);
			}
			ProcessBoltCatchInput();
			ProcessMagReleaseInput();
			MonitorShotDischarge(hostFirearm);
		}
	}

	private void UpdateMuzzleDevices(FVRFireArm hostFA)
	{
		if ((Object)(object)m_physicalObject == (Object)null || (Object)(object)m_attachable == (Object)null)
		{
			return;
		}
		MuzzleDevice val = null;
		FVRFireArmAttachmentMount[] componentsInChildren = ((Component)m_physicalObject).GetComponentsInChildren<FVRFireArmAttachmentMount>(true);
		foreach (FVRFireArmAttachmentMount val2 in componentsInChildren)
		{
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			for (int num = val2.AttachmentsList.Count - 1; num >= 0; num--)
			{
				if ((Object)(object)val2.AttachmentsList[num] == (Object)null || (Object)(object)val2.AttachmentsList[num].curMount != (Object)(object)val2)
				{
					val2.AttachmentsHash.Remove(val2.AttachmentsList[num]);
					val2.AttachmentsList.RemoveAt(num);
				}
			}
			val2.CheckStatus();
			for (int j = 0; j < val2.AttachmentsList.Count; j++)
			{
				FVRFireArmAttachment obj = val2.AttachmentsList[j];
				MuzzleDevice val3 = (MuzzleDevice)(object)((obj is MuzzleDevice) ? obj : null);
				if ((Object)(object)val3 != (Object)null)
				{
					val = val3;
					break;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				break;
			}
		}
		if (!((Object)(object)val != (Object)(object)m_activeMuzzleDevice))
		{
			return;
		}
		if ((Object)(object)m_activeMuzzleDevice != (Object)null)
		{
			m_attachable.DeRegisterMuzzleDevice(m_activeMuzzleDevice);
			MuzzleDevice activeMuzzleDevice = m_activeMuzzleDevice;
			Suppressor val4 = (Suppressor)(object)((activeMuzzleDevice is Suppressor) ? activeMuzzleDevice : null);
			if ((Object)(object)val4 != (Object)null)
			{
				m_attachable.RegisterSuppressor((Suppressor)null);
			}
			MuzzleDevice activeMuzzleDevice2 = m_activeMuzzleDevice;
			MuzzleBrake val5 = (MuzzleBrake)(object)((activeMuzzleDevice2 is MuzzleBrake) ? activeMuzzleDevice2 : null);
			if ((Object)(object)val5 != (Object)null)
			{
				m_attachable.RegisterMuzzleBrake((MuzzleBrake)null);
			}
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[AttachableFirearmHelper] Deregistered muzzle device from attachable.");
			}
		}
		m_activeMuzzleDevice = val;
		if (!((Object)(object)m_activeMuzzleDevice != (Object)null))
		{
			return;
		}
		m_attachable.RegisterMuzzleDevice(m_activeMuzzleDevice);
		MuzzleDevice activeMuzzleDevice3 = m_activeMuzzleDevice;
		Suppressor val6 = (Suppressor)(object)((activeMuzzleDevice3 is Suppressor) ? activeMuzzleDevice3 : null);
		if ((Object)(object)val6 != (Object)null)
		{
			m_attachable.RegisterSuppressor(val6);
		}
		MuzzleDevice activeMuzzleDevice4 = m_activeMuzzleDevice;
		MuzzleBrake val7 = (MuzzleBrake)(object)((activeMuzzleDevice4 is MuzzleBrake) ? activeMuzzleDevice4 : null);
		if ((Object)(object)val7 != (Object)null)
		{
			m_attachable.RegisterMuzzleBrake(val7);
		}
		if ((Object)(object)hostFA != (Object)null)
		{
			if (hostFA.MuzzleDevices.Contains(m_activeMuzzleDevice))
			{
				hostFA.DeRegisterMuzzleDevice(m_activeMuzzleDevice);
			}
			if ((Object)(object)val6 != (Object)null && (Object)(object)hostFA.CurrentSuppressor == (Object)(object)val6)
			{
				hostFA.RegisterSuppressor((Suppressor)null);
			}
			if ((Object)(object)val7 != (Object)null && (Object)(object)hostFA.CurrentMuzzleBrake == (Object)(object)val7)
			{
				hostFA.RegisterMuzzleBrake((MuzzleBrake)null);
			}
		}
		if (EnableDebugLogging)
		{
			Debug.Log((object)("[AttachableFirearmHelper] Successfully registered muzzle device to attachable: " + ((Object)((Component)m_activeMuzzleDevice).gameObject).name));
		}
	}

	private void UpdateAltGripBridge(FVRFireArm hostFA)
	{
		if (!((Object)(object)m_physicalObject != (Object)null) || !((Object)(object)((FVRPhysicalObject)m_physicalObject).AltGrip != (Object)null))
		{
			return;
		}
		FVRPhysicalObject val = (FVRPhysicalObject)((!((Object)(object)hostFA != (Object)null)) ? ((object)m_physicalObject) : ((object)hostFA));
		if ((Object)(object)((FVRPhysicalObject)m_physicalObject).AltGrip.PrimaryObject != (Object)(object)val)
		{
			((FVRPhysicalObject)m_physicalObject).AltGrip.PrimaryObject = val;
			if (EnableDebugLogging)
			{
				Debug.Log((object)("[AttachableFirearmHelper] Updated AltGrip.PrimaryObject to " + ((Object)((Component)val).gameObject).name));
			}
		}
	}

	private void ProcessBoltCatchInput()
	{
		if (FixStreamlinedBoltCatch && !((Object)(object)m_closedBoltWeapon == (Object)null) && m_closedBoltWeapon.HasBoltCatchButton && !((Object)(object)m_physicalObject == (Object)null) && ((FVRInteractiveObject)m_physicalObject).IsHeld && !((Object)(object)((FVRInteractiveObject)m_physicalObject).m_hand == (Object)null))
		{
			FVRViveHand hand = ((FVRInteractiveObject)m_physicalObject).m_hand;
			if (hand.IsInStreamlinedMode && hand.Input.TouchpadPressed && hand.Input.TouchpadAxes.y > 0.4f)
			{
				m_closedBoltWeapon.IsBoltCatchButtonHeld = true;
			}
		}
	}

	private void ProcessMagReleaseInput()
	{
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		if (!FixMagReleaseInput || (Object)(object)m_closedBoltWeapon == (Object)null || (Object)(object)m_physicalObject == (Object)null || !((FVRInteractiveObject)m_physicalObject).IsHeld || (Object)(object)((FVRInteractiveObject)m_physicalObject).m_hand == (Object)null)
		{
			return;
		}
		FVRViveHand hand = ((FVRInteractiveObject)m_physicalObject).m_hand;
		bool flag = false;
		if (hand.IsInStreamlinedMode)
		{
			if (hand.Input.TouchpadDown && hand.Input.TouchpadAxes.y <= 0.2f)
			{
				flag = true;
			}
		}
		else if (hand.Input.TouchpadDown && Vector2.Angle(hand.Input.TouchpadAxes, Vector2.down) < 45f)
		{
			flag = true;
		}
		if (flag && (Object)(object)((AttachableFirearm)m_closedBoltWeapon).Magazine != (Object)null)
		{
			m_closedBoltWeapon.ReleaseMag();
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[AttachableFirearmHelper] Magazine released via controller.");
			}
		}
	}

	private void MonitorShotDischarge(FVRFireArm hostFA)
	{
		bool flag = false;
		if ((Object)(object)m_closedBoltWeapon != (Object)null)
		{
			if (m_closedBoltWeapon.m_timeSinceFiredShot < 0.05f && m_lastTimeSinceFired >= 0.05f)
			{
				flag = true;
			}
			m_lastTimeSinceFired = m_closedBoltWeapon.m_timeSinceFiredShot;
		}
		if (flag && !m_hasFiredThisCycle)
		{
			m_hasFiredThisCycle = true;
			OnShotDischarged(hostFA);
		}
		else if (!flag)
		{
			m_hasFiredThisCycle = false;
		}
	}

	private void OnShotDischarged(FVRFireArm hostFA)
	{
		if (FixHaptics)
		{
			TriggerHaptics(hostFA);
		}
		if (FixOffHandRecoil && (Object)(object)hostFA != (Object)null)
		{
			if ((Object)(object)m_physicalObject != (Object)null && ((FVRInteractiveObject)m_physicalObject).IsHeld)
			{
				hostFA.Recoil(hostFA.IsTwoHandStabilized(), hostFA.IsForegripStabilized(), hostFA.IsShoulderStabilized(), m_attachable.GetRecoilProfile(), 1f);
				if (EnableDebugLogging)
				{
					Debug.Log((object)"[AttachableFirearmHelper] Injected recoil to host firearm from direct grip.");
				}
			}
		}
		else if ((Object)(object)hostFA == (Object)null && FixStandaloneDownwardRecoil && (Object)(object)m_attachable != (Object)null)
		{
			FVRFireArmRecoilProfile recoilProfile = m_attachable.GetRecoilProfile();
			if ((Object)(object)recoilProfile != (Object)null)
			{
				float num = recoilProfile.VerticalRotPerShot * Random.Range(0.9f, 1f) * StandaloneRecoilDirection;
				m_attachable.m_recoilX = Mathf.Clamp(m_attachable.m_recoilX + num, 0f - recoilProfile.MaxVerticalRot, recoilProfile.MaxVerticalRot);
				float num2 = Random.Range(0f - recoilProfile.HorizontalRotPerShot, recoilProfile.HorizontalRotPerShot);
				m_attachable.m_recoilY = Mathf.Clamp(m_attachable.m_recoilY + num2, 0f - recoilProfile.MaxHorizontalRot, recoilProfile.MaxHorizontalRot);
				float num3 = recoilProfile.ZLinearPerShot * Random.Range(0.9f, 1f);
				m_attachable.m_recoilLinearZ = Mathf.Clamp(m_attachable.m_recoilLinearZ + num3, m_attachable.m_recoilPoseHolderLocalPosStart.z, m_attachable.m_recoilPoseHolderLocalPosStart.z + recoilProfile.ZLinearMax);
			}
		}
		if (FixAIPerception && (Object)(object)hostFA != (Object)null)
		{
			GM.CurrentSceneSettings.OnShotFired(hostFA);
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[AttachableFirearmHelper] Dispatched OnShotFired to AI scene settings.");
			}
		}
	}

	private void TriggerHaptics(FVRFireArm hostFA)
	{
		if ((Object)(object)m_physicalObject != (Object)null)
		{
			if ((Object)(object)((FVRInteractiveObject)m_physicalObject).m_hand != (Object)null)
			{
				((FVRInteractiveObject)m_physicalObject).m_hand.Buzz(((FVRInteractiveObject)m_physicalObject).m_hand.Buzzer.Buzz_GunShot);
			}
			if ((Object)(object)((FVRPhysicalObject)m_physicalObject).AltGrip != (Object)null && (Object)(object)((FVRInteractiveObject)((FVRPhysicalObject)m_physicalObject).AltGrip).m_hand != (Object)null)
			{
				((FVRInteractiveObject)((FVRPhysicalObject)m_physicalObject).AltGrip).m_hand.Buzz(((FVRInteractiveObject)((FVRPhysicalObject)m_physicalObject).AltGrip).m_hand.Buzzer.Buzz_GunShot);
			}
		}
		if ((Object)(object)hostFA != (Object)null)
		{
			if ((Object)(object)((FVRInteractiveObject)hostFA).m_hand != (Object)null)
			{
				((FVRInteractiveObject)hostFA).m_hand.Buzz(((FVRInteractiveObject)hostFA).m_hand.Buzzer.Buzz_GunShot);
			}
			if ((Object)(object)((FVRPhysicalObject)hostFA).AltGrip != (Object)null && (Object)(object)((FVRInteractiveObject)((FVRPhysicalObject)hostFA).AltGrip).m_hand != (Object)null)
			{
				((FVRInteractiveObject)((FVRPhysicalObject)hostFA).AltGrip).m_hand.Buzz(((FVRInteractiveObject)hostFA).m_hand.Buzzer.Buzz_GunShot);
			}
		}
	}

	private FVRFireArm GetHostFirearm()
	{
		if ((Object)(object)m_physicalObject == (Object)null || (Object)(object)((FVRFireArmAttachment)m_physicalObject).curMount == (Object)null)
		{
			return null;
		}
		FVRFireArmAttachmentMount rootMount = ((FVRFireArmAttachment)m_physicalObject).curMount.GetRootMount();
		if ((Object)(object)rootMount != (Object)null && (Object)(object)rootMount.MyObject != (Object)null)
		{
			FVRPhysicalObject myObject = rootMount.MyObject;
			return (FVRFireArm)(object)((myObject is FVRFireArm) ? myObject : null);
		}
		return null;
	}
}
[DefaultExecutionOrder(100)]
public class AudioConsistencyAttachable : MonoBehaviour
{
	[Tooltip("Enables verbose console logging for debugging.")]
	public bool EnableDebugLogging = false;

	[Header("Audio Profiles")]
	[Tooltip("A complete clone of the weapon's factory audio set, used as the bulletproof fallback.")]
	public FVRFirearmAudioSet BaseHandlingAudioProfile;

	private AttachableFirearm m_firearm;

	private FVRFirearmAudioSet m_lastAudioClipSet;

	private FVRFirearmAudioSet m_lastSourceAudioClipSet;

	public void Awake()
	{
		m_firearm = ((Component)this).GetComponent<AttachableFirearm>();
		if ((Object)(object)m_firearm != (Object)null && (Object)(object)m_firearm.AudioClipSet != (Object)null)
		{
			m_lastSourceAudioClipSet = m_firearm.AudioClipSet;
			BaseHandlingAudioProfile = Object.Instantiate<FVRFirearmAudioSet>(m_lastSourceAudioClipSet);
			((Object)BaseHandlingAudioProfile).name = ((Object)((Component)m_firearm).gameObject).name + "_BaseAudioVault";
			FVRFirearmAudioSet val = CreateEnforcedClone(m_lastSourceAudioClipSet);
			m_firearm.AudioClipSet = val;
			m_lastAudioClipSet = val;
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[AudioConsistencyAttachable] Factory audio set successfully cloned into baseline vault and enforced on Awake.");
			}
		}
		else
		{
			Debug.LogError((object)"[AudioConsistencyAttachable] Fatal: No AttachableFirearm or AudioClipSet found on the object!");
		}
	}

	public void LateUpdate()
	{
		if ((Object)(object)m_firearm == (Object)null)
		{
			return;
		}
		FVRFirearmAudioSet audioClipSet = m_firearm.AudioClipSet;
		if ((Object)(object)audioClipSet == (Object)null || !((Object)(object)audioClipSet != (Object)(object)m_lastAudioClipSet))
		{
			return;
		}
		if ((Object)(object)audioClipSet == (Object)(object)m_lastSourceAudioClipSet)
		{
			m_firearm.AudioClipSet = m_lastAudioClipSet;
			return;
		}
		m_lastSourceAudioClipSet = audioClipSet;
		FVRFirearmAudioSet val = CreateEnforcedClone(audioClipSet);
		m_firearm.AudioClipSet = val;
		m_lastAudioClipSet = val;
		if (EnableDebugLogging)
		{
			Debug.Log((object)("[AudioConsistencyAttachable] TRULY new audio set detected. Cloned and enforced mechanical handling sounds on: " + ((Object)audioClipSet).name));
		}
	}

	private FVRFirearmAudioSet CreateEnforcedClone(FVRFirearmAudioSet source)
	{
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		FVRFirearmAudioSet val = Object.Instantiate<FVRFirearmAudioSet>(BaseHandlingAudioProfile);
		((Object)val).name = ((Object)source).name + "_Enforced";
		if (source.Shots_Main != null)
		{
			val.Shots_Main = source.Shots_Main;
		}
		if (source.Shots_Suppressed != null)
		{
			val.Shots_Suppressed = source.Shots_Suppressed;
		}
		if (source.Shots_LowPressure != null)
		{
			val.Shots_LowPressure = source.Shots_LowPressure;
		}
		if (source.MagazineIn != null)
		{
			val.MagazineIn = source.MagazineIn;
		}
		if (source.MagazineOut != null)
		{
			val.MagazineOut = source.MagazineOut;
		}
		if (source.MagazineInsertRound != null)
		{
			val.MagazineInsertRound = source.MagazineInsertRound;
		}
		if (source.MagazineEjectRound != null)
		{
			val.MagazineEjectRound = source.MagazineEjectRound;
		}
		val.UsesTail_Main = source.UsesTail_Main;
		val.UsesTail_Suppressed = source.UsesTail_Suppressed;
		val.UsesLowPressureSet = source.UsesLowPressureSet;
		val.TailPitchMod_Main = source.TailPitchMod_Main;
		val.TailPitchMod_Suppressed = source.TailPitchMod_Suppressed;
		val.TailPitchMod_LowPressure = source.TailPitchMod_LowPressure;
		val.Loudness_Primary = source.Loudness_Primary;
		val.Loudness_OperationMult = source.Loudness_OperationMult;
		return val;
	}
}
[DefaultExecutionOrder(100)]
public class ModularAttachableTubeFed : MonoBehaviour
{
	[Tooltip("Enables verbose console logging for debugging.")]
	public bool EnableDebugLogging = false;

	[Tooltip("The primary AttachableTubeFed component managing firing and cycling logic.")]
	public AttachableTubeFed TubeFed;

	[Tooltip("The ModularFVRPhysicalObject managing modular points on this weapon.")]
	public ModularFVRPhysicalObject ModularPhysicalObject;

	[Tooltip("The sliding bolt component on the shotgun.")]
	public AttachableTubeFedBolt Bolt;

	[Tooltip("The persistent sliding carriage handle component on the shotgun.")]
	public AttachableTubeFedFore Handle;

	[Tooltip("The foregrip GameObject containing FVRAlternateGrip to be resized/repositioned by modular handguards. If null, searches children.")]
	public GameObject Foregrip;

	[Tooltip("Fallback trigger transform if no modular trigger is installed.")]
	public Transform DefaultTrigger;

	[Tooltip("Fallback safety selector transform if no modular selector is installed.")]
	public Transform DefaultSafety;

	[Tooltip("Fallback muzzle position transform if no modular barrel is installed.")]
	public Transform DefaultMuzzle;

	[Tooltip("Fallback stock position transform if no modular stock is installed.")]
	public Transform DefaultStock;

	[Tooltip("If enabled, forces UsesAnimatedCarrier to false and UsesMagazines to true on Awake for box magazine feeding.")]
	public bool EnforceBoxMagazineFeed = true;

	[Tooltip("Enables dual-mode pump-action and semi-automatic switching on this shotgun.")]
	public bool EnableModeSwitching = true;

	[Tooltip("If enabled, forces the bolt to cycle automatically on all shell types in Automatic mode, even if low pressure.")]
	public bool AutoCycleAllRounds = true;

	[Header("Workbench Orientation")]
	[Tooltip("Rotational offset applied to the workbench alignment direction. Set Z to 180 to flip upright.")]
	public Vector3 WorkbenchQBRotationOffset = new Vector3(0f, 0f, 180f);

	[Tooltip("Positional offset applied to the workbench slot anchor.")]
	public Vector3 WorkbenchQBPositionOffset = Vector3.zero;

	private bool m_originalHasTrigger;

	private bool m_originalHasSafety;

	private float m_originalTriggerBreakThreshold;

	private float m_originalTriggerResetThreshold;

	private FireArmRoundType m_originalRoundType;

	private FireArmMagazineType m_originalMagazineType;

	private FVRFireArmRecoilProfile m_originalRecoilProfile;

	private FVRFireArmRecoilProfile m_originalRecoilProfileStocked;

	private FVRFirearmAudioSet m_originalAudioClipSet;

	private float m_originalBoltSpeedForward;

	private float m_originalBoltSpeedRearward;

	private float m_originalBoltSpringStiffness;

	private bool m_hasSubscribed;

	private bool m_wasMounted;

	private TransformProxy m_cachedSkinProxy;

	private ModularWorkshopPlatform m_cachedPlatform;

	private FVRQuickBeltSlot m_lastQbSlot;

	private Vector3 m_originalPlatformPosePos;

	private bool m_isSlottedOnWorkbench;

	private ModularWeaponPartsAttachmentPoint[] m_originalAttachmentPoints;

	private List<ModularWeaponPartsAttachmentPoint> m_cachedSubAttachmentPoints;

	private string m_originalSkinPath;

	private Transform m_originalForegripParent;

	private Vector3 m_originalForegripLocalPos;

	private Quaternion m_originalForegripLocalRot;

	private bool m_originalForegripActive;

	private bool m_wasChamberSpentLastFrame;

	public void Awake()
	{
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)TubeFed == (Object)null)
		{
			TubeFed = ((Component)this).GetComponent<AttachableTubeFed>();
			if ((Object)(object)TubeFed == (Object)null)
			{
				TubeFed = ((Component)this).GetComponentInParent<AttachableTubeFed>();
			}
		}
		if ((Object)(object)TubeFed == (Object)null)
		{
			Debug.LogError((object)"[ModularAttachableTubeFed] Fatal: AttachableTubeFed component not found on GameObject or parents!");
			return;
		}
		if ((Object)(object)ModularPhysicalObject == (Object)null)
		{
			ModularPhysicalObject = ((Component)this).GetComponentInChildren<ModularFVRPhysicalObject>(true);
			if ((Object)(object)ModularPhysicalObject == (Object)null)
			{
				ModularPhysicalObject = ((Component)this).GetComponent<ModularFVRPhysicalObject>();
			}
		}
		if ((Object)(object)ModularPhysicalObject == (Object)null)
		{
			Debug.LogError((object)"[ModularAttachableTubeFed] Fatal: ModularFVRPhysicalObject component not found on GameObject or children!");
			return;
		}
		if ((Object)(object)ModularPhysicalObject != (Object)null)
		{
			m_originalAttachmentPoints = ModularPhysicalObject.ModularWeaponPartsAttachmentPoints;
			m_originalSkinPath = ModularPhysicalObject.SkinPath;
		}
		if ((Object)(object)Bolt == (Object)null)
		{
			Bolt = TubeFed.Bolt;
			if ((Object)(object)Bolt == (Object)null)
			{
				Bolt = ((Component)this).GetComponentInChildren<AttachableTubeFedBolt>();
			}
		}
		if ((Object)(object)Handle == (Object)null)
		{
			Handle = TubeFed.Handle;
			if ((Object)(object)Handle == (Object)null)
			{
				Handle = ((Component)this).GetComponentInChildren<AttachableTubeFedFore>();
			}
		}
		if ((Object)(object)Foregrip == (Object)null)
		{
			FVRAlternateGrip componentInChildren = ((Component)this).GetComponentInChildren<FVRAlternateGrip>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				Foregrip = ((Component)componentInChildren).gameObject;
			}
		}
		if ((Object)(object)Foregrip != (Object)null)
		{
			m_originalForegripParent = Foregrip.transform.parent;
			m_originalForegripLocalPos = Foregrip.transform.localPosition;
			m_originalForegripLocalRot = Foregrip.transform.localRotation;
			m_originalForegripActive = Foregrip.activeSelf;
		}
		if ((Object)(object)DefaultTrigger == (Object)null)
		{
			DefaultTrigger = TubeFed.Trigger;
		}
		if ((Object)(object)DefaultSafety == (Object)null)
		{
			DefaultSafety = TubeFed.Safety;
		}
		if ((Object)(object)DefaultMuzzle == (Object)null)
		{
			DefaultMuzzle = ((AttachableFirearm)TubeFed).MuzzlePos;
		}
		if ((Object)(object)DefaultStock == (Object)null)
		{
			DefaultStock = ((AttachableFirearm)TubeFed).StockPos;
		}
		m_originalHasTrigger = TubeFed.HasTrigger;
		m_originalHasSafety = TubeFed.HasSafety;
		m_originalTriggerBreakThreshold = TubeFed.TriggerBreakThreshold;
		m_originalTriggerResetThreshold = TubeFed.TriggerResetThreshold;
		m_originalRoundType = ((AttachableFirearm)TubeFed).RoundType;
		m_originalMagazineType = ((AttachableFirearm)TubeFed).MagazineType;
		m_originalRecoilProfile = ((AttachableFirearm)TubeFed).RecoilProfile;
		m_originalRecoilProfileStocked = ((AttachableFirearm)TubeFed).RecoilProfileStocked;
		m_originalAudioClipSet = ((AttachableFirearm)TubeFed).AudioClipSet;
		if ((Object)(object)((AttachableFirearm)TubeFed).RecoilProfileStocked == (Object)null)
		{
			((AttachableFirearm)TubeFed).UsesStockedRecoilProfile = false;
		}
		if ((Object)(object)Bolt != (Object)null)
		{
			m_originalBoltSpeedForward = Bolt.Speed_Forward;
			m_originalBoltSpeedRearward = 0f - Mathf.Abs(Bolt.Speed_Rearward);
			Bolt.Speed_Rearward = m_originalBoltSpeedRearward;
			m_originalBoltSpringStiffness = Bolt.SpringStiffness;
		}
		if (EnforceBoxMagazineFeed)
		{
			TubeFed.UsesAnimatedCarrier = false;
			((AttachableFirearm)TubeFed).UsesMagazines = true;
		}
		if (EnableModeSwitching)
		{
			TubeFed.CanModeSwitch = true;
		}
		ForceCheckMountState();
	}

	public void Start()
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		if ((Object)(object)ModularPhysicalObject != (Object)null && !m_hasSubscribed)
		{
			ModularPhysicalObject.PartAdded += new PartAdded(OnModularPartAdded);
			m_hasSubscribed = true;
		}
		RebuildWeaponState();
		ForceCheckMountState();
	}

	public void OnEnable()
	{
		ForceCheckMountState();
	}

	public void OnTransformParentChanged()
	{
		ForceCheckMountState();
	}

	public void Update()
	{
		ForceCheckMountState();
		UpdateWorkbenchOrientation();
		UpdateModeSwitchInput();
		UpdateSemiAutoImpulse();
		CheckForDestroyedReferences();
	}

	public void OnDestroy()
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		if (m_hasSubscribed && (Object)(object)ModularPhysicalObject != (Object)null)
		{
			ModularPhysicalObject.PartAdded -= new PartAdded(OnModularPartAdded);
			m_hasSubscribed = false;
		}
		if (m_isSlottedOnWorkbench && (Object)(object)m_cachedPlatform != (Object)null)
		{
			if ((Object)(object)m_cachedPlatform.QuickBeltSlot != (Object)null && (Object)(object)m_cachedPlatform.QuickBeltSlot.PoseOverride != (Object)null)
			{
				m_cachedPlatform.QuickBeltSlot.PoseOverride.localPosition = m_originalPlatformPosePos;
			}
			m_isSlottedOnWorkbench = false;
		}
	}

	private FVRViveHand GetHoldingHand()
	{
		if ((Object)(object)TubeFed == (Object)null)
		{
			return null;
		}
		if ((Object)(object)TubeFed.Handle != (Object)null && (Object)(object)((FVRInteractiveObject)TubeFed.Handle).m_hand != (Object)null)
		{
			return ((FVRInteractiveObject)TubeFed.Handle).m_hand;
		}
		if ((Object)(object)((AttachableFirearm)TubeFed).Interface != (Object)null && (Object)(object)((FVRInteractiveObject)((AttachableFirearm)TubeFed).Interface).m_hand != (Object)null)
		{
			return ((FVRInteractiveObject)((AttachableFirearm)TubeFed).Interface).m_hand;
		}
		if ((Object)(object)Foregrip != (Object)null)
		{
			FVRAlternateGrip component = Foregrip.GetComponent<FVRAlternateGrip>();
			if ((Object)(object)component != (Object)null && (Object)(object)((FVRInteractiveObject)component).m_hand != (Object)null)
			{
				return ((FVRInteractiveObject)component).m_hand;
			}
		}
		if ((Object)(object)((AttachableFirearm)TubeFed).Attachment != (Object)null && (Object)(object)((FVRInteractiveObject)((AttachableFirearm)TubeFed).Attachment).m_hand != (Object)null)
		{
			return ((FVRInteractiveObject)((AttachableFirearm)TubeFed).Attachment).m_hand;
		}
		return null;
	}

	private void UpdateModeSwitchInput()
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		if (!EnableModeSwitching || (Object)(object)TubeFed == (Object)null)
		{
			return;
		}
		FVRViveHand holdingHand = GetHoldingHand();
		if ((Object)(object)holdingHand == (Object)null)
		{
			return;
		}
		bool flag = false;
		if (holdingHand.IsInStreamlinedMode)
		{
			if (holdingHand.Input.AXButtonDown)
			{
				flag = true;
			}
		}
		else
		{
			Vector2 touchpadAxes = holdingHand.Input.TouchpadAxes;
			if (holdingHand.Input.TouchpadDown && ((Vector2)(ref touchpadAxes)).magnitude > 0.2f && Vector2.Angle(touchpadAxes, Vector2.down) <= 45f)
			{
				flag = true;
			}
		}
		if (flag)
		{
			ToggleFireMode();
		}
	}

	public void ToggleFireMode()
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)TubeFed == (Object)null) && (!((Object)(object)TubeFed.Bolt != (Object)null) || (int)TubeFed.Bolt.CurPos == 0) && (!TubeFed.HasHandle || !((Object)(object)TubeFed.Handle != (Object)null) || (int)TubeFed.Handle.CurPos == 0))
		{
			bool isHammerCocked = TubeFed.m_isHammerCocked;
			TubeFed.m_isHammerCocked = false;
			TubeFed.ToggleMode();
			TubeFed.m_isHammerCocked = isHammerCocked;
			if (EnableDebugLogging)
			{
				Debug.Log((object)("[ModularAttachableTubeFed] Toggled shotgun mode to: " + ((object)Unsafe.As<ShotgunMode, ShotgunMode>(ref TubeFed.Mode)/*cast due to .constrained prefix*/).ToString()));
			}
		}
	}

	private void UpdateSemiAutoImpulse()
	{
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Invalid comparison between Unknown and I4
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)TubeFed == (Object)null || (Object)(object)Bolt == (Object)null || (Object)(object)TubeFed.Chamber == (Object)null)
		{
			return;
		}
		bool flag = TubeFed.Chamber.IsFull && TubeFed.Chamber.IsSpent;
		if (flag && !m_wasChamberSpentLastFrame && (int)TubeFed.Mode == 1 && AutoCycleAllRounds && (int)Bolt.CurPos == 0 && Bolt.m_curBoltSpeed == 0f)
		{
			Bolt.ImpartFiringImpulse();
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[ModularAttachableTubeFed] Imparted firing impulse for low-pressure shell in Automatic mode.");
			}
		}
		m_wasChamberSpentLastFrame = flag;
	}

	private void UpdateWorkbenchOrientation()
	{
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0211: Unknown result type (might be due to invalid IL or missing references)
		//IL_0216: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0260: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Unknown result type (might be due to invalid IL or missing references)
		//IL_026a: Unknown result type (might be due to invalid IL or missing references)
		//IL_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Unknown result type (might be due to invalid IL or missing references)
		//IL_0286: Unknown result type (might be due to invalid IL or missing references)
		//IL_0243: Unknown result type (might be due to invalid IL or missing references)
		//IL_0248: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)TubeFed == (Object)null || (Object)(object)((AttachableFirearm)TubeFed).Attachment == (Object)null)
		{
			return;
		}
		FVRQuickBeltSlot quickbeltSlot = ((FVRPhysicalObject)((AttachableFirearm)TubeFed).Attachment).QuickbeltSlot;
		if ((Object)(object)quickbeltSlot != (Object)(object)m_lastQbSlot)
		{
			m_lastQbSlot = quickbeltSlot;
			if (m_isSlottedOnWorkbench && (Object)(object)m_cachedPlatform != (Object)null)
			{
				if ((Object)(object)m_cachedPlatform.QuickBeltSlot != (Object)null && (Object)(object)m_cachedPlatform.QuickBeltSlot.PoseOverride != (Object)null)
				{
					m_cachedPlatform.QuickBeltSlot.PoseOverride.localPosition = m_originalPlatformPosePos;
				}
				m_isSlottedOnWorkbench = false;
				if (EnableDebugLogging)
				{
					Debug.Log((object)"[ModularAttachableTubeFed] Object unslotted from workbench.");
				}
			}
			m_cachedPlatform = null;
			if ((Object)(object)quickbeltSlot != (Object)null)
			{
				m_cachedPlatform = ((Component)quickbeltSlot).GetComponentInParent<ModularWorkshopPlatform>();
				if ((Object)(object)m_cachedPlatform == (Object)null)
				{
					m_cachedPlatform = ((Component)quickbeltSlot).GetComponent<ModularWorkshopPlatform>();
				}
				if ((Object)(object)m_cachedPlatform == (Object)null && (Object)(object)ModularPhysicalObject != (Object)null && (Object)(object)ModularPhysicalObject.WorkshopPlatform != (Object)null && (Object)(object)ModularPhysicalObject.WorkshopPlatform.QuickBeltSlot == (Object)(object)quickbeltSlot)
				{
					m_cachedPlatform = ModularPhysicalObject.WorkshopPlatform;
				}
			}
		}
		if ((Object)(object)m_cachedPlatform != (Object)null && (Object)(object)m_cachedPlatform.AlignmentDirection != (Object)null && (Object)(object)m_cachedPlatform.QuickBeltSlot != (Object)null && (Object)(object)m_cachedPlatform.QuickBeltSlot.PoseOverride != (Object)null)
		{
			if (!m_isSlottedOnWorkbench)
			{
				m_isSlottedOnWorkbench = true;
				m_originalPlatformPosePos = m_cachedPlatform.QuickBeltSlot.PoseOverride.localPosition;
			}
			Quaternion val = Quaternion.identity;
			if ((Object)(object)((FVRInteractiveObject)((AttachableFirearm)TubeFed).Attachment).QBPoseOverride != (Object)null)
			{
				val = ((FVRInteractiveObject)((AttachableFirearm)TubeFed).Attachment).QBPoseOverride.localRotation;
			}
			Quaternion val2 = m_cachedPlatform.AlignmentDirection.rotation * Quaternion.Euler(WorkbenchQBRotationOffset) * val;
			if (m_cachedPlatform.QuickBeltSlot.PoseOverride.rotation != val2)
			{
				m_cachedPlatform.QuickBeltSlot.PoseOverride.rotation = val2;
			}
			if (WorkbenchQBPositionOffset != Vector3.zero)
			{
				m_cachedPlatform.QuickBeltSlot.PoseOverride.localPosition = m_originalPlatformPosePos + WorkbenchQBPositionOffset;
			}
		}
	}

	private void ForceCheckMountState()
	{
		if (!((Object)(object)TubeFed == (Object)null) && !((Object)(object)((AttachableFirearm)TubeFed).Attachment == (Object)null) && !((Object)(object)ModularPhysicalObject == (Object)null))
		{
			bool flag = (Object)(object)((FVRFireArmAttachment)((AttachableFirearm)TubeFed).Attachment).curMount != (Object)null;
			if (flag && ModularPhysicalObject.ReceiverSkinUIPointProxy != null)
			{
				m_cachedSkinProxy = ModularPhysicalObject.ReceiverSkinUIPointProxy;
				ModularPhysicalObject.ReceiverSkinUIPointProxy = null;
			}
			if (flag != m_wasMounted)
			{
				m_wasMounted = flag;
				SetModularPointsMountedState(flag);
			}
			else if (flag && ((Component)ModularPhysicalObject).gameObject.activeSelf)
			{
				SetModularPointsMountedState(isMounted: true);
			}
		}
	}

	private void SetModularPointsMountedState(bool isMounted)
	{
		if ((Object)(object)ModularPhysicalObject == (Object)null)
		{
			return;
		}
		((Behaviour)ModularPhysicalObject).enabled = !isMounted;
		if (isMounted)
		{
			ModularWorkshopUI[] componentsInChildren = ((Component)this).GetComponentsInChildren<ModularWorkshopUI>(true);
			if (componentsInChildren != null)
			{
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					if ((Object)(object)componentsInChildren[i] != (Object)null && (Object)(object)((Component)componentsInChildren[i]).gameObject != (Object)null)
					{
						Object.Destroy((Object)(object)((Component)componentsInChildren[i]).gameObject);
					}
				}
			}
			if (ModularPhysicalObject.SubAttachmentPoints != null && ModularPhysicalObject.SubAttachmentPoints.Count > 0)
			{
				m_cachedSubAttachmentPoints = new List<ModularWeaponPartsAttachmentPoint>(ModularPhysicalObject.SubAttachmentPoints);
				ModularPhysicalObject.SubAttachmentPoints.Clear();
			}
			if (ModularPhysicalObject.ReceiverSkinUIPointProxy != null)
			{
				m_cachedSkinProxy = ModularPhysicalObject.ReceiverSkinUIPointProxy;
				ModularPhysicalObject.ReceiverSkinUIPointProxy = null;
			}
			ModularPhysicalObject.ModularWeaponPartsAttachmentPoints = (ModularWeaponPartsAttachmentPoint[])(object)new ModularWeaponPartsAttachmentPoint[0];
			if (!string.IsNullOrEmpty(m_originalSkinPath))
			{
				ModularPhysicalObject.SkinPath = m_originalSkinPath + "_MOUNTED";
			}
		}
		else
		{
			if (m_originalAttachmentPoints != null)
			{
				ModularPhysicalObject.ModularWeaponPartsAttachmentPoints = m_originalAttachmentPoints;
			}
			if (m_cachedSubAttachmentPoints != null && m_cachedSubAttachmentPoints.Count > 0)
			{
				ModularPhysicalObject.SubAttachmentPoints = new List<ModularWeaponPartsAttachmentPoint>(m_cachedSubAttachmentPoints);
				m_cachedSubAttachmentPoints.Clear();
			}
			if (m_cachedSkinProxy != null)
			{
				ModularPhysicalObject.ReceiverSkinUIPointProxy = m_cachedSkinProxy;
				m_cachedSkinProxy = null;
			}
			if (!string.IsNullOrEmpty(m_originalSkinPath))
			{
				ModularPhysicalObject.SkinPath = m_originalSkinPath;
			}
			ModularPhysicalObject.ConvertTransformsToProxies();
			if (EnableDebugLogging)
			{
				Debug.Log((object)("[ModularAttachableTubeFed] Restored ModularWeaponPartsAttachmentPoints (" + ModularPhysicalObject.ModularWeaponPartsAttachmentPoints.Length + " points) and sub-points after unmounting."));
			}
		}
	}

	private void CheckForDestroyedReferences()
	{
		bool flag = false;
		if (((AttachableFirearm)TubeFed).HasActiveShoulderStock && (Object)(object)((AttachableFirearm)TubeFed).StockPos == (Object)null)
		{
			flag = true;
		}
		if (TubeFed.HasTrigger && (Object)(object)TubeFed.Trigger == (Object)null)
		{
			flag = true;
		}
		if (TubeFed.HasSafety && (Object)(object)TubeFed.Safety == (Object)null)
		{
			flag = true;
		}
		if (flag)
		{
			if (EnableDebugLogging)
			{
				Debug.Log((object)"[ModularAttachableTubeFed] Detected destroyed transform reference (part removed). Triggering state rebuild.");
			}
			RebuildWeaponState();
		}
	}

	public void OnModularPartAdded(ModularWeaponPartsAttachmentPoint attachmentPoint, ModularWeaponPart newPart)
	{
		if (!((Object)(object)newPart == (Object)null) && !((Object)(object)TubeFed == (Object)null))
		{
			RebuildWeaponState();
		}
	}

	private List<ModularWeaponPart> GetActiveWeaponParts()
	{
		List<ModularWeaponPart> list = new List<ModularWeaponPart>();
		ModularWeaponPart[] componentsInChildren = ((Component)this).GetComponentsInChildren<ModularWeaponPart>(false);
		if (componentsInChildren != null)
		{
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null && ((Component)componentsInChildren[i]).gameObject.activeInHierarchy && !list.Contains(componentsInChildren[i]))
				{
					list.Add(componentsInChildren[i]);
				}
			}
		}
		return list;
	}

	private void RebuildWeaponState()
	{
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04de: Unknown result type (might be due to invalid IL or missing references)
		//IL_04e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_05f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_05fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0701: Unknown result type (might be due to invalid IL or missing references)
		//IL_0717: Unknown result type (might be due to invalid IL or missing references)
		//IL_088f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0891: Unknown result type (might be due to invalid IL or missing references)
		//IL_07b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_07c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_08c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_08c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_08b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_08b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0800: Unknown result type (might be due to invalid IL or missing references)
		//IL_0816: Unknown result type (might be due to invalid IL or missing references)
		//IL_09c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_09cc: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)TubeFed == (Object)null)
		{
			return;
		}
		Transform val = null;
		string text = string.Empty;
		Transform val2 = null;
		Transform val3 = null;
		Transform stockPos = DefaultStock;
		bool hasActiveShoulderStock = false;
		string text2 = "Factory Default";
		Transform trigger = DefaultTrigger;
		bool hasTrigger = m_originalHasTrigger && (Object)(object)DefaultTrigger != (Object)null;
		Transform safety = DefaultSafety;
		bool hasSafety = m_originalHasSafety;
		FireArmRoundType roundType = m_originalRoundType;
		FireArmMagazineType magazineType = m_originalMagazineType;
		FVRFireArmRecoilProfile recoilProfile = m_originalRecoilProfile;
		FVRFireArmRecoilProfile recoilProfileStocked = m_originalRecoilProfileStocked;
		FVRFirearmAudioSet audioClipSet = m_originalAudioClipSet;
		float triggerBreakThreshold = m_originalTriggerBreakThreshold;
		float triggerResetThreshold = m_originalTriggerResetThreshold;
		float speed_Forward = m_originalBoltSpeedForward;
		float num = m_originalBoltSpeedRearward;
		float springStiffness = m_originalBoltSpringStiffness;
		ModularHandguard val4 = null;
		ModularBarrel val5 = null;
		ModularBarrelExtension val6 = null;
		List<ModularWeaponPart> activeWeaponParts = GetActiveWeaponParts();
		for (int i = 0; i < activeWeaponParts.Count; i++)
		{
			ModularWeaponPart val7 = activeWeaponParts[i];
			if ((Object)(object)val7 == (Object)null || (Object)(object)((Component)val7).gameObject == (Object)null || !((Component)val7).gameObject.activeInHierarchy)
			{
				continue;
			}
			ModularBarrel val8 = ((Component)val7).GetComponent<ModularBarrel>();
			if ((Object)(object)val8 == (Object)null)
			{
				val8 = ((Component)val7).GetComponentInChildren<ModularBarrel>();
			}
			if ((Object)(object)val8 != (Object)null)
			{
				val5 = val8;
			}
			ModularBarrelExtension val9 = ((Component)val7).GetComponent<ModularBarrelExtension>();
			if ((Object)(object)val9 == (Object)null)
			{
				val9 = ((Component)val7).GetComponentInChildren<ModularBarrelExtension>();
			}
			if ((Object)(object)val9 != (Object)null)
			{
				val6 = val9;
			}
			ModularHandguard val10 = ((Component)val7).GetComponent<ModularHandguard>();
			if ((Object)(object)val10 == (Object)null)
			{
				val10 = ((Component)val7).GetComponentInChildren<ModularHandguard>();
			}
			if ((Object)(object)val10 != (Object)null)
			{
				val4 = val10;
			}
			FirearmModificationAddon val11 = ((Component)val7).GetComponent<FirearmModificationAddon>();
			if ((Object)(object)val11 == (Object)null)
			{
				val11 = ((Component)val7).GetComponentInChildren<FirearmModificationAddon>();
			}
			if ((Object)(object)val11 != (Object)null)
			{
				if ((Object)(object)val11.Trigger != (Object)null)
				{
					trigger = val11.Trigger;
					hasTrigger = true;
				}
				if (val11.ChangesTriggerThresholds)
				{
					triggerBreakThreshold = val11.TriggerThreshold;
					triggerResetThreshold = val11.TriggerReset;
				}
				if ((Object)(object)val11.FireSelector != (Object)null)
				{
					safety = val11.FireSelector;
					hasSafety = true;
				}
				if (val11.AdjustsFireRate)
				{
					if (val11.BoltSpeed_Forward > 0f)
					{
						speed_Forward = val11.BoltSpeed_Forward;
					}
					if (val11.BoltSpeed_Rearward > 0f)
					{
						num = val11.BoltSpeed_Rearward;
					}
					if (val11.BoltSpringStiffness > 0f)
					{
						springStiffness = val11.BoltSpringStiffness;
					}
				}
			}
			ModularStock val12 = ((Component)val7).GetComponent<ModularStock>();
			if ((Object)(object)val12 == (Object)null)
			{
				val12 = ((Component)val7).GetComponentInChildren<ModularStock>();
			}
			if ((Object)(object)val12 != (Object)null)
			{
				Transform val13 = val12.StockPoint;
				if ((Object)(object)val13 == (Object)null)
				{
					val13 = FindChildTransformRecursive(((Component)val7).transform, "Point_Stock");
				}
				if ((Object)(object)val13 == (