Decompiled source of DualSenseRain v3.0.1

DualSenseRain.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using EntityStates;
using EntityStates.DroneTech.Weapon.Paint;
using EntityStates.GlobalSkills.LunarDetonator;
using EntityStates.GlobalSkills.LunarNeedle;
using EntityStates.Heretic.Weapon;
using EntityStates.Railgunner.Reload;
using EntityStates.Seeker;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Microsoft.Win32.SafeHandles;
using Rewired;
using RoR2;
using RoR2.CameraModes;
using RoR2.GamepadVibration;
using RoR2.Projectile;
using RoR2.Skills;
using RoR2.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DualSenseRain")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DualSenseRain")]
[assembly: AssemblyTitle("DualSenseRain")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DualSenseRain
{
	internal sealed class DualSenseHid : IDisposable
	{
		private static class Crc32
		{
			private static readonly uint[] Table = BuildTable();

			private static uint[] BuildTable()
			{
				uint[] array = new uint[256];
				for (uint num = 0u; num < 256; num++)
				{
					uint num2 = num;
					for (int i = 0; i < 8; i++)
					{
						num2 = (((num2 & 1) != 0) ? (0xEDB88320u ^ (num2 >> 1)) : (num2 >> 1));
					}
					array[num] = num2;
				}
				return array;
			}

			public static uint Compute(byte seed, byte[] data, int offset, int count)
			{
				uint num = uint.MaxValue;
				num = Table[(num ^ seed) & 0xFF] ^ (num >> 8);
				for (int i = offset; i < offset + count; i++)
				{
					num = Table[(num ^ data[i]) & 0xFF] ^ (num >> 8);
				}
				return ~num;
			}
		}

		private static class Native
		{
			public struct SP_DEVICE_INTERFACE_DATA
			{
				public int cbSize;

				public Guid InterfaceClassGuid;

				public int Flags;

				public IntPtr Reserved;
			}

			public struct HIDD_ATTRIBUTES
			{
				public int Size;

				public ushort VendorID;

				public ushort ProductID;

				public ushort VersionNumber;
			}

			public struct HIDP_CAPS
			{
				public ushort Usage;

				public ushort UsagePage;

				public ushort InputReportByteLength;

				public ushort OutputReportByteLength;

				public ushort FeatureReportByteLength;

				[MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
				public ushort[] Reserved;

				public ushort NumberLinkCollectionNodes;

				public ushort NumberInputButtonCaps;

				public ushort NumberInputValueCaps;

				public ushort NumberInputDataIndices;

				public ushort NumberOutputButtonCaps;

				public ushort NumberOutputValueCaps;

				public ushort NumberOutputDataIndices;

				public ushort NumberFeatureButtonCaps;

				public ushort NumberFeatureValueCaps;

				public ushort NumberFeatureDataIndices;
			}

			public const uint DIGCF_PRESENT = 2u;

			public const uint DIGCF_DEVICEINTERFACE = 16u;

			public const uint GENERIC_READ = 2147483648u;

			public const uint GENERIC_WRITE = 1073741824u;

			public const uint FILE_SHARE_READ = 1u;

			public const uint FILE_SHARE_WRITE = 2u;

			public const uint OPEN_EXISTING = 3u;

			public const int HIDP_STATUS_SUCCESS = 1114112;

			[DllImport("hid.dll")]
			public static extern void HidD_GetHidGuid(out Guid hidGuid);

			[DllImport("hid.dll")]
			public static extern bool HidD_GetAttributes(SafeFileHandle device, ref HIDD_ATTRIBUTES attributes);

			[DllImport("hid.dll")]
			public static extern bool HidD_GetPreparsedData(SafeFileHandle device, out IntPtr preparsedData);

			[DllImport("hid.dll")]
			public static extern bool HidD_FreePreparsedData(IntPtr preparsedData);

			[DllImport("hid.dll", SetLastError = true)]
			public static extern bool HidD_SetOutputReport(SafeFileHandle device, byte[] buffer, int length);

			[DllImport("hid.dll", SetLastError = true)]
			public static extern bool HidD_GetFeature(SafeFileHandle device, byte[] buffer, int length);

			[DllImport("hid.dll")]
			public static extern int HidP_GetCaps(IntPtr preparsedData, out HIDP_CAPS caps);

			[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
			public static extern IntPtr SetupDiGetClassDevsW(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, uint flags);

			[DllImport("setupapi.dll", SetLastError = true)]
			public static extern bool SetupDiEnumDeviceInterfaces(IntPtr devInfo, IntPtr devInfoData, ref Guid interfaceClassGuid, uint memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);

			[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
			public static extern bool SetupDiGetDeviceInterfaceDetailW(IntPtr devInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr detailData, uint detailDataSize, out uint requiredSize, IntPtr deviceInfoData);

			[DllImport("setupapi.dll", SetLastError = true)]
			public static extern bool SetupDiDestroyDeviceInfoList(IntPtr devInfo);

			[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
			public static extern SafeFileHandle CreateFileW(string fileName, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);

			[DllImport("kernel32.dll", SetLastError = true)]
			public static extern bool WriteFile(SafeFileHandle file, byte[] buffer, uint toWrite, out uint written, IntPtr overlapped);
		}

		private const ushort SonyVid = 1356;

		private const ushort DualSensePid = 3302;

		private const ushort DualSenseEdgePid = 3570;

		private SafeFileHandle handle;

		private bool bluetooth;

		private int outputLength;

		private byte btSeq;

		private readonly object sync = new object();

		private readonly byte[] pendingRight = new byte[11];

		private readonly byte[] pendingLeft = new byte[11];

		private byte pendingHeavy;

		private byte pendingLight;

		private bool pendingMotors;

		private bool pendingLights;

		private byte pendingRed;

		private byte pendingGreen;

		private byte pendingBlue;

		private byte pendingLeds;

		private bool lightSetupDone;

		private bool dirty;

		private Thread worker;

		private volatile bool running;

		private readonly AutoResetEvent wake = new AutoResetEvent(initialState: false);

		public static Action<string> Log = delegate
		{
		};

		public int WritesOk;

		public int WritesFailed;

		public volatile bool Blocked;

		public string Mode = "?";

		public bool AudioSetup = true;

		public byte SpeakerVolume = 127;

		public byte HeadphoneVolume = 100;

		public byte SpeakerBoost;

		private bool rumbleWasOn;

		private bool vibV2;

		public GameInputPad Gi;

		private IntPtr giDev;

		private bool giOff;

		private int giFails;

		private DateTime nextGiTry = DateTime.MinValue;

		private int consecutiveTimeouts;

		private bool usedFallback;

		private readonly OverlappedIo ioWorker = new OverlappedIo();

		private readonly OverlappedIo ioOther = new OverlappedIo();

		public Gyro Gyro;

		private readonly byte[] sentRight = new byte[11];

		private readonly byte[] sentLeft = new byte[11];

		private DateTime lastTrigFull = DateTime.MinValue;

		public bool IsConnected
		{
			get
			{
				if (!HidOpen)
				{
					return giDev != IntPtr.Zero;
				}
				return true;
			}
		}

		private bool HidOpen
		{
			get
			{
				if (handle != null && !handle.IsInvalid)
				{
					return !handle.IsClosed;
				}
				return false;
			}
		}

		public bool IsBluetooth => bluetooth;

		public string DevicePath { get; private set; }

		public string HapticsEndpoint { get; private set; } = "";

		public void Start()
		{
			if (!running)
			{
				running = true;
				worker = new Thread(WorkerLoop)
				{
					IsBackground = true,
					Name = "DualSenseRain HID"
				};
				worker.Start();
			}
		}

		public void SetLights(bool lights, byte red, byte green, byte blue, byte leds)
		{
			lock (sync)
			{
				if (pendingLights == lights && pendingRed == red && pendingGreen == green && pendingBlue == blue && pendingLeds == leds)
				{
					return;
				}
				pendingLights = lights;
				pendingRed = red;
				pendingGreen = green;
				pendingBlue = blue;
				pendingLeds = leds;
				dirty = true;
			}
			wake.Set();
		}

		public void SetState(byte[] right, byte[] left, byte heavy, byte light, bool motors)
		{
			lock (sync)
			{
				Buffer.BlockCopy(right, 0, pendingRight, 0, 11);
				Buffer.BlockCopy(left, 0, pendingLeft, 0, 11);
				pendingHeavy = heavy;
				pendingLight = light;
				pendingMotors = motors;
				dirty = true;
			}
			wake.Set();
		}

		public void ResetNow()
		{
			if (!IsConnected)
			{
				return;
			}
			byte[] array = TriggerEffects.Off();
			SpeakerBoost = 0;
			rumbleWasOn = true;
			try
			{
				Send(array, array, 0, 0, motors: true, lights: true, 0, 0, 64, 4);
			}
			catch
			{
			}
		}

		private void WorkerLoop()
		{
			byte[] array = new byte[11];
			byte[] array2 = new byte[11];
			byte heavy = 0;
			byte light = 0;
			bool motors = false;
			bool lights = false;
			byte red = 0;
			byte green = 0;
			byte blue = 0;
			byte leds = 0;
			DateTime dateTime = DateTime.MinValue;
			while (running)
			{
				wake.WaitOne(250);
				if (!running)
				{
					break;
				}
				if (giDev != IntPtr.Zero && !GameInputPad.Alive(giDev))
				{
					DropGi();
				}
				if (!IsConnected)
				{
					if (DateTime.UtcNow < dateTime)
					{
						continue;
					}
					dateTime = DateTime.UtcNow.AddSeconds(3.0);
					bool num = TryOpen();
					bool flag = PickGi();
					if (!num && !flag)
					{
						continue;
					}
					lock (sync)
					{
						dirty = true;
					}
				}
				else if (giDev == IntPtr.Zero && Gi != null && !giOff && DateTime.UtcNow >= nextGiTry)
				{
					nextGiTry = DateTime.UtcNow.AddSeconds(2.0);
					if (PickGi())
					{
						lock (sync)
						{
							dirty = true;
						}
					}
				}
				bool flag2;
				lock (sync)
				{
					flag2 = dirty;
					if (flag2)
					{
						Buffer.BlockCopy(pendingRight, 0, array, 0, 11);
						Buffer.BlockCopy(pendingLeft, 0, array2, 0, 11);
						heavy = pendingHeavy;
						light = pendingLight;
						motors = pendingMotors;
						lights = pendingLights;
						red = pendingRed;
						green = pendingGreen;
						blue = pendingBlue;
						leds = pendingLeds;
						dirty = false;
					}
				}
				if (flag2 && !Send(array, array2, heavy, light, motors, lights, red, green, blue, leds))
				{
					Log("DualSense отключён или запись не удалась — переподключение.");
					CloseHandle();
				}
			}
		}

		private bool Send(byte[] right, byte[] left, byte heavy, byte light, bool motors, bool lights, byte red, byte green, byte blue, byte leds)
		{
			byte[] array = new byte[outputLength];
			int num;
			if (bluetooth)
			{
				array[0] = 49;
				array[1] = (byte)(btSeq << 4);
				btSeq = (byte)((btSeq + 1) & 0xF);
				array[2] = 16;
				num = 3;
			}
			else
			{
				array[0] = 2;
				num = 1;
			}
			bool num2 = (DateTime.UtcNow - lastTrigFull).TotalSeconds > 1.0;
			bool flag = num2 || !TriggerEffects.Same(right, sentRight);
			bool flag2 = num2 || !TriggerEffects.Same(left, sentLeft);
			if (num2)
			{
				lastTrigFull = DateTime.UtcNow;
			}
			if (flag)
			{
				Buffer.BlockCopy(right, 0, sentRight, 0, 11);
			}
			if (flag2)
			{
				Buffer.BlockCopy(left, 0, sentLeft, 0, 11);
			}
			bool flag3 = motors && (heavy != 0 || light != 0);
			bool flag4 = flag3 || rumbleWasOn;
			rumbleWasOn = flag3;
			if (!flag3)
			{
				heavy = (light = 0);
			}
			array[num] = (byte)((flag ? 4 : 0) | (flag2 ? 8 : 0) | (flag4 ? (vibV2 ? 2 : 3) : 0));
			if (flag4 && vibV2)
			{
				array[num + 38] |= 4;
			}
			array[num + 1] = (byte)(lights ? 20u : 0u);
			if (AudioSetup)
			{
				bool flag5 = Gyro != null && Gyro.Headset;
				array[num] |= 176;
				array[num + 1] |= 130;
				array[num + 4] = HeadphoneVolume;
				array[num + 5] = SpeakerVolume;
				array[num + 7] = (byte)(0x40 | ((!flag5) ? 48 : 0));
				array[num + 9] = 15;
				array[num + 37] = (byte)(SpeakerBoost & 7);
			}
			if (lights)
			{
				if (!lightSetupDone)
				{
					array[num + 38] |= 2;
					array[num + 41] = 2;
					lightSetupDone = true;
				}
				array[num + 42] = 0;
				array[num + 43] = (byte)(leds | 0x20);
				array[num + 44] = red;
				array[num + 45] = green;
				array[num + 46] = blue;
			}
			array[num + 2] = light;
			array[num + 3] = heavy;
			Buffer.BlockCopy(right, 0, array, num + 10, 11);
			Buffer.BlockCopy(left, 0, array, num + 21, 11);
			if (bluetooth)
			{
				uint num3 = Crc32.Compute(162, array, 0, 74);
				array[74] = (byte)num3;
				array[75] = (byte)(num3 >> 8);
				array[76] = (byte)(num3 >> 16);
				array[77] = (byte)(num3 >> 24);
			}
			if (giDev != IntPtr.Zero)
			{
				int num4 = Gi.Send(giDev, array, array.Length, bluetooth);
				if (num4 >= 0)
				{
					WritesOk++;
					giFails = 0;
					if (WritesOk == 1)
					{
						Log("Первая команда на геймпад отправлена (GameInput, " + (bluetooth ? "BT" : "USB") + ").");
					}
					return true;
				}
				giFails++;
				if (giFails <= 3)
				{
					Log($"GameInput: SendRawDeviceOutput вернул 0x{num4:X8}.");
				}
				if (giFails >= 5)
				{
					Log("GameInput не принимает команды — дальше пишу в геймпад напрямую (HID).");
					giOff = true;
					DropGi();
				}
				if (!HidOpen)
				{
					WritesFailed++;
					lastTrigFull = DateTime.MinValue;
					return true;
				}
			}
			if (!HidOpen)
			{
				return false;
			}
			OverlappedIo overlappedIo = ((Thread.CurrentThread == worker) ? ioWorker : ioOther);
			if (overlappedIo.Write(handle, array, 150))
			{
				WritesOk++;
				consecutiveTimeouts = 0;
				if (WritesOk == 1)
				{
					Log("Первая команда на геймпад отправлена (" + (bluetooth ? "BT" : "USB") + ").");
				}
				return true;
			}
			if (Native.HidD_SetOutputReport(handle, array, array.Length))
			{
				WritesOk++;
				consecutiveTimeouts = 0;
				if (!usedFallback)
				{
					usedFallback = true;
					Log("Команды идут через запасной канал HidD_SetOutputReport.");
				}
				return true;
			}
			WritesFailed++;
			lastTrigFull = DateTime.MinValue;
			if (WritesFailed <= 5)
			{
				Log($"Ошибка записи: WriteFile код {overlappedIo.LastError}, SetOutputReport код {Marshal.GetLastWin32Error()}.");
			}
			if (overlappedIo.LastError == 1460)
			{
				consecutiveTimeouts++;
				if (consecutiveTimeouts == 3)
				{
					Log("Геймпад не принимает команды (таймаут). Скорее всего, его держит другая программа (DSX, DS4Windows, reWASD) — закрой её. Мод попробует снова позже.");
				}
				Blocked = consecutiveTimeouts >= 3;
				return true;
			}
			return false;
		}

		private bool TryOpen()
		{
			try
			{
				Native.HidD_GetHidGuid(out var hidGuid);
				IntPtr intPtr = Native.SetupDiGetClassDevsW(ref hidGuid, IntPtr.Zero, IntPtr.Zero, 18u);
				if (intPtr == IntPtr.Zero || intPtr == new IntPtr(-1))
				{
					return false;
				}
				try
				{
					Native.SP_DEVICE_INTERFACE_DATA ifData = new Native.SP_DEVICE_INTERFACE_DATA
					{
						cbSize = Marshal.SizeOf(typeof(Native.SP_DEVICE_INTERFACE_DATA))
					};
					for (uint num = 0u; Native.SetupDiEnumDeviceInterfaces(intPtr, IntPtr.Zero, ref hidGuid, num, ref ifData); num++)
					{
						string path = GetPath(intPtr, ref ifData);
						if (path != null && TryOpenPath(path))
						{
							return true;
						}
					}
				}
				finally
				{
					Native.SetupDiDestroyDeviceInfoList(intPtr);
				}
			}
			catch (Exception ex)
			{
				Log("Ошибка поиска DualSense: " + ex.Message);
			}
			return false;
		}

		private static string GetPath(IntPtr devInfo, ref Native.SP_DEVICE_INTERFACE_DATA ifData)
		{
			Native.SetupDiGetDeviceInterfaceDetailW(devInfo, ref ifData, IntPtr.Zero, 0u, out var requiredSize, IntPtr.Zero);
			if (requiredSize == 0)
			{
				return null;
			}
			IntPtr intPtr = Marshal.AllocHGlobal((int)requiredSize);
			try
			{
				Marshal.WriteInt32(intPtr, (IntPtr.Size == 8) ? 8 : 6);
				if (!Native.SetupDiGetDeviceInterfaceDetailW(devInfo, ref ifData, intPtr, requiredSize, out var _, IntPtr.Zero))
				{
					return null;
				}
				return Marshal.PtrToStringUni(IntPtr.Add(intPtr, 4));
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}

		private bool TryOpenPath(string path)
		{
			string text = path.ToLowerInvariant();
			if (!text.Contains("vid_054c") && !text.Contains("054c"))
			{
				return false;
			}
			SafeFileHandle safeFileHandle = Native.CreateFileW(path, 3221225472u, 3u, IntPtr.Zero, 3u, 1073741824u, IntPtr.Zero);
			if (safeFileHandle.IsInvalid)
			{
				safeFileHandle = Native.CreateFileW(path, 1073741824u, 3u, IntPtr.Zero, 3u, 1073741824u, IntPtr.Zero);
				if (safeFileHandle.IsInvalid)
				{
					return false;
				}
			}
			if (safeFileHandle.IsInvalid)
			{
				return false;
			}
			Native.HIDD_ATTRIBUTES attributes = new Native.HIDD_ATTRIBUTES
			{
				Size = Marshal.SizeOf(typeof(Native.HIDD_ATTRIBUTES))
			};
			if (!Native.HidD_GetAttributes(safeFileHandle, ref attributes) || attributes.VendorID != 1356 || (attributes.ProductID != 3302 && attributes.ProductID != 3570))
			{
				safeFileHandle.Dispose();
				return false;
			}
			int num = 0;
			int inputLen = 0;
			if (Native.HidD_GetPreparsedData(safeFileHandle, out var preparsedData))
			{
				try
				{
					if (Native.HidP_GetCaps(preparsedData, out var caps) == 1114112)
					{
						num = caps.OutputReportByteLength;
						inputLen = caps.InputReportByteLength;
					}
				}
				finally
				{
					Native.HidD_FreePreparsedData(preparsedData);
				}
			}
			if (num == 48)
			{
				bluetooth = false;
			}
			else
			{
				if (num < 78)
				{
					safeFileHandle.Dispose();
					return false;
				}
				bluetooth = true;
			}
			outputLength = (bluetooth ? num : 48);
			handle = safeFileHandle;
			DevicePath = path;
			try
			{
				byte[] array = new byte[64];
				array[0] = 32;
				if (Native.HidD_GetFeature(safeFileHandle, array, array.Length))
				{
					int num2 = array[44] | (array[45] << 8);
					Log($"Прошивка DualSense: {num2 >> 8:X}.{num2 & 0xFF:X2}.");
				}
			}
			catch
			{
			}
			lightSetupDone = false;
			try
			{
				Gyro?.Start(path, bluetooth, inputLen);
			}
			catch (Exception ex)
			{
				Log("Гироскоп: " + ex.Message);
			}
			Mode = "HID напрямую (" + (bluetooth ? "BT" : "USB") + ")";
			Log("DualSense" + ((attributes.ProductID == 3570) ? " Edge" : "") + " найден (" + (bluetooth ? "Bluetooth" : "USB") + ").");
			return true;
		}

		private bool PickGi()
		{
			if (Gi == null || giOff || giDev != IntPtr.Zero)
			{
				return giDev != IntPtr.Zero;
			}
			IntPtr intPtr = Gi.Find(DevicePath);
			if (intPtr == IntPtr.Zero)
			{
				return false;
			}
			giDev = intPtr;
			giFails = 0;
			if (!HidOpen)
			{
				bluetooth = GameInputPad.IsBluetooth(intPtr);
				outputLength = (bluetooth ? 78 : 48);
				lightSetupDone = false;
				string text = GameInputPad.PnpPath(intPtr);
				if (text.Length > 0)
				{
					try
					{
						Gyro?.Start(text, bluetooth, bluetooth ? 78 : 64);
					}
					catch (Exception ex)
					{
						Log("Гироскоп: " + ex.Message);
					}
				}
			}
			HapticsEndpoint = (bluetooth ? "" : GameInputPad.HapticEndpoint(intPtr));
			Mode = "GameInput (" + (bluetooth ? "BT" : "USB") + ")";
			Log("Команды на геймпад идут через GameInput: «" + GameInputPad.Name(intPtr) + "»" + ((HapticsEndpoint.Length > 0) ? (", хаптика: " + HapticsEndpoint) : "") + ".");
			return true;
		}

		private void DropGi()
		{
			IntPtr intPtr = giDev;
			giDev = IntPtr.Zero;
			HapticsEndpoint = "";
			if (intPtr != IntPtr.Zero)
			{
				GameInputPad.ReleaseDev(intPtr);
			}
			if (!HidOpen)
			{
				try
				{
					Gyro?.Stop();
					return;
				}
				catch
				{
					return;
				}
			}
			Mode = "HID напрямую (" + (bluetooth ? "BT" : "USB") + ")";
		}

		private void CloseHandle()
		{
			try
			{
				Gyro?.Stop();
			}
			catch
			{
			}
			try
			{
				handle?.Dispose();
			}
			catch
			{
			}
			handle = null;
		}

		public void Dispose()
		{
			running = false;
			wake.Set();
			try
			{
				worker?.Join(500);
			}
			catch
			{
			}
			ResetNow();
			DropGi();
			try
			{
				Gi?.Dispose();
			}
			catch
			{
			}
			Gi = null;
			CloseHandle();
			ioWorker.Dispose();
			ioOther.Dispose();
		}
	}
	internal sealed class GameAudio
	{
		private sealed class Bank
		{
			private readonly string path;

			private readonly Dictionary<uint, (byte type, byte[] body)> objs = new Dictionary<uint, (byte, byte[])>();

			private readonly Dictionary<uint, (long off, int size)> didx = new Dictionary<uint, (long, int)>();

			private Dictionary<uint, List<uint>> children;

			public Bank(string path)
			{
				this.path = path;
				using FileStream fileStream = File.OpenRead(path);
				using BinaryReader binaryReader = new BinaryReader(fileStream);
				long num = -1L;
				List<(uint, uint, uint)> list = new List<(uint, uint, uint)>();
				while (fileStream.Position + 8 <= fileStream.Length)
				{
					string text = Encoding.ASCII.GetString(binaryReader.ReadBytes(4));
					uint num2 = binaryReader.ReadUInt32();
					long position = fileStream.Position;
					switch (text)
					{
					case "DIDX":
					{
						for (int i = 0; i < num2 / 12; i++)
						{
							list.Add((binaryReader.ReadUInt32(), binaryReader.ReadUInt32(), binaryReader.ReadUInt32()));
						}
						break;
					}
					case "DATA":
						num = position;
						break;
					case "HIRC":
					{
						uint num3 = binaryReader.ReadUInt32();
						for (uint num4 = 0u; num4 < num3; num4++)
						{
							byte item = binaryReader.ReadByte();
							uint count = binaryReader.ReadUInt32();
							byte[] array = binaryReader.ReadBytes((int)count);
							if (array.Length >= 4)
							{
								objs[BitConverter.ToUInt32(array, 0)] = (item, array);
							}
						}
						break;
					}
					}
					fileStream.Position = position + num2;
				}
				foreach (var (key, num5, item2) in list)
				{
					didx[key] = (num + num5, (int)item2);
				}
			}

			public byte[] Wem(uint id)
			{
				if (!didx.TryGetValue(id, out (long, int) value))
				{
					return null;
				}
				using FileStream fileStream = File.OpenRead(path);
				fileStream.Position = value.Item1;
				byte[] array = new byte[value.Item2];
				fileStream.Read(array, 0, array.Length);
				return array;
			}

			private static uint Fnv(string s)
			{
				uint num = 2166136261u;
				byte[] bytes = Encoding.ASCII.GetBytes(s.ToLowerInvariant());
				foreach (byte b in bytes)
				{
					num *= 16777619;
					num ^= b;
				}
				return num;
			}

			private uint Parent(uint id)
			{
				(byte type, byte[] body) tuple = objs[id];
				byte item = tuple.type;
				byte[] item2 = tuple.body;
				int num = ((item == 2) ? 18 : 4);
				for (int i = num; i < Math.Min(item2.Length - 4, num + 30); i++)
				{
					uint num2 = BitConverter.ToUInt32(item2, i);
					if (num2 != id && objs.TryGetValue(num2, out (byte, byte[]) value) && (value.Item1 == 5 || value.Item1 == 6 || value.Item1 == 7 || value.Item1 == 9))
					{
						return num2;
					}
				}
				return 0u;
			}

			private void BuildChildren()
			{
				children = new Dictionary<uint, List<uint>>();
				foreach (KeyValuePair<uint, (byte, byte[])> obj in objs)
				{
					if (obj.Value.Item1 != 2 && obj.Value.Item1 != 5 && obj.Value.Item1 != 6 && obj.Value.Item1 != 9)
					{
						continue;
					}
					uint num = Parent(obj.Key);
					if (num != 0)
					{
						if (!children.TryGetValue(num, out var value))
						{
							value = (children[num] = new List<uint>());
						}
						value.Add(obj.Key);
					}
				}
			}

			private void Sounds(uint id, List<uint> outSrc, int depth)
			{
				if (depth > 6 || !objs.TryGetValue(id, out (byte, byte[]) value))
				{
					return;
				}
				if (value.Item1 == 2)
				{
					if (value.Item2.Length >= 13)
					{
						outSrc.Add(BitConverter.ToUInt32(value.Item2, 9));
					}
					return;
				}
				if (children == null)
				{
					BuildChildren();
				}
				if (!children.TryGetValue(id, out var value2))
				{
					return;
				}
				foreach (uint item in value2)
				{
					Sounds(item, outSrc, depth + 1);
				}
			}

			public List<uint> Resolve(string ev)
			{
				List<uint> list = new List<uint>();
				if (!objs.TryGetValue(Fnv(ev), out (byte, byte[]) value) || value.Item1 != 4)
				{
					return list;
				}
				int num = value.Item2[4];
				for (int i = 0; i < num && 9 + 4 * i <= value.Item2.Length; i++)
				{
					uint key = BitConverter.ToUInt32(value.Item2, 5 + 4 * i);
					if (objs.TryGetValue(key, out (byte, byte[]) value2) && value2.Item2.Length >= 10 && BitConverter.ToUInt16(value2.Item2, 4) == 1027)
					{
						Sounds(BitConverter.ToUInt32(value2.Item2, 6), list, 0);
					}
				}
				return list;
			}
		}

		public static Action<string> Log = delegate
		{
		};

		private readonly string bankDir;

		private readonly string vgm;

		private readonly string cache;

		private Thread worker;

		public volatile bool Ready;

		public int SpeakerClips;

		public int StepClips;

		private readonly Dictionary<string, List<float[]>> speaker = new Dictionary<string, List<float[]>>(StringComparer.OrdinalIgnoreCase);

		private readonly Dictionary<string, List<float[]>> steps = new Dictionary<string, List<float[]>>();

		private readonly Dictionary<string, List<float[]>> lands = new Dictionary<string, List<float[]>>();

		private readonly Random rnd = new Random();

		private readonly Dictionary<string, float[]> loops = new Dictionary<string, float[]>(StringComparer.OrdinalIgnoreCase);

		private static readonly (string bank, string media, string key)[] LoopMedia = new(string, string, string)[3]
		{
			("char_Toolbot", "MULT_walk_loop", "ToolbotBody"),
			("char_chef", "chef_roller_move_loop", "ChefBody"),
			("char_treeBot", "treeBot_sprint_loop", "TreebotBody")
		};

		private readonly Dictionary<uint, List<float[]>> reloads = new Dictionary<uint, List<float[]>>();

		private float lastReloadAt;

		private uint lastReloadId;

		public static readonly string[] SpeakerEvents = new string[26]
		{
			"Play_UI_menuClick", "Play_UI_menuHover", "Play_UI_menuBack", "Play_UI_commandHUD_select", "Play_UI_artifactSelect", "Play_UI_artifactDeselect", "Play_UI_item_pickup", "Play_item_proc_bandolierPickup", "Play_Hex_Item_Pickup", "Play_CursedBook_Pickup",
			"Play_UI_chest_unlock", "Play_UI_barrel_open", "Play_UI_rustedLockbox_open", "Play_UI_lunarCache_open", "Play_UI_obj_casinoChest_open", "Play_UI_3D_printer_process", "Play_UI_3D_printer_itemIntoPrinter", "Play_UI_3D_printer_selectItem", "Play_UI_coin", "Play_ui_lunar_coin_drop",
			"Play_UI_insufficient_funds", "Play_UI_shrineActivate", "Play_UI_equipment_activate", "Play_drone_repair", "Play_GG_INTER_DroneVendor_Purchase", "Play_UI_HUD_unfold"
		};

		public string PluginsDir;

		public static bool RawSteps = false;

		public float[] Reload(string name, uint id)
		{
			if (!Ready)
			{
				return null;
			}
			if (name != null)
			{
				if (name.IndexOf("reload", StringComparison.OrdinalIgnoreCase) < 0)
				{
					return null;
				}
				id = FnvId(name);
			}
			lock (reloads)
			{
				if (!reloads.TryGetValue(id, out var value) || value.Count == 0)
				{
					return null;
				}
				float num = (float)Environment.TickCount / 1000f;
				if (id == lastReloadId && num - lastReloadAt < 0.05f)
				{
					return null;
				}
				lastReloadId = id;
				lastReloadAt = num;
				return value[rnd.Next(value.Count)];
			}
		}

		private static uint FnvId(string s)
		{
			uint num = 2166136261u;
			byte[] bytes = Encoding.ASCII.GetBytes(s.ToLowerInvariant());
			foreach (byte b in bytes)
			{
				num *= 16777619;
				num ^= b;
			}
			return num;
		}

		private void LoadReloads()
		{
			int num = 0;
			string[] files = Directory.GetFiles(bankDir, "*.txt");
			foreach (string path in files)
			{
				string path2 = Path.ChangeExtension(path, ".bnk");
				if (!File.Exists(path2))
				{
					continue;
				}
				List<string> list = new List<string>();
				string[] array = File.ReadAllLines(path);
				for (int j = 0; j < array.Length; j++)
				{
					string[] array2 = array[j].Split('\t');
					if (array2.Length > 2 && array2[2].StartsWith("Play_", StringComparison.OrdinalIgnoreCase) && array2[2].IndexOf("reload", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						list.Add(array2[2].Trim());
					}
				}
				if (list.Count == 0)
				{
					continue;
				}
				Bank bank;
				try
				{
					bank = new Bank(path2);
				}
				catch
				{
					continue;
				}
				foreach (string item in list)
				{
					List<float[]> list2 = new List<float[]>();
					foreach (uint item2 in bank.Resolve(item))
					{
						float[] array3 = Decode(bank, item2);
						if (array3 != null)
						{
							list2.Add(GameSounds.ForSpeaker(array3));
						}
					}
					if (list2.Count != 0)
					{
						lock (reloads)
						{
							reloads[FnvId(item)] = list2;
						}
						num++;
					}
				}
			}
			if (!string.IsNullOrEmpty(PluginsDir) && Directory.Exists(PluginsDir))
			{
				files = Directory.GetFiles(PluginsDir, "*.bnk", SearchOption.AllDirectories);
				foreach (string path3 in files)
				{
					try
					{
						string directoryName = Path.GetDirectoryName(path3);
						while (directoryName != null && Path.GetDirectoryName(directoryName) != null && !string.Equals(Path.GetFullPath(Path.GetDirectoryName(directoryName)).TrimEnd('\\', '/'), Path.GetFullPath(PluginsDir).TrimEnd('\\', '/'), StringComparison.OrdinalIgnoreCase))
						{
							directoryName = Path.GetDirectoryName(directoryName);
						}
						if (directoryName == null)
						{
							continue;
						}
						HashSet<string> hashSet = new HashSet<string>();
						string[] array = Directory.GetFiles(directoryName, "*.dll", SearchOption.AllDirectories);
						for (int j = 0; j < array.Length; j++)
						{
							byte[] array4 = File.ReadAllBytes(array[j]);
							for (int k = 0; k < 2; k++)
							{
								foreach (Match item3 in Regex.Matches(Encoding.Unicode.GetString(array4, k, array4.Length - k), "Play_[A-Za-z0-9_]*[Rr]eload[A-Za-z0-9_]*"))
								{
									hashSet.Add(item3.Value);
								}
							}
						}
						if (hashSet.Count == 0)
						{
							continue;
						}
						Bank bank2 = new Bank(path3);
						foreach (string item4 in hashSet)
						{
							List<float[]> list3 = new List<float[]>();
							foreach (uint item5 in bank2.Resolve(item4))
							{
								float[] array5 = Decode(bank2, item5);
								if (array5 != null)
								{
									list3.Add(GameSounds.ForSpeaker(array5));
								}
							}
							if (list3.Count != 0)
							{
								lock (reloads)
								{
									reloads[FnvId(item4)] = list3;
								}
								num++;
							}
						}
					}
					catch (Exception ex)
					{
						Log("Звуки мода " + Path.GetFileName(path3) + ": " + ex.Message);
					}
				}
			}
			Log($"Звуки перезарядки из игры и модов: {num} событий.");
		}

		public float[] Loop(string bodyName)
		{
			if (!Ready || bodyName == null)
			{
				return null;
			}
			lock (loops)
			{
				float[] value;
				return loops.TryGetValue(bodyName, out value) ? value : null;
			}
		}

		public GameAudio(string bankDir, string vgmDir, string cacheDir)
		{
			this.bankDir = bankDir;
			vgm = Path.Combine(vgmDir, "dsr_vgm.dll");
			cache = cacheDir;
		}

		public void Start()
		{
			if (worker == null)
			{
				worker = new Thread(Load)
				{
					IsBackground = true,
					Name = "DualSenseRain game audio",
					Priority = ThreadPriority.BelowNormal
				};
				worker.Start();
			}
		}

		public float[] Speaker(string ev)
		{
			if (!Ready)
			{
				return null;
			}
			lock (speaker)
			{
				List<float[]> value;
				return (speaker.TryGetValue(ev, out value) && value.Count > 0) ? value[rnd.Next(value.Count)] : null;
			}
		}

		public float[] Step(string surface, bool land = false)
		{
			if (!Ready)
			{
				return null;
			}
			string key = Material(surface);
			Dictionary<string, List<float[]>> dictionary = (land ? lands : steps);
			lock (dictionary)
			{
				if ((!dictionary.TryGetValue(key, out var value) || value.Count == 0) && (land || !dictionary.TryGetValue("rock", out value) || value.Count == 0))
				{
					return null;
				}
				return value[rnd.Next(value.Count)];
			}
		}

		public static string Material(string surface)
		{
			string text = (surface ?? "").ToLowerInvariant();
			if (text.Contains("water") || text.Contains("splash"))
			{
				return "water";
			}
			if (text.Contains("snow"))
			{
				return "snow";
			}
			if (text.Contains("metal") || text.Contains("machine") || text.Contains("mech") || text.Contains("grate"))
			{
				return "metal";
			}
			if (text.Contains("wood"))
			{
				return "wood";
			}
			if (text.Contains("solus"))
			{
				return "solus";
			}
			if (text.Contains("dirt") || text.Contains("grass") || text.Contains("sand") || text.Contains("mud") || text.Contains("moss") || text.Contains("ash") || text.Contains("sulfur"))
			{
				return "dirt";
			}
			return "rock";
		}

		private void Load()
		{
			try
			{
				if (!File.Exists(vgm) || LoadLibraryExW(vgm, IntPtr.Zero, 8u) == IntPtr.Zero)
				{
					Log("Звуки игры: не загрузился dsr_vgm.dll — остаются звуки мода.");
					return;
				}
				Directory.CreateDirectory(cache);
				Bank bank = new Bank(Path.Combine(bankDir, "Global.bnk"));
				string[] speakerEvents = SpeakerEvents;
				foreach (string text in speakerEvents)
				{
					foreach (uint item2 in bank.Resolve(text))
					{
						float[] array = Decode(bank, item2);
						if (array == null)
						{
							continue;
						}
						lock (speaker)
						{
							if (!speaker.TryGetValue(text, out var value))
							{
								value = (speaker[text] = new List<float[]>());
							}
							value.Add(GameSounds.ForSpeaker(array));
						}
						SpeakerClips++;
					}
				}
				string path = Path.Combine(bankDir, "Global.txt");
				if (File.Exists(path))
				{
					speakerEvents = File.ReadAllLines(path);
					foreach (string text2 in speakerEvents)
					{
						int num = text2.IndexOf("Footstep Material\\", StringComparison.Ordinal);
						if (num < 0)
						{
							continue;
						}
						string[] array2 = text2.Split('\t');
						if (array2.Length < 3 || !uint.TryParse(array2[1].Trim(), out var result))
						{
							continue;
						}
						string[] array3 = text2.Substring(num + "Footstep Material\\".Length).Split('\\');
						if (array3.Length < 2)
						{
							continue;
						}
						bool flag = array3[0] == "land_material";
						if (!flag && array3[0] != "step_material")
						{
							continue;
						}
						string text3 = array3[1];
						float[] array4 = Decode(bank, result);
						if (array4 == null)
						{
							continue;
						}
						float[] item = ToHaptic(array4, loop: false, text3);
						Dictionary<string, List<float[]>> dictionary = (flag ? lands : steps);
						lock (dictionary)
						{
							if (!dictionary.TryGetValue(text3, out var value2))
							{
								value2 = (dictionary[text3] = new List<float[]>());
							}
							value2.Add(item);
						}
						StepClips++;
					}
				}
				try
				{
					LoadReloads();
				}
				catch (Exception ex)
				{
					Log("Перезарядки: " + ex.Message);
				}
				(string, string, string)[] loopMedia = LoopMedia;
				for (int i = 0; i < loopMedia.Length; i++)
				{
					var (text4, value3, key) = loopMedia[i];
					try
					{
						string path2 = Path.Combine(bankDir, text4 + ".txt");
						string path3 = Path.Combine(bankDir, text4 + ".bnk");
						if (!File.Exists(path2) || !File.Exists(path3))
						{
							continue;
						}
						uint result2 = 0u;
						speakerEvents = File.ReadAllLines(path2);
						for (int j = 0; j < speakerEvents.Length; j++)
						{
							string[] array5 = speakerEvents[j].Split('\t');
							if (array5.Length > 3 && array5[3].EndsWith(".wem", StringComparison.OrdinalIgnoreCase) && array5[2].IndexOf(value3, StringComparison.OrdinalIgnoreCase) >= 0 && uint.TryParse(array5[1].Trim(), out result2))
							{
								break;
							}
							result2 = 0u;
						}
						if (result2 == 0)
						{
							continue;
						}
						float[] array6 = Decode(new Bank(path3), result2);
						if (array6 != null)
						{
							lock (loops)
							{
								loops[key] = ToHaptic(array6, loop: true);
							}
						}
					}
					catch (Exception ex2)
					{
						Log("Звук движения " + text4 + ": " + ex2.Message);
					}
				}
				Ready = true;
				List<string> list3 = new List<string>();
				lock (steps)
				{
					foreach (KeyValuePair<string, List<float[]>> step in steps)
					{
						list3.Add(step.Key + " " + step.Value.Count);
					}
				}
				Log(string.Format("Звуки игры загружены: в динамик {0}, шагов по поверхностям {1} ({2}), езда/бег: {3}.", SpeakerClips, StepClips, string.Join(", ", list3), string.Join(", ", loops.Keys)));
			}
			catch (Exception ex3)
			{
				Log("Звуки игры: " + ex3.Message);
			}
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern IntPtr LoadLibraryExW(string path, IntPtr file, uint flags);

		[DllImport("dsr_vgm", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
		private static extern int dsr_vgm_to_wav(byte[] data, int len, string outPath);

		private float[] Decode(Bank bank, uint id)
		{
			string text = Path.Combine(cache, id + ".wav");
			if (!File.Exists(text))
			{
				byte[] array = bank.Wem(id);
				if (array == null)
				{
					string path = Path.Combine(bankDir, id + ".wem");
					if (!File.Exists(path))
					{
						return null;
					}
					array = File.ReadAllBytes(path);
				}
				try
				{
					int num = dsr_vgm_to_wav(array, array.Length, text);
					if (num <= 0)
					{
						Log($"vgmstream: {id} не декодировался ({num})");
						return null;
					}
				}
				catch (Exception ex)
				{
					Log("vgmstream: " + ex.Message);
					return null;
				}
				if (!File.Exists(text))
				{
					return null;
				}
			}
			return GameSounds.LoadWav(text, 48000);
		}

		private static float[] ToHaptic(float[] s, bool loop = false, string mat = null)
		{
			if (RawSteps && !loop)
			{
				float num = 1E-06f;
				foreach (float num2 in s)
				{
					float num3 = ((num2 < 0f) ? (0f - num2) : num2);
					if (num3 > num)
					{
						num = num3;
					}
				}
				float[] array = new float[s.Length];
				float num4 = 1f / num;
				float num5 = 0f;
				float num6 = 0f;
				for (int j = 0; j < s.Length; j++)
				{
					float num7 = s[j] * num4;
					num5 = 0.995f * (num5 + num7 - num6);
					num6 = num7;
					array[j] = num5;
				}
				return array;
			}
			double num8 = 650.0;
			double num9 = 170.0;
			double num10 = 0.004;
			double num11 = 5.0;
			double num12 = 0.5;
			double num13 = 0.0;
			double num14 = 6.0;
			switch (mat)
			{
			case "metal":
				num8 = 1400.0;
				num9 = 280.0;
				num10 = 0.0006;
				num11 = 1.5;
				num12 = 1.4;
				num14 = 4.0;
				break;
			case "solus":
				num8 = 1600.0;
				num9 = 330.0;
				num10 = 0.001;
				num11 = 1.0;
				num12 = 1.6;
				num13 = 30.0;
				num14 = 4.0;
				break;
			case "wood":
				num8 = 500.0;
				num9 = 135.0;
				num10 = 0.003;
				num11 = 2.0;
				num12 = 1.1;
				num14 = 5.0;
				break;
			case "snow":
				num8 = 420.0;
				num9 = 0.0;
				num10 = 0.006;
				num11 = 9.0;
				num12 = 0.0;
				num14 = 7.0;
				break;
			case "dirt":
				num8 = 320.0;
				num9 = 85.0;
				num10 = 0.005;
				num11 = 3.0;
				num12 = 0.8;
				num14 = 3.0;
				break;
			case "water":
				num8 = 300.0;
				num9 = 65.0;
				num10 = 0.0012;
				num11 = 4.0;
				num12 = 0.9;
				num13 = 7.0;
				num14 = 3.0;
				break;
			case "rock":
				num8 = 650.0;
				num9 = 175.0;
				num10 = 0.004;
				num11 = 5.0;
				num12 = 0.6;
				num14 = 6.0;
				break;
			}
			if (loop)
			{
				num8 = 650.0;
				num9 = 170.0;
				num10 = 0.004;
				num11 = 5.0;
				num12 = 0.5;
				num13 = 0.0;
				num14 = 6.0;
			}
			double num15 = Math.PI * 2.0 * num8 / 48000.0;
			double num16 = Math.Cos(num15);
			double num17 = Math.Sin(num15) / 1.414;
			double num18 = 1.0 + num17;
			float num19 = (float)((1.0 - num16) / 2.0 / num18);
			float num20 = (float)((1.0 - num16) / num18);
			float num21 = num19;
			float num22 = (float)(-2.0 * num16 / num18);
			float num23 = (float)((1.0 - num17) / num18);
			float num24 = 0f;
			float num25 = 0f;
			float num26 = 0f;
			float num27 = 0f;
			float num28 = 0f;
			float num29 = 0f;
			float num30 = 0f;
			float num31 = 0f;
			uint num32 = 625341585u;
			double num33 = 0.0;
			float[] array2 = new float[s.Length];
			float num34 = 1E-06f;
			for (int k = 0; k < s.Length; k++)
			{
				float num35 = s[k];
				num28 = 0.996f * (num28 + num35 - num29);
				num29 = num35;
				num35 = num28;
				float num36 = num19 * num35 + num20 * num24 + num21 * num25 - num22 * num26 - num23 * num27;
				num25 = num24;
				num24 = num35;
				num27 = num26;
				num26 = num36;
				float num37 = num35 - num36;
				float num38 = ((num37 < 0f) ? (0f - num37) : num37);
				num30 += (num38 - num30) * ((num38 > num30) ? 0.3f : ((float)num10));
				num32 ^= num32 << 13;
				num32 ^= num32 >> 17;
				num32 ^= num32 << 5;
				num31 += ((float)(num32 & 0xFFFF) / 32768f - 1f - num31) * 0.04f;
				double num39 = num9 * ((num13 > 0.0) ? (1.0 + 0.25 * Math.Sin(Math.PI * 2.0 * num13 * (double)k / 48000.0)) : 1.0);
				num33 += Math.PI * 2.0 * num39 / 48000.0;
				float num40 = (array2[k] = num36 + num30 * (num31 * (float)num11 + (float)num12 * (float)Math.Sin(num33)) * 1.6f);
				float num41 = ((num40 < 0f) ? (0f - num40) : num40);
				if (num41 > num34)
				{
					num34 = num41;
				}
			}
			float num42 = 1f / num34;
			float num43 = (float)Math.Tanh(num14);
			for (int l = 0; l < array2.Length; l++)
			{
				array2[l] = (float)(Math.Tanh(num14 * (double)array2[l] * (double)num42) / (double)num43);
			}
			return array2;
		}
	}
	internal sealed class GameInputPad : IDisposable
	{
		private struct Span4
		{
			private int a;

			private int b;

			private int c;

			private int d;

			private int e;

			public int n;

			public int this[int i] => i switch
			{
				3 => d, 
				2 => c, 
				1 => b, 
				0 => a, 
				_ => e, 
			};

			public void Add(int v)
			{
				if (v <= 0)
				{
					return;
				}
				for (int i = 0; i < n; i++)
				{
					if (this[i] == v)
					{
						return;
					}
				}
				switch (n)
				{
				default:
					return;
				case 0:
					a = v;
					break;
				case 1:
					b = v;
					break;
				case 2:
					c = v;
					break;
				case 3:
					d = v;
					break;
				case 4:
					e = v;
					break;
				}
				n++;
			}
		}

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate int GiInit(ref Guid riid, out IntPtr ppv);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate uint UnkFn(IntPtr self);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate void EnableBg(IntPtr self, [MarshalAs(UnmanagedType.U1)] bool on);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate int RegDevCb(IntPtr self, IntPtr device, int kind, IntPtr ctx, IntPtr cb, out ulong token);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		[return: MarshalAs(UnmanagedType.U1)]
		private delegate bool Unreg(IntPtr self, ulong token);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate void DeviceCb(ulong token, IntPtr ctx, int ev, IntPtr device);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate ushort GetU16(IntPtr self);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate uint GetU32(IntPtr self);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		[return: MarshalAs(UnmanagedType.U1)]
		private delegate bool GetBool(IntPtr self);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate uint GetStr(IntPtr self, uint bytes, [Out] byte[] buf);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate uint GetInfos(IntPtr self, uint count, [Out] byte[] infos);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate int GetHaptic(IntPtr self, IntPtr info);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate int CreateRaw(IntPtr self, uint id, int kind, out IntPtr report);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate int SendRaw(IntPtr self, IntPtr report);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		private delegate UIntPtr GetSize(IntPtr self);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		[return: MarshalAs(UnmanagedType.U1)]
		private delegate bool SetRaw(IntPtr self, UIntPtr size, byte[] data);

		public static Action<string> Log = delegate
		{
		};

		private static readonly Guid IID_IGameInput = new Guid("F2DAAE4C-4D21-4250-8953-4F791E6279AB");

		private const int KindRaw = 1;

		private const int KindController = 14;

		private const int KindGamepad = 262144;

		private const int RawOutputReport = 1;

		private IntPtr dll;

		private IntPtr gi;

		private ulong token;

		private readonly object devLock = new object();

		private readonly List<IntPtr> pads = new List<IntPtr>();

		private int usbSizeOk;

		private readonly byte[] tmp = new byte[128];

		private static GameInputPad current;

		private static readonly DeviceCb cbDelegate = OnDevice;

		private static IntPtr cbPtr;

		private static readonly Dictionary<IntPtr, Delegate> fnCache = new Dictionary<IntPtr, Delegate>();

		public string DllPath { get; private set; }

		public bool Ready => gi != IntPtr.Zero;

		public int PadCount
		{
			get
			{
				lock (devLock)
				{
					return pads.Count;
				}
			}
		}

		public static GameInputPad Create(string modDir)
		{
			GameInputPad gameInputPad = new GameInputPad();
			try
			{
				gameInputPad.Init(modDir);
			}
			catch (Exception ex)
			{
				Log("GameInput: " + ex.Message);
			}
			if (!gameInputPad.Ready)
			{
				gameInputPad.Dispose();
				return null;
			}
			return gameInputPad;
		}

		private void Init(string modDir)
		{
			string text = PickDll(modDir);
			if (text == null)
			{
				Log("GameInput: GameInputRedist.dll не найден ни в системе, ни рядом с модом — работаю через HID.");
				return;
			}
			dll = LoadLibraryW(text);
			if (dll == IntPtr.Zero)
			{
				Log($"GameInput: не загрузился {text} (код {Marshal.GetLastWin32Error()}).");
				return;
			}
			IntPtr procAddress = GetProcAddress(dll, "GameInputInitialize");
			if (procAddress == IntPtr.Zero)
			{
				Log("GameInput: в " + text + " нет GameInputInitialize (старый GameInput) — работаю через HID.");
				return;
			}
			GiInit obj = (GiInit)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(GiInit));
			Guid riid = IID_IGameInput;
			int num = obj(ref riid, out var ppv);
			if (num < 0 || ppv == IntPtr.Zero)
			{
				Log($"GameInput: GameInputInitialize вернул 0x{num:X8}.");
				return;
			}
			gi = ppv;
			DllPath = text;
			try
			{
				V<EnableBg>(gi, 13)(gi, on: true);
			}
			catch
			{
			}
			current = this;
			if (cbPtr == IntPtr.Zero)
			{
				cbPtr = Marshal.GetFunctionPointerForDelegate(cbDelegate);
			}
			num = V<RegDevCb>(gi, 8)(gi, IntPtr.Zero, 262159, IntPtr.Zero, cbPtr, out token);
			if (num < 0)
			{
				Log($"GameInput: RegisterDeviceCallback 0x{num:X8}.");
			}
			Log("GameInput готов: " + text);
		}

		private static string PickDll(string modDir)
		{
			List<string> list = new List<string>();
			string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
			list.Add(Path.Combine(folderPath, "GameInputRedist.dll"));
			string text = RegRedistDir();
			if (!string.IsNullOrEmpty(text))
			{
				list.Add(Path.Combine(text, "GameInputRedist.dll"));
			}
			if (!string.IsNullOrEmpty(modDir))
			{
				list.Add(Path.Combine(modDir, "GameInputRedist.dll"));
			}
			string text2 = null;
			Version version = null;
			foreach (string item in list)
			{
				if (File.Exists(item))
				{
					Version version2 = new Version(0, 0);
					try
					{
						FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(item);
						version2 = new Version(versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart);
					}
					catch
					{
					}
					if (text2 == null || version2 > version)
					{
						text2 = item;
						version = version2;
					}
				}
			}
			return text2;
		}

		private static string RegRedistDir()
		{
			try
			{
				StringBuilder stringBuilder = new StringBuilder(520);
				int cb = stringBuilder.Capacity * 2;
				if (RegGetValueW(new IntPtr(-2147483646), "SOFTWARE\\Microsoft\\GameInput", "RedistDir", 65538, out var _, stringBuilder, ref cb) == 0)
				{
					return stringBuilder.ToString();
				}
			}
			catch
			{
			}
			return null;
		}

		private static void OnDevice(ulong tok, IntPtr ctx, int ev, IntPtr dev)
		{
			GameInputPad gameInputPad = current;
			if (gameInputPad == null || dev == IntPtr.Zero)
			{
				return;
			}
			try
			{
				switch (ev)
				{
				case 0:
				{
					ushort num = V<GetU16>(dev, 3)(dev);
					ushort num2 = V<GetU16>(dev, 4)(dev);
					if (num != 1356 || (num2 != 3302 && num2 != 3570))
					{
						break;
					}
					lock (gameInputPad.devLock)
					{
						if (gameInputPad.pads.Contains(dev))
						{
							break;
						}
						AddRef(dev);
						gameInputPad.pads.Add(dev);
					}
					Log("GameInput: подключён " + Name(dev) + " (" + (IsBluetooth(dev) ? "Bluetooth" : "USB") + ").");
					break;
				}
				case 1:
					lock (gameInputPad.devLock)
					{
						if (!gameInputPad.pads.Remove(dev))
						{
							break;
						}
					}
					Release(dev);
					Log("GameInput: DualSense отключён.");
					break;
				}
			}
			catch
			{
			}
		}

		public IntPtr Find(string hidPath)
		{
			lock (devLock)
			{
				IntPtr intPtr = IntPtr.Zero;
				foreach (IntPtr pad in pads)
				{
					if (Alive(pad))
					{
						if (intPtr == IntPtr.Zero)
						{
							intPtr = pad;
						}
						if (!string.IsNullOrEmpty(hidPath) && SamePath(PnpPath(pad), hidPath))
						{
							AddRef(pad);
							return pad;
						}
					}
				}
				if (intPtr != IntPtr.Zero)
				{
					AddRef(intPtr);
				}
				return intPtr;
			}
		}

		private static bool SamePath(string a, string b)
		{
			if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
			{
				return false;
			}
			a = a.ToLowerInvariant();
			b = b.ToLowerInvariant();
			if (a == b)
			{
				return true;
			}
			return a.TrimStart('\\', '?').Replace('#', '\\') == b.TrimStart('\\', '?').Replace('#', '\\');
		}

		public static bool Alive(IntPtr dev)
		{
			try
			{
				return V<GetBool>(dev, 43)(dev);
			}
			catch
			{
				return false;
			}
		}

		public static string Name(IntPtr dev)
		{
			return Str(dev, 18);
		}

		public static string PnpPath(IntPtr dev)
		{
			return Str(dev, 19);
		}

		private static string Str(IntPtr dev, int slot)
		{
			byte[] array = new byte[1024];
			try
			{
				uint val = V<GetStr>(dev, slot)(dev, (uint)(array.Length - 1), array);
				int num = Array.IndexOf(array, (byte)0);
				if (num < 0)
				{
					num = (int)Math.Min(val, (uint)array.Length);
				}
				return Encoding.UTF8.GetString(array, 0, num);
			}
			catch
			{
				return "";
			}
		}

		public static bool IsBluetooth(IntPtr dev)
		{
			try
			{
				uint num = V<GetU32>(dev, 38)(dev);
				switch (num)
				{
				default:
					num = 32u;
					break;
				case 1u:
				case 2u:
				case 3u:
				case 4u:
				case 5u:
				case 6u:
				case 7u:
				case 8u:
				case 9u:
				case 10u:
				case 11u:
				case 12u:
				case 13u:
				case 14u:
				case 15u:
				case 16u:
				case 17u:
				case 18u:
				case 19u:
				case 20u:
				case 21u:
				case 22u:
				case 23u:
				case 24u:
				case 25u:
				case 26u:
				case 27u:
				case 28u:
				case 29u:
				case 30u:
				case 31u:
				case 32u:
					break;
				case 0u:
					goto end_IL_0000;
				}
				byte[] array = new byte[384];
				num = V<GetInfos>(dev, 39)(dev, num, array);
				bool flag = false;
				for (int i = 0; i < num; i++)
				{
					switch (BitConverter.ToUInt32(array, i * 12 + 4))
					{
					case 49u:
						return true;
					case 2u:
						flag = true;
						break;
					}
				}
				if (flag)
				{
					return false;
				}
				end_IL_0000:;
			}
			catch
			{
			}
			string text = PnpPath(dev).ToLowerInvariant();
			if (!text.Contains("00001124-0000-1000-8000-00805f9b34fb") && !text.Contains("bthenum"))
			{
				return text.Contains("bthledevice");
			}
			return true;
		}

		public static string HapticEndpoint(IntPtr dev)
		{
			IntPtr intPtr = Marshal.AllocHGlobal(1024);
			try
			{
				for (int i = 0; i < 1024; i += 8)
				{
					Marshal.WriteInt64(intPtr, i, 0L);
				}
				if (V<GetHaptic>(dev, 42)(dev, intPtr) < 0)
				{
					return "";
				}
				return Marshal.PtrToStringUni(intPtr) ?? "";
			}
			catch
			{
				return "";
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}

		public int Send(IntPtr dev, byte[] report, int len, bool bt)
		{
			if (dev == IntPtr.Zero)
			{
				return -2147467261;
			}
			int num = V<CreateRaw>(dev, 54)(dev, report[0], 1, out var report2);
			if (num < 0 || report2 == IntPtr.Zero)
			{
				if (num >= 0)
				{
					return -2147467259;
				}
				return num;
			}
			try
			{
				int num2 = (int)(ulong)V<GetSize>(report2, 5)(report2);
				Span4 span = default(Span4);
				if (bt)
				{
					span.Add(len);
					if (num2 >= len)
					{
						span.Add(num2);
					}
				}
				else
				{
					span.Add(usbSizeOk);
					span.Add(64);
					if (num2 >= 48)
					{
						span.Add(num2);
					}
					span.Add(63);
					span.Add(48);
				}
				num = -2147024809;
				for (int i = 0; i < span.n; i++)
				{
					int num3 = span[i];
					if (num3 < len || num3 > tmp.Length)
					{
						continue;
					}
					Array.Clear(tmp, 0, num3);
					Buffer.BlockCopy(report, 0, tmp, 0, len);
					if (!V<SetRaw>(report2, 7)(report2, (UIntPtr)(ulong)num3, tmp))
					{
						continue;
					}
					num = V<SendRaw>(dev, 57)(dev, report2);
					if (num >= 0)
					{
						if (!bt)
						{
							usbSizeOk = num3;
						}
						break;
					}
				}
				return num;
			}
			finally
			{
				Release(report2);
			}
		}

		public void Dispose()
		{
			if (current == this)
			{
				current = null;
			}
			if (!(gi != IntPtr.Zero))
			{
				return;
			}
			try
			{
				if (token != 0L)
				{
					V<Unreg>(gi, 9)(gi, token);
				}
			}
			catch
			{
			}
			lock (devLock)
			{
				foreach (IntPtr pad in pads)
				{
					Release(pad);
				}
				pads.Clear();
			}
			Release(gi);
			gi = IntPtr.Zero;
		}

		private static T V<T>(IntPtr obj, int slot) where T : class
		{
			IntPtr intPtr = Marshal.ReadIntPtr(Marshal.ReadIntPtr(obj), slot * IntPtr.Size);
			lock (fnCache)
			{
				if (fnCache.TryGetValue(intPtr, out var value) && value is T result)
				{
					return result;
				}
				Delegate delegateForFunctionPointer = Marshal.GetDelegateForFunctionPointer(intPtr, typeof(T));
				fnCache[intPtr] = delegateForFunctionPointer;
				return (T)(object)delegateForFunctionPointer;
			}
		}

		private static void AddRef(IntPtr o)
		{
			if (o != IntPtr.Zero)
			{
				V<UnkFn>(o, 1)(o);
			}
		}

		private static void Release(IntPtr o)
		{
			if (o != IntPtr.Zero)
			{
				V<UnkFn>(o, 2)(o);
			}
		}

		public static void ReleaseDev(IntPtr d)
		{
			try
			{
				Release(d);
			}
			catch
			{
			}
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern IntPtr LoadLibraryW(string path);

		[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
		private static extern IntPtr GetProcAddress(IntPtr mod, string name);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
		private static extern int RegGetValueW(IntPtr hkey, string subKey, string value, int flags, out int type, StringBuilder data, ref int cb);
	}
	internal sealed class GameSounds
	{
		public static Action<string> Log = delegate
		{
		};

		private readonly Dictionary<string, List<float[]>> clips = new Dictionary<string, List<float[]>>(StringComparer.OrdinalIgnoreCase);

		private readonly Random rnd = new Random();

		public int Count => clips.Count;

		public void Add(string ev, string wavPath)
		{
			float[] array = LoadWav(wavPath, 48000);
			if (array != null)
			{
				if (!clips.TryGetValue(ev, out var value))
				{
					value = (clips[ev] = new List<float[]>());
				}
				value.Add(array);
			}
		}

		public float[] Pick(string ev)
		{
			if (!clips.TryGetValue(ev, out var value) || value.Count == 0)
			{
				return null;
			}
			return value[rnd.Next(value.Count)];
		}

		public bool Has(string ev)
		{
			return clips.ContainsKey(ev);
		}

		public static float[] ForSpeaker(float[] s)
		{
			if (s == null)
			{
				return null;
			}
			double num = Math.Cos(0.02356194490192345);
			double num2 = Math.Sin(0.02356194490192345) / 1.414;
			double num3 = 1.0 + num2;
			float num4 = (float)((1.0 + num) / 2.0 / num3);
			float num5 = (float)((0.0 - (1.0 + num)) / num3);
			float num6 = num4;
			float num7 = (float)(-2.0 * num / num3);
			float num8 = (float)((1.0 - num2) / num3);
			float num9 = 0f;
			float num10 = 0f;
			float num11 = 0f;
			float num12 = 0f;
			float num13 = 1E-06f;
			float[] array = new float[s.Length];
			for (int i = 0; i < s.Length; i++)
			{
				float num14 = s[i];
				float num15 = num4 * num14 + num5 * num9 + num6 * num10 - num7 * num11 - num8 * num12;
				num10 = num9;
				num9 = num14;
				num12 = num11;
				num11 = num15;
				array[i] = num15;
				float num16 = ((num15 < 0f) ? (0f - num15) : num15);
				if (num16 > num13)
				{
					num13 = num16;
				}
			}
			float num17 = 0.7f / num13;
			int num18 = Math.Min(96, array.Length / 4);
			for (int j = 0; j < array.Length; j++)
			{
				float num19 = 1f;
				if (j < num18)
				{
					num19 = (float)j / (float)num18;
				}
				else if (j > array.Length - num18)
				{
					num19 = (float)(array.Length - j) / (float)num18;
				}
				array[j] *= num17 * num19;
			}
			return array;
		}

		public static float[] LoadWav(string path, int outRate)
		{
			try
			{
				byte[] array = File.ReadAllBytes(path);
				int i = 12;
				int num = 0;
				int num2 = 0;
				int num3 = 0;
				int num4 = 0;
				int num5 = -1;
				int num6 = 0;
				int num7;
				for (; i + 8 <= array.Length; i += 8 + num7 + (num7 & 1))
				{
					string text = Encoding.ASCII.GetString(array, i, 4);
					num7 = BitConverter.ToInt32(array, i + 4);
					if (text == "fmt ")
					{
						num4 = BitConverter.ToUInt16(array, i + 8);
						num = BitConverter.ToUInt16(array, i + 10);
						num2 = BitConverter.ToInt32(array, i + 12);
						num3 = BitConverter.ToUInt16(array, i + 22);
					}
					else if (text == "data")
					{
						num5 = i + 8;
						num6 = Math.Min(num7, array.Length - num5);
						break;
					}
				}
				if (num5 < 0 || num <= 0 || num2 <= 0)
				{
					return null;
				}
				int num8 = num3 / 8;
				int num9 = num6 / (num8 * num);
				float[] array2 = new float[num9];
				bool flag = num4 switch
				{
					65534 => num3 == 32, 
					3 => true, 
					_ => false, 
				};
				for (int j = 0; j < num9; j++)
				{
					float num10 = 0f;
					for (int k = 0; k < num; k++)
					{
						int startIndex = num5 + (j * num + k) * num8;
						num10 += ((num3 == 16) ? ((float)BitConverter.ToInt16(array, startIndex) / 32768f) : (flag ? BitConverter.ToSingle(array, startIndex) : 0f));
					}
					array2[j] = num10 / (float)num;
				}
				if (num2 == outRate)
				{
					return array2;
				}
				int num11 = (int)((long)num9 * (long)outRate / num2);
				float[] array3 = new float[num11];
				double num12 = (double)num2 / (double)outRate;
				for (int l = 0; l < num11; l++)
				{
					double num13 = (double)l * num12;
					int num14 = (int)num13;
					float num15 = (float)(num13 - (double)num14);
					float num16 = array2[Math.Max(num14 - 1, 0)];
					float num17 = array2[Math.Min(num14, num9 - 1)];
					float num18 = array2[Math.Min(num14 + 1, num9 - 1)];
					float num19 = array2[Math.Min(num14 + 2, num9 - 1)];
					array3[l] = num17 + 0.5f * num15 * (num18 - num16 + num15 * (2f * num16 - 5f * num17 + 4f * num18 - num19 + num15 * (3f * (num17 - num18) + num19 - num16)));
				}
				return array3;
			}
			catch (Exception ex)
			{
				Log("Звук " + Path.GetFileName(path) + ": " + ex.Message);
				return null;
			}
		}
	}
	internal sealed class GameSpeaker
	{
		private class RouteTry
		{
			public string Label;

			public Func<AkOutputSettings> Make;

			public bool Push;

			public bool DiagOnly;

			public bool Calibrate;
		}

		public static Action<string> Log = delegate
		{
		};

		public static GameSpeaker Instance;

		public bool SkillSounds = true;

		private GameObject listener;

		private GameObject uiEmitter;

		private GameObject bodyEmitter;

		private GameObject hitEmitter;

		private ulong listenerId;

		private ulong outputId;

		private readonly HashSet<uint> uiIds = new HashSet<uint>();

		private readonly Dictionary<uint, float> lastPlayed = new Dictionary<uint, float>();

		private static readonly string[] UiEvents = new string[83]
		{
			"Play_UI_menuClick", "Play_UI_menuHover", "Play_UI_menuBack", "Play_UI_item_pickup", "Play_UI_item_spawn_tier1", "Play_UI_item_spawn_tier2", "Play_UI_item_spawn_tier3", "Play_UI_item_land_tier1", "Play_UI_item_land_tier2", "Play_UI_item_land_tier3",
			"Play_UI_item_land_command", "Play_wTier2Drop", "Play_UI_chest_unlock", "Play_UI_barrel_open", "Play_UI_rustedLockbox_open", "Play_UI_lunarCache_open", "Play_UI_obj_casinoChest_open", "Play_UI_monsterLogDrop", "Play_UI_artifactKey_spawn", "Play_UI_coin",
			"Play_ui_lunar_coin_drop", "Play_UI_insufficient_funds", "Play_UI_achievementUnlock", "Play_UI_achievementUnlock_enhanced", "Play_Achievement", "Play_UI_equipment_activate", "Play_UI_cooldownRefresh", "Play_UI_skill_unlock", "Play_UI_levelUp_player", "Play_UI_shrineActivate",
			"Play_UI_teleporter_event_complete", "Play_ui_teleporter_activate", "Play_UI_artifactSelect", "Play_UI_artifactDeselect", "Play_UI_3D_printer_selectItem", "Play_UI_3D_printer_itemIntoPrinter", "Play_UI_conversion_item", "Play_UI_conversion_void", "Play_UI_commandHUD_select", "Play_UI_commandHUD_appear",
			"Play_UI_podBlastDoorOpen", "Play_UI_podImpact", "Play_ui_player_death", "Play_item_proc_bandolierPickup", "Play_DLC4_System_Medal_Bronze", "Play_DLC4_System_Medal_Silver", "Play_DLC4_System_Medal_Gold", "Play_UI_chatMessage", "Play_UI_takeDamage", "Play_UI_xp_gain",
			"Play_UI_charTeleport", "Play_UI_teleport_off_map", "Play_UI_HUD_unfold", "Play_UI_podImpactPre", "Play_UI_podSteamBurst", "Play_UI_tripleChestShutter", "Play_UI_obj_casinoChest_swap", "Play_UI_obj_casinoChest_expire", "Play_UI_3D_printer_process", "Play_UI_monsterLogLand",
			"Play_UI_arenaMode_wave_start", "Play_UI_arenaMode_wave_startBoss", "Play_UI_arenaMode_wave_complete", "Play_UI_arenaMode_coundown321", "Play_UI_arenaMode_coundownMain", "Play_UI_arenaMode_portal_open", "Play_UI_arenaMode_voidCollapse_appear", "Play_UI_arenaMode_voidCollapse_select", "Play_env_teleporter_active_button", "Play_Hex_Item_Land",
			"Play_Hex_Item_Pickup", "Play_System_CursedItem_Active_Start", "Play_CursedBook_Pickup", "Play_CursedBook_Open", "Play_CursedBook_Close", "Play_DLC4_Inter_CurseShrine_Open", "Play_DLC4_Inter_CurseShrine_Accept", "Play_DLC4_Inter_CurseShrine_Reroll", "Play_Item_Cursed_SoulJar_Pickup", "Play_item_proc_extraLife",
			"Play_item_void_extraLife", "Play_item_use_healAndRevive_activate", "Play_drone_repair"
		};

		private static readonly string[] HitEvents = new string[2] { "Play_UI_hit", "Play_UI_crit" };

		private readonly HashSet<uint> hitIds = new HashSet<uint>();

		public bool HitSounds = true;

		public ToneSynth Fallback;

		public bool FallbackEnabled;

		private readonly Dictionary<uint, string> idNames = new Dictionary<uint, string>();

		private readonly Dictionary<string, float> lastFallback = new Dictionary<string, float>();

		private readonly HashSet<string> lastOk = new HashSet<string>();

		private static readonly Dictionary<string, float> lastLocal = new Dictionary<string, float>();

		private bool idsTried;

		public Action<float[], int, int, int> Sink;

		public float PcCopyVolume = 0.01f;

		public float CaptureGain = 1f;

		private bool calibrating;

		private float detectAt = -1f;

		private float calibStart;

		private float peak1;

		private float peak2;

		private readonly List<RouteTry> routes = new List<RouteTry>();

		private RouteTry route;

		private bool testing;

		private bool capturing;

		private bool pushing;

		private bool routesBuilt;

		private bool routesDone;

		private float testStart;

		private float testPeak;

		private float lastReport;

		private int testPosts;

		private uint testPlayId;

		private float testDuration = -1f;

		private int captureChannels = 1;

		private int captureRate = 48000;

		private long captureTotal;

		private readonly float[] captureBuf = new float[24576];

		private readonly float[] monoBuf = new float[24576];

		private int blockFrames;

		private long blockGcd;

		private int blockSeen;

		private bool failLayout;

		private readonly List<string> routeLog = new List<string>();

		private const string TestEvent = "Play_UI_menuClick";

		private static readonly string[] Allowed = new string[29]
		{
			"menuhover", "menuclick", "menuback", "commandhud_select", "artifactselect", "artifactdeselect", "printer_select", "item_pickup", "bandolier", "hex_item_pickup",
			"cursedbook_pickup", "souljar_pickup", "chest_unlock", "barrel_open", "lockbox", "lunarcache_open", "casinochest_open", "chest_open", "printer_process", "itemintoprinter",
			"coin", "insufficient", "shrineactivate", "curseshrine", "equipment_activate", "drone_repair", "dronevendor_purchase", "lunarcache_open", "hud_unfold"
		};

		public static Func<string, bool> RealSound;

		public static Func<string, uint, bool> LocalSound;

		public static bool Claimed;

		public static bool OnlyInController = true;

		private float lastUiVol = -1f;

		private float lastBodyVol = -1f;

		private float lastHitVol = -1f;

		private static bool FromMod;

		public static Action<string, GameObject> AnyEvent;

		public static float AbilityWindowUntil = -10f;

		public static float LastLocalBlastAt = -10f;

		public static Vector3 LastLocalBlastPos;

		private static readonly string[] WorldKeys = new string[23]
		{
			"shrine", "portal", "teleporter", "teleport_", "halcyonite", "goldsiphon", "coinslot", "lunar_reroller", "lunarpool", "lunarcache",
			"newtshop", "chest_open", "chest_unlock", "barrel", "scrapper", "printer", "cauldron", "voidcache", "drone_repair", "obj_",
			"gateway", "multishop", "equipmentbarrel"
		};

		private static readonly Dictionary<int, bool> projCache = new Dictionary<int, bool>();

		public bool Ready { get; private set; }

		public string DeviceName { get; private set; }

		public int Attempts { get; private set; }

		public bool Verified { get; private set; }

		private static bool Local(string name, uint id)
		{
			string key = ((name != null) ? name.ToLowerInvariant() : id.ToString());
			float unscaledTime = Time.unscaledTime;
			if (lastLocal.TryGetValue(key, out var value) && unscaledTime - value < 0.12f)
			{
				return value > 0f;
			}
			bool flag = LocalSound(name, id);
			lastLocal[key] = (flag ? unscaledTime : (0f - unscaledTime));
			if (flag && Plugin.Verbose)
			{
				Log("Динамик: свой звук «" + (name ?? id.ToString()) + "».");
			}
			return flag;
		}

		public GameSpeaker()
		{
			Instance = this;
		}

		private void EnsureIds()
		{
			if (uiIds.Count > 0 || idsTried)
			{
				return;
			}
			idsTried = true;
			try
			{
				InitIds();
			}
			catch
			{
				idsTried = false;
			}
		}

		private void InitIds()
		{
			if (uiIds.Count <= 0)
			{
				string[] uiEvents = UiEvents;
				foreach (string text in uiEvents)
				{
					uint iDFromString = AkSoundEngine.GetIDFromString(text);
					uiIds.Add(iDFromString);
					idNames[iDFromString] = text;
				}
				uiEvents = HitEvents;
				foreach (string text2 in uiEvents)
				{
					uint iDFromString2 = AkSoundEngine.GetIDFromString(text2);
					hitIds.Add(iDFromString2);
					idNames[iDFromString2] = text2;
				}
			}
		}

		private static long Gcd(long a, long b)
		{
			while (b != 0L)
			{
				long num = a % b;
				a = b;
				b = num;
			}
			return a;
		}

		private void NoteBlock(uint avail)
		{
			blockGcd = ((blockGcd == 0L) ? avail : Gcd(blockGcd, avail));
			if (++blockSeen >= 8)
			{
				int num = Math.Max(1, captureChannels);
				long num2 = blockGcd / num;
				if (blockGcd % num == 0L && num2 >= 64 && num2 <= 4096 && (num2 & (num2 - 1)) == 0L)
				{
					blockFrames = (int)num2;
					Log($"Звуки игры в динамике: блок захвата {blockFrames} кадров × {num} кан. (по каналам).");
				}
				else if (blockSeen > 120)
				{
					blockFrames = -1;
					Log($"Звуки игры в динамике: не удалось понять раскладку захвата (НОД {blockGcd}, каналов {num}) — включаю запасные звуки.");
					failLayout = true;
				}
			}
		}

		private int Deplanarize(int got)
		{
			int num = Math.Max(1, captureChannels);
			int num2 = blockFrames;
			int num3 = num2 * num;
			int result = 0;
			float num4 = CaptureGain / (float)num;
			for (int i = 0; i + num3 <= got; i += num3)
			{
				for (int j = 0; j < num2; j++)
				{
					float num5 = 0f;
					for (int k = 0; k < num; k++)
					{
						num5 += captureBuf[i + k * num2 + j];
					}
					monoBuf[result++] = num5 * num4;
				}
			}
			return result;
		}

		public bool Start(string preferName)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0072: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (Ready || routesDone)
			{
				return Ready;
			}
			if (testing)
			{
				return false;
			}
			try
			{
				if (!AkSoundEngine.IsInitialized())
				{
					return false;
				}
				InitIds();
				if (!Object.op_Implicit((Object)(object)listener))
				{
					listener = new GameObject("DualSenseRain_SpeakerListener");
					Object.DontDestroyOnLoad((Object)(object)listener);
					AkSoundEngine.RegisterGameObj(listener, ((Object)listener).name);
					listenerId = AkSoundEngine.GetAkGameObjectID(listener);
					AkSoundEngine.SetObjectPosition(listener, Vector3.zero, Vector3.forward, Vector3.up);
					uiEmitter = MakeEmitter("DualSenseRain_SpeakerUI");
					bodyEmitter = MakeEmitter("DualSenseRain_SpeakerBody");
					hitEmitter = MakeEmitter("DualSenseRain_SpeakerHits");
				}
				if (!routesBuilt)
				{
					BuildRoutes(preferName);
					routesBuilt = true;
				}
				return NextRoute();
			}
			catch (Exception ex)
			{
				routesDone = true;
				Log("Звуки игры в динамик недоступны: " + ex.Message);
				return false;
			}
		}

		private void BuildRoutes(string preferName)
		{
			if (Sink != null)
			{
				routes.Add(new RouteTry
				{
					Label = "основное устройство → поток HD (моно)",
					Make = () => new AkOutputSettings("System", 0u, AkChannelConfig.Standard(4u)),
					Push = true,
					Calibrate = true
				});
				routes.Add(new RouteTry
				{
					Label = "основное устройство → поток HD",
					Make = () => new AkOutputSettings("System", 0u, AkChannelConfig.Standard(3u)),
					Push = true,
					Calibrate = true
				});
			}
			List<(string, uint, bool)> list = new List<(string, uint, bool)>();
			uint windowsDeviceCount = AkSoundEngine.GetWindowsDeviceCount((AkAudioDeviceState)1);
			uint item = default(uint);
			for (int num = 0; num < windowsDeviceCount; num++)
			{
				string text = AkSoundEngine.GetWindowsDeviceName(num, ref item, (AkAudioDeviceState)1) ?? "";
				string text2 = text.ToLowerInvariant();
				if (text2.Contains("dualsense") || text2.Contains("wireless controller"))
				{
					bool item2 = !string.IsNullOrEmpty(preferName) && text.StartsWith(preferName, StringComparison.OrdinalIgnoreCase);
					list.Add((text, item, item2));
				}
			}
			foreach (var item3 in list.Where<(string, uint, bool)>(((string name, uint id, bool hdDevice) x) => !x.hdDevice).Concat(list.Where<(string, uint, bool)>(((string name, uint id, bool hdDevice) x) => x.hdDevice)))
			{
				(string name, uint id, bool hdDevice) dd = item3;
				routes.Add(new RouteTry
				{
					Label = "«" + dd.name + "»",
					Make = () => new AkOutputSettings("System", dd.id, AkChannelConfig.Standard(3u))
				});
			}
			Log("Звуки игры в динамик: проверяю пути — " + string.Join(", ", routes.Select((RouteTry r) => r.Label)) + ".");
		}

		private bool NextRoute()
		{
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			while (routes.Count > 0)
			{
				route = routes[0];
				routes.RemoveAt(0);
				AKRESULT val;
				try
				{
					val = AkSoundEngine.AddOutput(route.Make(), ref outputId, new ulong[1] { listenerId }, 1u);
				}
				catch (Exception ex)
				{
					routeLog.Add(route.Label + ": " + ex.GetType().Name);
					continue;
				}
				if ((int)val != 1)
				{
					routeLog.Add($"{route.Label}: {val}");
					continue;
				}
				try
				{
					AkChannelConfig speakerConfiguration = AkSoundEngine.GetSpeakerConfiguration(outputId);
					captureChannels = (int)((speakerConfiguration == null || speakerConfiguration.uNumChannels == 0) ? 1 : speakerConfiguration.uNumChannels);
					uint sampleRate = AkSoundEngine.GetSampleRate();
					captureRate = (int)((sampleRate != 0) ? sampleRate : 48000);
					AkSoundEngine.StartDeviceCapture(outputId);
					capturing = true;
				}
				catch (Exception ex2)
				{
					routeLog.Add(route.Label + ": захват " + ex2.GetType().Name);
					try
					{
						AkSoundEngine.RemoveOutput(outputId);
					}
					catch
					{
					}
					continue;
				}
				AkSoundEngine.SetOutputVolume(outputId, 1f);
				testing = true;
				testStart = Time.unscaledTime;
				testPeak = 0f;
				testPosts = 0;
				testPlayId = 0u;
				testDuration = -1f;
				captureTotal = 0L;
				detectAt = -1f;
				calibrating = false;
				CaptureGain = 1f;
				blockFrames = 0;
				blockGcd = 0L;
				blockSeen = 0;
				return false;
			}
			Finish(null);
			return false;
		}

		private void PostTest()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			try
			{
				AkSoundEngine.SetGameObjectOutputBusVolume(uiEmitter, listener, 0.5f);
				testPlayId = AkSoundEngine.PostEvent(AkSoundEngine.GetIDFromString("Play_UI_menuClick"), uiEmitter, 8u, (EventCallback)delegate(object cookie, AkCallbackType type, AkCallbackInfo info)
				{
					AkDurationCallbackInfo val = (AkDurationCallbackInfo)(object)((info is AkDurationCallbackInfo) ? info : null);
					if (val != null)
					{
						testDuration = val.fEstimatedDuration;
					}
				}, (object)null);
			}
			catch
			{
			}
			testPosts++;
		}

		public void Pump()
		{
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Unknown result type (might be due to invalid IL or missing references)
			if (!capturing)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			float num = 0f;
			try
			{
				uint num2 = AkSoundEngine.UpdateCaptureSampleCount(outputId);
				if (num2 != 0 && blockFrames == 0)
				{
					NoteBlock(num2);
				}
				int num3 = 0;
				while (num2 != 0 && num3++ < 16)
				{
					uint num4 = Math.Min(num2, (uint)captureBuf.Length);
					uint captureSamples = AkSoundEngine.GetCaptureSamples(outputId, captureBuf, num4);
					if (captureSamples == 0)
					{
						break;
					}
					captureTotal += captureSamples;
					for (int i = 0; i < captureSamples; i++)
					{
						float num5 = ((captureBuf[i] < 0f) ? (0f - captureBuf[i]) : captureBuf[i]);
						if (num5 > num)
						{
							num = num5;
						}
					}
					if (pushing && blockFrames > 0)
					{
						int num6 = Deplanarize((int)captureSamples);
						if (num6 > 0)
						{
							Sink?.Invoke(monoBuf, num6, 1, captureRate);
						}
					}
					num2 = ((num2 > captureSamples) ? (num2 - captureSamples) : 0u);
				}
			}
			catch (Exception ex)
			{
				routeLog.Add(route?.Label + ": ошибка захвата " + ex.GetType().Name);
				EndRoute();
				NextRoute();
				return;
			}
			if (failLayout)
			{
				failLayout = false;
				EndRoute();
				Finish("раскладка захвата не распознана");
				return;
			}
			if (!testing)
			{
				if (pushing && unscaledTime - lastReport > 60f)
				{
					lastReport = unscaledTime;
					Log($"Звуки игры в динамике: идёт ({captureTotal / Math.Max(1, captureChannels)} кадров).");
				}
				return;
			}
			if (unscaledTime - testStart > 0.3f)
			{
				testPeak = Mathf.Max(testPeak, num);
			}
			float num7 = unscaledTime - testStart;
			if (testPosts == 0 && num7 > 0.35f)
			{
				PostTest();
			}
			if (testPosts == 1 && num7 > 1.1f && testPeak < 0.003f)
			{
				PostTest();
			}
			if (calibrating)
			{
				float num8 = unscaledTime - calibStart;
				if (num8 > 0.05f)
				{
					peak2 = Mathf.Max(peak2, num);
				}
				if (testPosts == 1 && num8 > 0.1f)
				{
					PostTest();
				}
				if (!(num8 < 0.9f))
				{
					calibrating = false;
					bool flag = peak2 >= 0.5f * peak1;
					if (flag)
					{
						AkSoundEngine.SetOutputVolume(outputId, 0f);
						CaptureGain = 1f;
					}
					else
					{
						float num9 = Mathf.Clamp(PcCopyVolume, 0.003f, 1f);
						AkSoundEngine.SetOutputVolume(outputId, num9);
						CaptureGain = 1f / num9;
					}
					routeLog.Add(flag ? "копия на колонках ПК выключена" : $"копия на колонках ПК {Mathf.Clamp(PcCopyVolume, 0.003f, 1f):0.###}");
					routeLog.Add($"каналов {captureChannels}, {captureRate} Гц");
					Accept(unscaledTime);
				}
				return;
			}
			if (testPeak >= 0.003f && detectAt < 0f)
			{
				detectAt = unscaledTime;
			}
			if (testPeak >= 0.003f && unscaledTime - detectAt > 0.45f)
			{
				detectAt = -1f;
				routeLog.Add($"{route.Label}: звук есть (пик {testPeak:0.000})");
				if (route.DiagOnly)
				{
					EndRoute();
					Finish("Wwise рисует звук только на основные колонки");
				}
				else if (route.Calibrate)
				{
					calibrating = true;
					calibStart = unscaledTime;
					peak1 = testPeak;
					peak2 = 0f;
					testPosts = 1;
					AkSoundEngine.SetOutputVolume(outputId, 0.05f);
				}
				else
				{
					Accept(unscaledTime);
				}
			}
			else if (num7 > 2.2f && detectAt < 0f)
			{
				routeLog.Add(string.Format("{0}: тишина (событие {1}, длительность {2}, кадров {3})", route.Label, (testPlayId != 0) ? "запущено" : "не запустилось", (testDuration >= 0f) ? (testDuration.ToString("0") + " мс") : "нет", captureTotal / Math.Max(1, captureChannels)));
				EndRoute();
				NextRoute();
			}
		}

		private void Accept(float now)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			testing = false;
			pushing = route.Push;
			if (!pushing)
			{
				try
				{
					AkSoundEngine.StopDeviceCapture(outputId);
				}
				catch
				{
				}
				capturing = false;
			}
			AkSoundEngine.SetGameObjectOutputBusVolume(uiEmitter, listener, Mathf.Clamp01((lastUiVol < 0f) ? 0.8f : lastUiVol));
			Ready = true;
			Verified = true;
			DeviceName = route.Label;
			lastReport = now;
			Log("Звуки игры в динамике геймпада включены: " + route.Label + ". Проверено: " + string.Join("; ", routeLog) + ".");
		}

		private void EndRoute()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			testing = false;
			try
			{
				if (capturing)
				{
					AkSoundEngine.StopDeviceCapture(outputId);
				}
			}
			catch
			{
			}
			try
			{
				AkSoundEngine.RemoveOutput(outputId);
			}
			catch
			{
			}
			capturing = false;
			pushing = false;
		}

		private void Finish(string extra)
		{
			routesDone = true;
			Ready = false;
			Verified = false;
			Log("Звуки игры в динамик: рабочего пути нет — играют запасные звуки мода. Проверено: " + string.Join("; ", routeLog) + ((extra != null) ? (". " + extra) : "") + ".");
		}

		internal static bool TakeOver()
		{
			bool result = Claimed && OnlyInController;
			Claimed = false;
			return result;
		}

		internal static void AfterPost(uint playingId)
		{
			if (Claimed && OnlyInController && playingId != 0)
			{
				try
				{
					AkSoundEngine.StopPlayingID(playingId);
				}
				catch
				{
				}
			}
			Claimed = false;
		}

		public static bool IsAllowed(string name)
		{
			string text = name.ToLowerInvariant();
			string[] allowed = Allowed;
			foreach (string value in allowed)
			{
				if (text.Contains(value))
				{
					return true;
				}
			}
			return false;
		}

		private void PlayFallback(string name)
		{
			if (!FallbackEnabled || Fallback == null || name == null || !IsAllowed(name))
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			string text = name.ToLowerInvariant();
			if (lastFallback.TryGetValue(text, out var value) && unscaledTime - value < 0.12f)
			{
				if (lastOk.Contains(text))
				{
					Claimed = true;
				}
				if (Plugin.Verbose && !text.Contains("menuhover"))
				{
					Log(string.Format("Динамик: «{0}» пришёл повторно через {1:0} мс — в геймпаде не повторяю{2}.", name, (unscaledTime - value) * 1000f, lastOk.Contains(text) ? ", на колонках глушу" : ""));
				}
				return;
			}
			lastFallback[text] = unscaledTime;
			if (RealSound != null && RealSound(name))
			{
				Claimed = true;
				lastOk.Add(text);
				if (Plugin.Verbose && !text.Contains("menuhover"))
				{
					Log("Динамик: «" + name + "»" + (FromMod ? " (мод)" : "") + ".");
				}
			}
			else
			{
				lastOk.Remove(text);
			}
		}

		private GameObject MakeEmitter(string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			Object.DontDestroyOnLoad((Object)(object)val);
			AkSoundEngine.RegisterGameObj(val, name);
			AkSoundEngine.SetObjectPosition(val, Vector3.zero, Vector3.forward, Vector3.up);
			AkSoundEngine.SetListeners(val, new ulong[1] { listenerId }, 1u);
			return val;
		}

		public void SetVolume(float ui, float body, float hits)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			if (!Ready || (Mathf.Abs(ui - lastUiVol) < 0.005f && Mathf.Abs(body - lastBodyVol) < 0.005f && Mathf.Abs(hits - lastHitVol) < 0.005f))
			{
				return;
			}
			lastUiVol = ui;
			lastBodyVol = body;
			lastHitVol = hits;
			try
			{
				AkSoundEngine.SetOutputVolume(outputId, 1f);
				AkSoundEngine.SetGameObjectOutputBusVolume(uiEmitter, listener, Mathf.Clamp01(ui));
				AkSoundEngine.SetGameObjectOutputBusVolume(bodyEmitter, listener, Mathf.Clamp01(body));
				AkSoundEngine.SetGameObjectOutputBusVolume(hitEmitter, listener, Mathf.Clamp01(hits));
			}
			catch
			{
			}
		}

		public void Play(string name)
		{
			if (!Ready)
			{
				FromMod = true;
				try
				{
					PlayFallback(name);
					return;
				}
				finally
				{
					FromMod = false;
				}
			}
			try
			{
				Repost(AkSoundEngine.GetIDFromString(name), uiEmitter);
			}
			catch
			{
			}
		}

		public bool IsOurs(GameObject go)
		{
			if (Object.op_Implicit((Object)(object)go))
			{
				if (!((Object)(object)go == (Object)(object)uiEmitter) && !((Object)(object)go == (Object)(object)bodyEmitter) && !((Object)(object)go == (Object)(object)hitEmitter))
				{
					return (Object)(object)go == (Object)(object)listener;
				}
				return true;
			}
			return false;
		}

		public void OnNamed(string name, GameObject go)
		{
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(name) || IsOurs(go))
			{
				return;
			}
			EnsureIds();
			try
			{
				AnyEvent?.Invoke(name, go);
			}
			catch
			{
			}
			if (LocalSound != null && Object.op_Implicit((Object)(object)go) && IsLocalBody(go))
			{
				try
				{
					if (Local(name, 0u))
					{
						Claimed = true;
					}
				}
				catch
				{
				}
			}
			if (!Ready)
			{
				if (uiIds.Count > 0)
				{
					uint iDFromString = AkSoundEngine.GetIDFromString(name);
					if (uiIds.Contains(iDFromString) || hitIds.Contains(iDFromString))
					{
						PlayFallback(name);
					}
				}
				return;
			}
			uint iDFromString2 = AkSoundEngine.GetIDFromString(name);
			if (uiIds.Contains(iDFromString2))
			{
				Repost(iDFromString2, uiEmitter);
			}
			else if (hitIds.Contains(iDFromString2))
			{
				if (HitSounds)
				{
					Repost(iDFromString2, hitEmitter, always: false, 0.05f);
				}
			}
			else
			{
				if (!name.StartsWith("Play_") && !name.StartsWith("Stop_"))
				{
					return;
				}
				string text = name.ToLowerInvariant();
				if (Object.op_Implicit((Object)(object)go) && name.StartsWith("Play_") && !text.Contains("loop") && IsWorldEvent(text) && NearLocal(go, 25f))
				{
					Repost(iDFromString2, uiEmitter);
				}
				else
				{
					if (!SkillSounds || !Object.op_Implicit((Object)(object)go) || !name.StartsWith("Play_") || text.Contains("loop"))
					{
						return;
					}
					if (!IsLocalBody(go))
					{
						if ((text.Contains("explo") || text.Contains("detonat") || text.Contains("impact") || text.Contains("blast") || text.Contains("boom")) && Time.unscaledTime - LastLocalBlastAt < 0.4f)
						{
							Vector3 val = go.transform.position - LastLocalBlastPos;
							if (((Vector3)(ref val)).sqrMagnitude < 100f)
							{
								Repost(iDFromString2, bodyEmitter, always: false, 0.06f);
							}
						}
					}
					else if (!(Time.unscaledTime > AbilityWindowUntil) && !text.Contains("step") && !text.Contains("land") && !text.Contains("jump") && !text.Contains("_vo") && !text.Contains("sprint") && !text.Contains("hurt") && !text.Contains("death") && !text.Contains("spawn") && !text.Contains("foley") && !text.Contains("idle") && !text.Contains("item_proc") && !text.Contains("buff"))
					{
						Repost(iDFromString2, bodyEmitter);
					}
				}
			}
		}

		public static void OpenAbilityWindow(float seconds)
		{
			float num = Time.unscaledTime + seconds;
			if (num > AbilityWindowUntil)
			{
				AbilityWindowUntil = num;
			}
		}

		public void OnId(uint id, GameObject go)
		{
			if (IsOurs(go))
			{
				return;
			}
			EnsureIds();
			if (LocalSound != null && Object.op_Implicit((Object)(object)go) && IsLocalBody(go))
			{
				try
				{
					if (Local(null, id))
					{
						Claimed = true;
					}
				}
				catch
				{
				}
			}
			if (!Ready)
			{
				if (idNames.TryGetValue(id, out var value))
				{
					PlayFallback(value);
				}
			}
			else if (uiIds.Contains(id))
			{
				Repost(id, uiEmitter);
			}
			else if (hitIds.Contains(id) && HitSounds)
			{
				Repost(id, hitEmitter, always: false, 0.05f);
			}
		}

		private void Repost(uint id, GameObject emitter, bool always = false, float gap = 0.12f)
		{
			float unscaledTime = Time.unscaledTime;
			if (!always && lastPlayed.TryGetValue(id, out var value) && unscaledTime - value < gap)
			{
				return;
			}
			lastPlayed[id] = unscaledTime;
			if (lastPlayed.Count > 512)
			{
				lastPlayed.Clear();
			}
			try
			{
				AkSoundEngine.PostEvent(id, emitter);
			}
			catch
			{
			}
		}

		private static bool IsWorldEvent(string ln)
		{
			if (ln.Contains("idle") || ln.Contains("_vo") || ln.Contains("step") || ln.Contains("ambient") || ln.Contains("amb_"))
			{
				return false;
			}
			string[] worldKeys = WorldKeys;
			foreach (string value in worldKeys)
			{
				if (ln.Contains(value))
				{
					return true;
				}
			}
			return false;
		}

		private static bool NearLocal(GameObject go, float r)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser();
			CharacterBody val = ((firstLocalUser != null) ? firstLocalUser.cachedBody : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			Vector3 val2 = go.transform.position - val.corePosition;
			return ((Vector3)(ref val2)).sqrMagnitude <= r * r;
		}

		private static bool IsLocalProjectile(GameObject go)
		{
			LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser();
			CharacterBody val = ((firstLocalUser != null) ? firstLocalUser.cachedBody : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			int instanceID = ((Object)go).GetInstanceID();
			if (projCache.TryGetValue(instanceID, out var value))
			{
				return value;
			}
			if (projCache.Count > 256)
			{
				projCache.Clear();
			}
			ProjectileController componentInParent = go.GetComponentInParent<ProjectileController>();
			value = Object.op_Implicit((Object)(object)componentInParent) && (Object)(object)componentInParent.owner == (Object)(object)((Component)val).gameObject;
			projCache[instanceID] = value;
			return value;
		}

		internal static bool IsLocalBodyObj(GameObject go)
		{
			if (Object.op_Implicit((Object)(object)go))
			{
				return IsLocalBody(go);
			}
			return false;
		}

		private static bool IsLocalBody(GameObject go)
		{
			LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser();
			CharacterBody val = ((firstLocalUser != null) ? firstLocalUser.cachedBody : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			if ((Object)(object)go == (Object)(object)((Component)val).gameObject)
			{
				return true;
			}
			Transform val2 = go.transform;
			int num = 0;
			while (num < 6 && Object.op_Implicit((Object)(object)val2))
			{
				if ((Object)(object)((Component)val2).gameObject == (Object)(object)((Component)val).gameObject)
				{
					return true;
				}
				num++;
				val2 = val2.parent;
			}
			Transform val3 = (Object.op_Implicit((Object)(object)val.modelLocator) ? val.modelLocator.modelTransform : null);
			if (Object.op_Implicit((Object)(object)val3))
			{
				return go.transform.IsChildOf(val3);
			}
			return false;
		}

		public void Dispose()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!Ready)
			{
				return;
			}
			try
			{
				if (capturing)
				{
					AkSoundEngine.StopDeviceCapture(outputId);
				}
			}
			catch
			{
			}
			try
			{
				AkSoundEngine.RemoveOutput(outputId);
			}
			catch
			{
			}
			Ready = false;
			capturing = false;
			pushing = false;
		}
	}
	internal static class SpeakerPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(string),
			typeof(GameObject)
		})]
		private static bool NamedPrefix(string in_pszEventName, GameObject in_gameObjectID, ref uint __result)
		{
			GameSpeaker.Claimed = false;
			try
			{
				GameSpeaker.Instance?.OnNamed(in_pszEventName, in_gameObjectID);
			}
			catch
			{
			}
			if (!GameSpeaker.TakeOver())
			{
				return true;
			}
			__result = 0u;
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(string),
			typeof(GameObject),
			typeof(uint),
			typeof(EventCallback),
			typeof(object)
		})]
		private static bool NamedCbPrefix(object[] __args, ref uint __result, out bool __state)
		{
			GameSpeaker.Claimed = false;
			try
			{
				GameSpeaker.Instance?.OnNamed(__args[0] as string, (GameObject)/*isinst with value type is only supported in some contexts*/);
			}
			catch
			{
			}
			__state = GameSpeaker.TakeOver();
			if (!__state || __args[3] != null)
			{
				return true;
			}
			__state = false;
			__result = 0u;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(string),
			typeof(GameObject),
			typeof(uint),
			typeof(EventCallback),
			typeof(object)
		})]
		private static void NamedCbPostfix(uint __result, bool __state)
		{
			if (__state && __result != 0)
			{
				try
				{
					AkSoundEngine.StopPlayingID(__result);
				}
				catch
				{
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(string),
			typeof(ulong)
		})]
		private static bool NamedGlobalPrefix(string in_pszEventName, ref uint __result)
		{
			GameSpeaker.Claimed = false;
			try
			{
				GameSpeaker.Instance?.OnNamed(in_pszEventName, null);
			}
			catch
			{
			}
			if (!GameSpeaker.TakeOver())
			{
				return true;
			}
			__result = 0u;
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(uint),
			typeof(GameObject)
		})]
		private static bool IdPrefix(uint in_eventID, GameObject in_gameObjectID, ref uint __result)
		{
			GameSpeaker.Claimed = false;
			try
			{
				GameSpeaker.Instance?.OnId(in_eventID, in_gameObjectID);
			}
			catch
			{
			}
			if (!GameSpeaker.TakeOver())
			{
				return true;
			}
			__result = 0u;
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(uint),
			typeof(GameObject),
			typeof(uint),
			typeof(EventCallback),
			typeof(object)
		})]
		private static bool IdCbPrefix(object[] __args, ref uint __result, out bool __state)
		{
			GameSpeaker.Claimed = false;
			try
			{
				GameSpeaker.Instance?.OnId((uint)__args[0], (GameObject)/*isinst with value type is only supported in some contexts*/);
			}
			catch
			{
			}
			__state = GameSpeaker.TakeOver();
			if (!__state || __args[3] != null)
			{
				return true;
			}
			__state = false;
			__result = 0u;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(AkSoundEngine), "PostEvent", new Type[]
		{
			typeof(uint),
			typeof(GameObject),
			typeof(uint),
			typeof(EventCallback),
			typeof(object)
		})]
		private static void IdCbPostfix(uint __result, bool __state)
		{
			if (__state && __result != 0)
			{
				try
				{
					AkSoundEngine.StopPlayingID(__result);
				}
				catch
				{
				}
			}
		}
	}
	internal static class GlyphPatcher
	{
		private const string Asset = "tmpsprPS5GlyphsUnified";

		private static readonly (int id, string glyph)[] XInputToPs5 = new(int, string)[20]
		{
			(0, "LS"),
			(1, "LS"),
			(2, "RS"),
			(3, "RS"),
			(4, "L2"),
			(5, "R2"),
			(6, "Cross"),
			(7, "Circle"),
			(8, "Square"),
			(9, "Triangle"),
			(10, "L1"),
			(11, "R1"),
			(12, "Create"),
			(13, "Options"),
			(14, "L3"),
			(15, "R3"),
			(16, "Up"),
			(17, "Right"),
			(18, "Down"),
			(19, "Left")
		};

		public static float Scale = 0.85f;

		public static float Spacing = 0.12f;

		private static string[] XInputNames => new string[9]
		{
			DefaultControllerMaps.xbox360ControllerName,
			DefaultControllerMaps.xboxOneControllerName,
			"XInput Gamepad",
			"XInput Gamepad 0",
			"XInput Gamepad 1",
			"XInput Gamepad 2",
			"XInput Gamepad 3",
			"Gamepad",
			"Controller"
		};

		public static bool Applied { get; private set; }

		private static string Wrap(string sprite)
		{
			return string.Format(CultureInfo.InvariantCulture, "<nobr><space={1:0.##}em><size={0:0}%><voffset=0.06em>{2}</voffset></size><space={1:0.##}em></nobr>", Scale * 100f, Spacing, sprite);
		}

		public static void Apply(Action<string> log)
		{
			if (Applied)
			{
				return;
			}
			try
			{
				Type? typeFromHandle = typeof(Glyphs);
				RuntimeHelpers.RunClassConstructor(typeFromHandle.TypeHandle);
				FieldInfo field = typeFromHandle.GetField("glyphMap", BindingFlags.Static | BindingFlags.NonPublic);
				Type nestedType = typeFromHandle.GetNestedType("GlyphKey", BindingFlags.NonPublic);
				if (field == null || nestedType == null)
				{
					log("Не нашёл Glyphs.glyphMap — иконки не изменены (игра обновилась?).");
					return;
				}
				IDictionary dictionary = (IDictionary)field.GetValue(null);
				int num = 0;
				int num2 = 0;
				foreach (object item3 in new ArrayList(dictionary.Keys))
				{
					if (dictionary[item3] is string text && text.StartsWith("<sprite=\"tmpsprPS5GlyphsUnified\""))
					{
						dictionary[item3] = Wrap(text);
						num2++;
					}
				}
				string[] xInputNames = XInputNames;
				foreach (string text2 in xInputNames)
				{
					(int, string)[] xInputToPs = XInputToPs5;
					for (int j = 0; j < xInputToPs.Length; j++)
					{
						(int, string) tuple = xInputToPs[j];
						int item = tuple.Item1;
						string item2 = tuple.Item2;
						object key = Activator.CreateInstance(nestedType, text2, item);
						dictionary[key] = Wrap("<sprite=\"tmpsprPS5GlyphsUnified\" name=\"texPS5GlyphsUnified_" + item2 + "\">");
						num++;
					}
				}
				Applied = true;
				log($"Иконки PS5: XInput-геймпады {num} привязок, родные значки DualSense выровнены: {num2} (размер {Scale:0.##}, отступ {Spacing:0.##}em).");
				try
				{
					InputBindingDisplayController.onBindingsChanged?.Invoke();
				}
				catch
				{
				}
			}
			catch (Exception ex)
			{
				log("Ошибка подмены иконок: " + ex);
			}
		}
	}
	public enum GyroActivation
	{
		Auto,
		Off,
		Always,
		WhileL2,
		WhileTouchingTouchpad,
		ToggleTouchpadClick
	}
	public enum GyroAxis
	{
		Yaw,
		Roll,
		PlayerSpace
	}
	internal sealed class Gyro
	{
		private static class Native
		{
			public const uint GENERIC_READ = 2147483648u;

			public const uint FILE_SHARE_READ = 1u;

			public const uint FILE_SHARE_WRITE = 2u;

			public const uint OPEN_EXISTING = 3u;

			[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
			public static extern SafeFileHandle CreateFileW(string fileName, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);

			[DllImport("kernel32.dll", SetLastError = true)]
			public static extern bool ReadFile(SafeFileHandle file, byte[] buffer, uint toRead, out uint read, IntPtr overlapped);
		}

		public readonly ConfigEntry<GyroActivation> Activation;

		public readonly ConfigEntry<GyroAxis> Axis;

		public readonly ConfigEntry<float> Sensit