Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ResponsiveInput v1.0.2
ResponsiveInput.dll
Decompiled a day agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("ResponsiveInput")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: AssemblyInformationalVersion("1.0.2")] [assembly: AssemblyProduct("ResponsiveInput")] [assembly: AssemblyTitle("ResponsiveInput")] [assembly: AssemblyVersion("1.0.2.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ResponsiveInput { internal sealed class FrameHistory { private const int Capacity = 2400; private const float MillisecondsPerSecond = 1000f; private const int FramesPerWorstFrame = 100; private readonly float[] frameSeconds = new float[2400]; private readonly List<float> windowFrames = new List<float>(2400); private int nextSlot; private int recordedFrames; private int framesInWindow; internal float FramesPerSecond { get; private set; } internal float AverageMilliseconds { get; private set; } internal float WorstMilliseconds { get; private set; } internal void Clear() { nextSlot = 0; recordedFrames = 0; framesInWindow = 0; } internal void Record(float seconds) { frameSeconds[nextSlot] = seconds; nextSlot = (nextSlot + 1) % 2400; if (recordedFrames < 2400) { recordedFrames++; } } internal void Summarize(float windowSeconds) { windowFrames.Clear(); float num = 0f; for (int i = 0; i < recordedFrames; i++) { if (!(num < windowSeconds)) { break; } float num2 = frameSeconds[SlotFramesAgo(i)]; windowFrames.Add(num2); num += num2; } framesInWindow = windowFrames.Count; if (framesInWindow != 0 && !(num <= 0f)) { windowFrames.Sort(); FramesPerSecond = (float)framesInWindow / num; AverageMilliseconds = num / (float)framesInWindow * 1000f; WorstMilliseconds = AverageOfSlowest(Mathf.Max(1, framesInWindow / 100)) * 1000f; } } private float AverageOfSlowest(int count) { float num = 0f; for (int i = windowFrames.Count - count; i < windowFrames.Count; i++) { num += windowFrames[i]; } return num / (float)count; } private int SlotFramesAgo(int framesAgo) { return (nextSlot - 1 - framesAgo + 2400) % 2400; } } internal static class GameUiScale { private const float FallbackReferenceWidth = 1920f; private const float FallbackReferenceHeight = 1080f; private const float FallbackSliderScale = 1f; private const float SmallestUsableScale = 0.01f; private const float UnscaledSize = 1f; private static readonly FieldInfo SliderScale = AccessTools.Field(typeof(GuiScaler), "m_largeGuiScale"); private static readonly FieldInfo ReferenceWidth = AccessTools.Field(typeof(GuiScaler), "m_minWidth"); private static readonly FieldInfo ReferenceHeight = AccessTools.Field(typeof(GuiScaler), "m_minHeight"); internal static float Current() { float num = ReadPositive(ReferenceWidth, 1920f); float num2 = ReadPositive(ReferenceHeight, 1080f); float num3 = ReadPositive(SliderScale, 1f); float num4 = Mathf.Min((float)Screen.width / num, (float)Screen.height / num2) * num3; if (!(num4 > 0.01f)) { return 1f; } return num4; } private static float ReadPositive(FieldInfo field, float fallback) { if (field == null || !field.IsStatic) { return fallback; } object value = field.GetValue(null); if (value is float num && num > 0f) { return num; } if (value is int num2 && num2 > 0) { return num2; } return fallback; } } internal sealed class Monitor : MonoBehaviour { private const string Section = "Monitor"; private const float DefaultMeasureSeconds = 3f; private const float MinMeasureSeconds = 1f; private const float MaxMeasureSeconds = 10f; private const float DefaultOverlayScale = 1f; private const float MinOverlayScale = 0.5f; private const float MaxOverlayScale = 2f; private const float MaxOffset = 2000f; private const float RefreshSeconds = 0.5f; private const int FontSize = 14; private const int HorizontalPadding = 8; private const int VerticalPadding = 6; private const float ScreenMargin = 10f; private const float GapBelowHotbar = 6f; private const int CornerCount = 4; private const KeyCode DefaultOverlayKey = (KeyCode)112; private const KeyCode DefaultOverlayControl = (KeyCode)306; private const KeyCode DefaultOverlayShift = (KeyCode)304; private const KeyCode DefaultCompareKey = (KeyCode)292; internal static bool AllOff; private static ConfigEntry<bool> showOverlay; private static ConfigEntry<KeyboardShortcut> overlayKey; private static ConfigEntry<KeyboardShortcut> compareKey; private static ConfigEntry<float> measureSeconds; private static ConfigEntry<float> overlayScale; private static ConfigEntry<float> offsetX; private static ConfigEntry<float> offsetY; private static bool startFreshRequested; private readonly FrameHistory history = new FrameHistory(); private readonly StringBuilder text = new StringBuilder(); private string shownText = ""; private float nextRefresh; private float hotbarLeft = 10f; private float hotbarBottom = 10f; private readonly Vector3[] corners = (Vector3[])(object)new Vector3[4]; private GUIStyle style; internal static void BindSettings(ConfigFile config) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Expected O, but got Unknown //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Expected O, but got Unknown showOverlay = config.Bind<bool>("Monitor", "ShowOverlay", false, "Show frame time and what each setting is doing in the top left of the screen. Nothing is measured while it's hidden."); showOverlay.SettingChanged += delegate { startFreshRequested = showOverlay.Value; }; overlayKey = config.Bind<KeyboardShortcut>("Monitor", "OverlayKey", new KeyboardShortcut((KeyCode)112, (KeyCode[])(object)new KeyCode[2] { (KeyCode)306, (KeyCode)304 }), "Shows or hides the overlay."); compareKey = config.Bind<KeyboardShortcut>("Monitor", "CompareKey", new KeyboardShortcut((KeyCode)292, Array.Empty<KeyCode>()), "Puts everything back to the game's own behaviour, and back again, without changing your settings. Use it with the overlay to compare."); measureSeconds = config.Bind<float>("Monitor", "MeasureSeconds", 3f, new ConfigDescription("How many seconds of frames the overlay averages.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>())); overlayScale = config.Bind<float>("Monitor", "OverlayScale", 1f, new ConfigDescription("Extra size for the overlay on top of the game's own UI scale.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>())); offsetX = config.Bind<float>("Monitor", "OffsetX", 0f, new ConfigDescription("Moves the overlay right from its spot under the hotbar. Negative moves it left.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-2000f, 2000f), Array.Empty<object>())); offsetY = config.Bind<float>("Monitor", "OffsetY", 0f, new ConfigDescription("Moves the overlay down from its spot under the hotbar. Negative moves it up.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-2000f, 2000f), Array.Empty<object>())); } private void Update() { HandleKeys(); if (showOverlay.Value) { if (startFreshRequested) { startFreshRequested = false; history.Clear(); shownText = ""; nextRefresh = 0f; } history.Record(Time.unscaledDeltaTime); NvidiaReflex.Wait.CountFrame(); AmdAntiLag.Wait.CountFrame(); if (!(Time.unscaledTime < nextRefresh)) { nextRefresh = Time.unscaledTime + 0.5f; NvidiaReflex.Wait.Roll(); AmdAntiLag.Wait.Roll(); RebuildText(); FindHotbar(); } } } private void FindHotbar() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) hotbarLeft = 10f; hotbarBottom = 10f; HotkeyBar val = (((Object)(object)Hud.instance != (Object)null) ? ((Component)Hud.instance).GetComponentInChildren<HotkeyBar>() : null); if ((Object)(object)val == (Object)null || !((Behaviour)val).isActiveAndEnabled) { return; } Canvas componentInParent = ((Component)val).GetComponentInParent<Canvas>(); Camera val2 = (((Object)(object)componentInParent != (Object)null && (int)componentInParent.renderMode != 0) ? componentInParent.worldCamera : null); float num = float.MaxValue; float num2 = float.MaxValue; RectTransform[] componentsInChildren = ((Component)val).GetComponentsInChildren<RectTransform>(); foreach (RectTransform val3 in componentsInChildren) { if (!((Object)(object)((Component)val3).GetComponent<Graphic>() == (Object)null)) { val3.GetWorldCorners(corners); Vector3[] array = corners; foreach (Vector3 val4 in array) { Vector2 val5 = RectTransformUtility.WorldToScreenPoint(val2, val4); num = Mathf.Min(num, val5.x); num2 = Mathf.Min(num2, val5.y); } } } if (num != float.MaxValue) { hotbarLeft = num; hotbarBottom = (float)Screen.height - num2 + 6f; } } private static void HandleKeys() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_0035: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = overlayKey.Value; if (((KeyboardShortcut)(ref value)).IsDown()) { showOverlay.Value = !showOverlay.Value; } value = compareKey.Value; if (((KeyboardShortcut)(ref value)).IsDown()) { AllOff = !AllOff; ShowMessage(AllOff ? "Responsive Input: game's own behaviour" : "Responsive Input: back ON"); } } private static void ShowMessage(string message) { if ((Object)(object)MessageHud.instance != (Object)null) { MessageHud.instance.ShowMessage((MessageType)1, message, 0, (Sprite)null, false, true); } } private void RebuildText() { //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) float value = measureSeconds.Value; history.Summarize(value); text.Length = 0; text.Append("Responsive Input"); if (AllOff) { text.Append(" [GAME'S OWN]"); } text.Append('\n'); text.AppendFormat("{0:0} fps {1:0.0} ms avg {2:0.0} ms worst 1% ({3:0}s)\n", history.FramesPerSecond, history.AverageMilliseconds, history.WorstMilliseconds, value); text.Append("Frames ahead: ").Append(FrameQueue.Status).Append('\n'); text.Append("NVIDIA Reflex: ").Append(NvidiaReflex.Status).Append('\n'); text.Append("AMD Anti-Lag 2: ").Append(AmdAntiLag.Status).Append('\n'); text.Append("Driver FPS cap: ").Append((DriverCap.Fps > 0) ? (DriverCap.Fps + " fps") : "off").Append('\n'); text.Append("Physics: ").Append(PhysicsRate.Status).Append('\n'); text.Append("Camera: ").Append(CameraFollow.Status).Append('\n'); text.Append("Input buffer: ").Append(InputBuffer.Status).Append('\n'); text.Append(overlayKey.Value).Append(" hide ").Append(compareKey.Value) .Append(" game's own / back on"); shownText = text.ToString(); } private void OnGUI() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) if (showOverlay.Value) { if (style == null) { style = CreateStyle(); } Matrix4x4 matrix = GUI.matrix; float num = GameUiScale.Current() * overlayScale.Value; GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f)); Vector2 val = style.CalcSize(new GUIContent(shownText)); float num2 = hotbarLeft / num + offsetX.Value; float num3 = hotbarBottom / num + offsetY.Value; GUI.Box(new Rect(num2, num3, val.x, val.y), shownText, style); GUI.matrix = matrix; } } private static GUIStyle CreateStyle() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //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_001e: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown GUIStyle val = new GUIStyle(GUI.skin.box) { alignment = (TextAnchor)0, fontSize = 14, richText = false, padding = new RectOffset(8, 8, 6, 6) }; val.normal.textColor = Color.white; return val; } } [BepInPlugin("com.dreich.responsiveinput", "Responsive Input", "1.0.2")] public class ResponsiveInputPlugin : BaseUnityPlugin { public const string Guid = "com.dreich.responsiveinput"; public const string Name = "Responsive Input"; public const string Version = "1.0.2"; internal const string Section = "General"; internal static ManualLogSource Log; private void Awake() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown //IL_0089: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; FrameQueue.BindSettings(((BaseUnityPlugin)this).Config); PhysicsRate.BindSettings(((BaseUnityPlugin)this).Config); NvidiaReflex.BindSettings(((BaseUnityPlugin)this).Config); CameraFollow.BindSettings(((BaseUnityPlugin)this).Config); InputBuffer.BindSettings(((BaseUnityPlugin)this).Config); Monitor.BindSettings(((BaseUnityPlugin)this).Config); Harmony val = new Harmony("com.dreich.responsiveinput"); if (!InputBuffer.Patch(val)) { Log.LogWarning((object)"The game has changed; InputBuffer can't be adjusted and is left at the game's own timing."); } AmdAntiLag.BindSettings(((BaseUnityPlugin)this).Config); DriverCap.BindSettings(((BaseUnityPlugin)this).Config); if (!InputHook.Patch(val)) { Log.LogWarning((object)"The game has changed; NVIDIA Reflex and AMD Anti-Lag 2 can't hook into input and are turned off."); } ((Component)this).gameObject.AddComponent<Monitor>(); } private void Update() { PhysicsRate.Sync(); NvidiaReflex.Sync(); AmdAntiLag.Sync(); FrameQueue.Sync(); CameraFollow.Sync(); } } internal static class DriverCap { private const int NoCap = 0; private const int MaxCap = 360; private const int MicrosecondsPerSecond = 1000000; private static ConfigEntry<int> fps; internal static int Fps => fps.Value; internal static int IntervalMicroseconds { get { if (fps.Value <= 0) { return 0; } return 1000000 / fps.Value; } } internal static void BindSettings(ConfigFile config) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown fps = config.Bind<int>("General", "DriverFpsCap", 0, new ConfigDescription("Caps your FPS inside the NVIDIA or AMD driver while Reflex or Anti-Lag 2 is on. A driver cap adds less delay than the game's own FPS limit, so if you use one, set this instead and turn the game's limit off. 0 means no cap. It's also a way to check Reflex or Anti-Lag 2 is working: with a cap below your FPS, the monitor's wait time goes up.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 360), Array.Empty<object>())); } } internal static class InputHook { private const string InputPollMethod = "InternalUpdate"; internal static bool Patch(Harmony harmony) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(ZInput), "InternalUpdate", (Type[])null, (Type[])null); if (methodInfo == null) { NvidiaReflex.GameChanged(); AmdAntiLag.GameChanged(); return false; } harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(InputHook), "BeforeInput", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); return true; } private static void BeforeInput() { NvidiaReflex.BeforeInput(); AmdAntiLag.BeforeInput(); } } internal static class AmdAntiLag { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Create(IntPtr device, IntPtr antiLag); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate int UpdateState(IntPtr self, IntPtr data); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate uint Release(IntPtr self); private const int AmdVendorId = 4098; private const string DriverModule = "amdxx64.dll"; private const string CreateEntryPoint = "AmdDxExtCreate11"; private const ulong AntiLagRequest = 13778779262078472358uL; private const string ControlString = "delag_next_osd_supported_in_dxxp = 1"; private const int DataSize = 32; private const int DataVersion = 1; private const int SizeOffset = 0; private const int VersionOffset = 4; private const int ModeOffset = 8; private const int ControlOffset = 16; private const int ControlLengthOffset = 24; private const int MaxFpsOffset = 28; private const int ModeEnabled = 1; private const int ModeDisabled = 2; private const int NoFrameCap = 0; private const int ReleaseSlot = 1; private const int UpdateSlot = 3; private const int Succeeded = 0; private const int NothingChanged = 1; private const int NoFrame = -1; private static ConfigEntry<bool> enabled; private static string unavailable; private static IntPtr antiLag = IntPtr.Zero; private static UpdateState update; private static bool started; private static bool applied; private static int appliedCap; private static int lastFrame = -1; internal static readonly DriverWait Wait = new DriverWait(); internal static bool Working => applied; internal static string Status { get { if (unavailable != null) { return "off - " + unavailable; } if (!applied) { return "off"; } return "on - driver accepted it, waited " + Wait.Describe(); } } [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetModuleHandle(string name); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr module, string name); internal static void BindSettings(ConfigFile config) { enabled = config.Bind<bool>("General", "AmdAntiLag2", false, "Turns on AMD Radeon Anti-Lag 2, AMD's version of NVIDIA Reflex: it keeps the game from running ahead of your graphics card so what you press shows up as soon as possible. Needs a Radeon RX 5000 series or newer, AMD Software 24.6.1 or newer, and DirectX 11, the game's default. On anything else it turns itself off."); unavailable = UnsupportedReason(); if (unavailable != null && enabled.Value) { ResponsiveInputPlugin.Log.LogInfo((object)("AMD Anti-Lag 2 is off: " + unavailable + ".")); } } internal static void GameChanged() { if (unavailable == null) { unavailable = "the game has changed"; } } private static string UnsupportedReason() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 if ((int)Application.platform != 2) { return "Windows only"; } if ((int)SystemInfo.graphicsDeviceType != 2) { return "needs DirectX 11"; } if (SystemInfo.graphicsDeviceVendorID != 4098) { return "needs an AMD graphics card"; } return null; } internal static void Sync() { if (unavailable != null) { return; } bool flag = enabled.Value && !Monitor.AllOff; int num = (flag ? DriverCap.Fps : 0); if ((flag == applied && num == appliedCap) || (!flag && !applied)) { return; } try { if (started || Start()) { if (!Send(flag ? 1 : 2, num)) { TurnOff("not supported by this graphics card or driver"); return; } applied = flag; appliedCap = num; ResponsiveInputPlugin.Log.LogInfo((object)(applied ? "AMD Anti-Lag 2 is on: the driver accepted it." : "AMD Anti-Lag 2 is off.")); } } catch (Exception ex) { TurnOff("it failed: " + ex.Message); } } internal static void BeforeInput() { if (applied && update != null && Time.frameCount != lastFrame) { lastFrame = Time.frameCount; long timestamp = Stopwatch.GetTimestamp(); update(antiLag, IntPtr.Zero); Wait.Add(Stopwatch.GetTimestamp() - timestamp); } } private static bool Start() { started = true; IntPtr moduleHandle = GetModuleHandle("amdxx64.dll"); IntPtr intPtr = ((moduleHandle != IntPtr.Zero) ? GetProcAddress(moduleHandle, "AmdDxExtCreate11") : IntPtr.Zero); if (intPtr == IntPtr.Zero) { TurnOff("AMD driver not found"); return false; } IntPtr intPtr2 = Marshal.AllocHGlobal(IntPtr.Size); try { Marshal.WriteInt64(intPtr2, -4667964811631079258L); int num = Marshal.GetDelegateForFunctionPointer<Create>(intPtr)(IntPtr.Zero, intPtr2); IntPtr intPtr3 = Marshal.ReadIntPtr(intPtr2); if (num != 0 || intPtr3 == IntPtr.Zero || intPtr3 == new IntPtr(-4667964811631079258L)) { TurnOff("AMD driver too old or graphics card not supported"); return false; } antiLag = intPtr3; } finally { Marshal.FreeHGlobal(intPtr2); } update = Marshal.GetDelegateForFunctionPointer<UpdateState>(VirtualMethod(antiLag, 3)); return true; } private static bool Send(int mode, int cap) { IntPtr intPtr = Marshal.StringToHGlobalAnsi("delag_next_osd_supported_in_dxxp = 1"); IntPtr intPtr2 = Marshal.AllocHGlobal(32); try { for (int i = 0; i < 32; i++) { Marshal.WriteByte(intPtr2, i, 0); } Marshal.WriteInt32(intPtr2, 0, 32); Marshal.WriteInt32(intPtr2, 4, 1); Marshal.WriteInt32(intPtr2, 8, mode); Marshal.WriteIntPtr(intPtr2, 16, intPtr); Marshal.WriteInt32(intPtr2, 24, "delag_next_osd_supported_in_dxxp = 1".Length); Marshal.WriteInt32(intPtr2, 28, cap); int num = update(antiLag, intPtr2); return num == 0 || num == 1; } finally { Marshal.FreeHGlobal(intPtr2); Marshal.FreeHGlobal(intPtr); } } private static IntPtr VirtualMethod(IntPtr instance, int slot) { return Marshal.ReadIntPtr(Marshal.ReadIntPtr(instance), slot * IntPtr.Size); } private static void TurnOff(string reason) { unavailable = reason; applied = false; if (antiLag != IntPtr.Zero) { Marshal.GetDelegateForFunctionPointer<Release>(VirtualMethod(antiLag, 1))(antiLag); antiLag = IntPtr.Zero; update = null; } ResponsiveInputPlugin.Log.LogWarning((object)("AMD Anti-Lag 2 is off: " + reason + ".")); } } internal static class CameraFollow { private const int VanillaPercent = 100; private const int DefaultPercent = 50; private const int MinPercent = 0; private const float Percent = 100f; private static ConfigEntry<int> smoothing; private static GameCamera camera; private static float originalSmoothness; internal static string Status { get { if ((Object)(object)camera == (Object)null) { return "waiting for the camera"; } return Mathf.RoundToInt(camera.m_smoothness / Mathf.Max(originalSmoothness, float.Epsilon) * 100f) + "% of the game's own easing"; } } internal static void BindSettings(ConfigFile config) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown smoothing = config.Bind<int>("General", "CameraSmoothing", 50, new ConfigDescription("How much the camera eases after your character instead of following them exactly, compared to the game's own amount. 100 is the game's own feel, lower follows your movement more tightly, 0 follows it exactly. Mouse look is never smoothed either way.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); } internal static void Sync() { GameCamera instance = GameCamera.instance; if (!((Object)(object)instance == (Object)null)) { if ((Object)(object)instance != (Object)(object)camera) { camera = instance; originalSmoothness = instance.m_smoothness; } int num = (Monitor.AllOff ? 100 : smoothing.Value); float num2 = originalSmoothness * (float)num / 100f; if (instance.m_smoothness != num2) { instance.m_smoothness = num2; } } } } internal static class InputBuffer { private const float VanillaSeconds = 0.5f; private const float MinSeconds = 0.05f; private const float MaxSeconds = 1f; private static readonly string[] BufferedFields = new string[3] { "m_queuedAttackTimer", "m_queuedSecondAttackTimer", "m_queuedDodgeTimer" }; private static readonly string[] BufferingMethods = new string[2] { "PlayerAttackInput", "Dodge" }; private static ConfigEntry<float> seconds; internal static string Status => Window().ToString("0.00") + " s" + (Mathf.Approximately(Window(), 0.5f) ? " (game's own)" : (" (game's own " + 0.5f.ToString("0.0") + " s)")); internal static void BindSettings(ConfigFile config) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown seconds = config.Bind<float>("General", "InputBuffer", 0.5f, new ConfigDescription("How long, in seconds, an attack or dodge pressed during another action is remembered and done as soon as possible. The game's own value is 0.5. Lower it if attacks you pressed a while ago fire late and feel delayed. Raise it if presses during animations feel dropped.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>())); } internal static bool Patch(Harmony harmony) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown HarmonyMethod val = new HarmonyMethod(typeof(InputBuffer), "UseConfiguredWindow", (Type[])null); string[] bufferingMethods = BufferingMethods; foreach (string text in bufferingMethods) { MethodInfo methodInfo = AccessTools.Method(typeof(Player), text, (Type[])null, (Type[])null); if (methodInfo == null) { return false; } harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null); } return true; } private static float Window() { if (!Monitor.AllOff) { return seconds.Value; } return 0.5f; } private static IEnumerable<CodeInstruction> UseConfiguredWindow(IEnumerable<CodeInstruction> instructions) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Expected O, but got Unknown HashSet<FieldInfo> hashSet = new HashSet<FieldInfo>(); string[] bufferedFields = BufferedFields; foreach (string text in bufferedFields) { FieldInfo fieldInfo = AccessTools.Field(typeof(Player), text); if (fieldInfo != null) { hashSet.Add(fieldInfo); } } MethodInfo methodInfo = AccessTools.Method(typeof(InputBuffer), "Window", (Type[])null, (Type[])null); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int j = 0; j < list.Count - 1; j++) { if (!(list[j].opcode != OpCodes.Ldc_R4) && list[j].operand is float num && num == 0.5f && !(list[j + 1].opcode != OpCodes.Stfld) && list[j + 1].operand is FieldInfo item && hashSet.Contains(item)) { list[j] = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Call, (object)methodInfo), list[j]); } } return list; } } internal static class FrameQueue { private const int LowLatencyQueue = 1; private const int NotCaptured = -1; private static ConfigEntry<bool> enabled; private static int originalQueue = -1; private static bool applied; private static bool DriverHandlesIt { get { if (!NvidiaReflex.Working) { return AmdAntiLag.Working; } return true; } } internal static string Status { get { if (!applied) { if (!enabled.Value || !DriverHandlesIt) { return "off - " + QualitySettings.maxQueuedFrames; } return "off - " + QualitySettings.maxQueuedFrames + " (Reflex or Anti-Lag 2 is handling it)"; } return "on - " + QualitySettings.maxQueuedFrames + " (game's own " + originalQueue + ")"; } } internal static void BindSettings(ConfigFile config) { enabled = config.Bind<bool>("General", "LowLatencyFrames", false, "Lets the game get at most one frame ahead of your graphics card instead of two, so clicks and key presses show up on screen sooner. Works on every graphics card, but it can cost a lot of FPS: the game and your graphics card take turns instead of working at the same time. Turns itself off while NVIDIA Reflex or AMD Anti-Lag 2 is working, since they lower the delay without that cost."); } internal static void Sync() { bool flag = enabled.Value && !Monitor.AllOff && !DriverHandlesIt; if (flag == applied && (!flag || QualitySettings.maxQueuedFrames == 1)) { return; } if (flag) { if (originalQueue == -1) { originalQueue = QualitySettings.maxQueuedFrames; } QualitySettings.maxQueuedFrames = 1; } else if (originalQueue != -1) { QualitySettings.maxQueuedFrames = originalQueue; } applied = flag; } } internal static class PhysicsRate { private const int VanillaRate = 50; private const int DefaultRate = 60; private const int MaxRate = 120; private const float RateTolerance = 0.0001f; private const float NotCaptured = -1f; private static ConfigEntry<bool> enabled; private static ConfigEntry<int> rate; private static float originalStep = -1f; private static bool applied; internal static string Status => (applied ? "on - " : "off - ") + Mathf.RoundToInt(1f / Time.fixedDeltaTime) + " physics ticks a second"; internal static void BindSettings(ConfigFile config) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown enabled = config.Bind<bool>("General", "FasterPhysics", false, "The game only acts on movement, attacks, blocking and dodging on its physics tick, 50 times a second, which adds up to 20 ms before a press does anything. This runs that tick faster, so presses are picked up sooner. It costs CPU time, so it can lower FPS on slower computers. Test it with your other mods."); rate = config.Bind<int>("General", "PhysicsRate", 60, new ConfigDescription("Physics ticks per second while FasterPhysics is on. The game's own rate is 50.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 120), Array.Empty<object>())); } internal static void Sync() { bool num = enabled.Value && !Monitor.AllOff; float num2 = 1f / (float)rate.Value; if (num) { if (originalStep == -1f) { originalStep = Time.fixedDeltaTime; } if (Mathf.Abs(Time.fixedDeltaTime - num2) > 0.0001f) { Time.fixedDeltaTime = num2; } } else if (applied && originalStep != -1f) { Time.fixedDeltaTime = originalStep; } applied = num; } } internal static class NvidiaReflex { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr QueryInterface(uint id); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Initialize(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetSleepMode(IntPtr device, byte[] parameters); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Sleep(IntPtr device); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetSleepStatus(IntPtr device, byte[] parameters); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetDevice(IntPtr self, out IntPtr device); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint Release(IntPtr self); private const int NvidiaVendorId = 4318; private const string NvapiLibrary = "nvapi64.dll"; private const string QueryEntryPoint = "nvapi_QueryInterface"; private const uint InitializeId = 22079528u; private const uint SetSleepModeId = 2887559648u; private const uint SleepId = 2234307026u; private const uint GetSleepStatusId = 2935581857u; private const int NvapiOk = 0; private const int SleepParamsSize = 44; private const int SleepParamsVersion = 65580; private const int StatusParamsSize = 136; private const int StatusParamsVersion = 65672; private const int StatusLowLatencyOffset = 4; private const int VersionOffset = 0; private const int LowLatencyOffset = 4; private const int BoostOffset = 5; private const int MinimumIntervalOffset = 8; private const byte On = 1; private const byte Off = 0; private const int NoFrameCap = 0; private const int GetDeviceSlot = 3; private const int ReleaseSlot = 2; private const int NoFrame = -1; private const int ConfirmAfterFrames = 120; private static ConfigEntry<bool> enabled; private static ConfigEntry<bool> boost; private static string unavailable; private static SetSleepMode setSleepMode; private static Sleep sleep; private static GetSleepStatus getSleepStatus; private static IntPtr device = IntPtr.Zero; private static bool started; private static bool applied; private static bool appliedBoost; private static int appliedInterval; private static bool driverAgrees; private static int lastSleptFrame = -1; private static int confirmAtFrame = -1; internal static readonly DriverWait Wait = new DriverWait(); internal static bool Working { get { if (applied) { return driverAgrees; } return false; } } internal static string Status { get { if (unavailable != null) { return "off - " + unavailable; } if (!applied) { return "off"; } bool? flag = DriverReportsLowLatency(); string text = ((flag == true) ? "driver confirms it's active" : ((flag == false) ? "driver says it's NOT active" : "driver can't report")); return "on - " + text + ", waited " + Wait.Describe(); } } [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr LoadLibrary(string name); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr module, string name); internal static void BindSettings(ConfigFile config) { enabled = config.Bind<bool>("General", "NvidiaReflex", false, "Turns on NVIDIA Reflex low latency mode, which keeps the game from running ahead of your graphics card so what you press shows up as soon as possible. Only works on NVIDIA graphics cards with DirectX 11, the game's default. On anything else it turns itself off."); boost = config.Bind<bool>("General", "NvidiaReflexBoost", false, "Also keeps your graphics card at full clock speed while Reflex is on. Lowers latency a little more when your FPS is limited by the CPU, at the cost of more power and heat."); unavailable = UnsupportedReason(); if (unavailable != null && enabled.Value) { ResponsiveInputPlugin.Log.LogInfo((object)("NVIDIA Reflex is off: " + unavailable + ".")); } } internal static void GameChanged() { if (unavailable == null) { unavailable = "the game has changed"; } } private static string UnsupportedReason() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 if ((int)Application.platform != 2) { return "Windows only"; } if ((int)SystemInfo.graphicsDeviceType != 2) { return "needs DirectX 11"; } if (SystemInfo.graphicsDeviceVendorID != 4318) { return "needs an NVIDIA graphics card"; } return null; } internal static void Sync() { if (unavailable != null) { return; } try { Toggle(); } catch (Exception ex) { TurnOff("it failed: " + ex.Message); } } private static void Toggle() { bool flag = enabled.Value && !Monitor.AllOff; int num = (flag ? DriverCap.IntervalMicroseconds : 0); if ((flag != applied || boost.Value != appliedBoost || num != appliedInterval) && (flag || applied) && (started || Start())) { if (!Apply(flag, flag && boost.Value, num)) { TurnOff("not supported by this graphics card or driver"); return; } applied = flag; appliedBoost = flag && boost.Value; appliedInterval = num; Report(); } } private static void Report() { if (!applied) { driverAgrees = false; confirmAtFrame = -1; ResponsiveInputPlugin.Log.LogInfo((object)"NVIDIA Reflex is off."); } else { driverAgrees = true; confirmAtFrame = Time.frameCount + 120; } } private static void Confirm() { confirmAtFrame = -1; string text = (appliedBoost ? "low latency mode with boost" : "low latency mode"); bool? flag = DriverReportsLowLatency(); driverAgrees = flag != false; if (flag == true) { ResponsiveInputPlugin.Log.LogInfo((object)("NVIDIA Reflex is on: the driver confirms " + text + " is active.")); } else if (flag == false) { ResponsiveInputPlugin.Log.LogWarning((object)"NVIDIA Reflex was turned on, but the driver reports low latency mode is not active."); } else { ResponsiveInputPlugin.Log.LogInfo((object)("NVIDIA Reflex is on: the driver accepted " + text + ", but couldn't report its status.")); } } private static bool? DriverReportsLowLatency() { if (getSleepStatus == null) { return null; } byte[] array = new byte[136]; BitConverter.GetBytes(65672).CopyTo(array, 0); if (getSleepStatus(device, array) != 0) { return null; } return array[4] != 0; } internal static void BeforeInput() { if (applied && sleep != null && Time.frameCount != lastSleptFrame) { lastSleptFrame = Time.frameCount; long timestamp = Stopwatch.GetTimestamp(); sleep(device); Wait.Add(Stopwatch.GetTimestamp() - timestamp); if (confirmAtFrame != -1 && Time.frameCount >= confirmAtFrame) { Confirm(); } } } private static bool Start() { started = true; IntPtr intPtr = LoadLibrary("nvapi64.dll"); IntPtr intPtr2 = ((intPtr != IntPtr.Zero) ? GetProcAddress(intPtr, "nvapi_QueryInterface") : IntPtr.Zero); if (intPtr2 == IntPtr.Zero) { TurnOff("NVIDIA driver not found"); return false; } QueryInterface delegateForFunctionPointer = Marshal.GetDelegateForFunctionPointer<QueryInterface>(intPtr2); IntPtr intPtr3 = delegateForFunctionPointer(22079528u); IntPtr intPtr4 = delegateForFunctionPointer(2887559648u); IntPtr intPtr5 = delegateForFunctionPointer(2234307026u); IntPtr intPtr6 = delegateForFunctionPointer(2935581857u); if (intPtr3 == IntPtr.Zero || intPtr4 == IntPtr.Zero || intPtr5 == IntPtr.Zero || Marshal.GetDelegateForFunctionPointer<Initialize>(intPtr3)() != 0) { TurnOff("NVIDIA driver too old"); return false; } device = GraphicsDevice(); if (device == IntPtr.Zero) { TurnOff("couldn't reach the graphics device"); return false; } setSleepMode = Marshal.GetDelegateForFunctionPointer<SetSleepMode>(intPtr4); sleep = Marshal.GetDelegateForFunctionPointer<Sleep>(intPtr5); if (intPtr6 != IntPtr.Zero) { getSleepStatus = Marshal.GetDelegateForFunctionPointer<GetSleepStatus>(intPtr6); } return true; } private static IntPtr GraphicsDevice() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown Texture2D val = new Texture2D(1, 1); try { val.Apply(); IntPtr nativeTexturePtr = ((Texture)val).GetNativeTexturePtr(); if (nativeTexturePtr == IntPtr.Zero) { return IntPtr.Zero; } Marshal.GetDelegateForFunctionPointer<GetDevice>(VirtualMethod(nativeTexturePtr, 3))(nativeTexturePtr, out var intPtr); if (intPtr != IntPtr.Zero) { Marshal.GetDelegateForFunctionPointer<Release>(VirtualMethod(intPtr, 2))(intPtr); } return intPtr; } finally { Object.Destroy((Object)(object)val); } } private static IntPtr VirtualMethod(IntPtr comObject, int slot) { return Marshal.ReadIntPtr(Marshal.ReadIntPtr(comObject), slot * IntPtr.Size); } private static bool Apply(bool lowLatency, bool withBoost, int intervalMicroseconds) { byte[] array = new byte[44]; BitConverter.GetBytes(65580).CopyTo(array, 0); array[4] = (lowLatency ? ((byte)1) : ((byte)0)); array[5] = (withBoost ? ((byte)1) : ((byte)0)); BitConverter.GetBytes(intervalMicroseconds).CopyTo(array, 8); return setSleepMode(device, array) == 0; } private static void TurnOff(string reason) { unavailable = reason; applied = false; ResponsiveInputPlugin.Log.LogWarning((object)("NVIDIA Reflex is off: " + reason + ".")); } } internal sealed class DriverWait { private const double MillisecondsPerSecond = 1000.0; private long waitedTicks; private int calls; private int frames; private double shownMilliseconds; private int shownCalls; private int shownFrames; internal void Add(long ticks) { waitedTicks += ticks; calls++; } internal void CountFrame() { frames++; } internal void Roll() { shownMilliseconds = ((calls > 0) ? ((double)waitedTicks * 1000.0 / (double)Stopwatch.Frequency / (double)calls) : 0.0); shownCalls = calls; shownFrames = frames; waitedTicks = 0L; calls = 0; frames = 0; } internal string Describe() { return shownMilliseconds.ToString("0.00") + " ms a frame (ran on " + shownCalls + " of " + shownFrames + " frames)"; } } }