sinmai-mods/UnlockFrameRate/FrameRatePlugin.cs
2024-06-01 19:30:03 +07:00

104 lines
3.2 KiB
C#

#pragma warning disable IDE0051
// ReSharper disable UnusedMember.Local
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
namespace UnlockFrameRate;
[BepInPlugin("io.github.beerpsi.sinmai.framerate", "FrameRate", "0.1.0")]
[BepInProcess("Sinmai.exe")]
public class FrameRatePlugin : BaseUnityPlugin
{
public static int TargetFrameRate { get; private set; } = 60;
public new static ManualLogSource Logger = BepInEx.Logging.Logger.CreateLogSource("FrameRate");
private ConfigEntry<int> _configFrameRate;
private ConfigEntry<int> _configVSyncCount;
private ConfigEntry<bool> _configDisplayFps;
private Harmony _harmony;
private void Awake()
{
_configFrameRate = Config.Bind(
"Config",
"FrameRate",
60,
"The frame rate to run the game at");
_configVSyncCount = Config.Bind(
"Config",
"VSyncCount",
0,
"Supported values are 0 to 4. 0 disables VSync and the rest enables it.\nWhen this is enabled, FrameRate is ignored and the target frame rate\nis calculated by taking the current refresh rate divided by VSyncCount\n(e.g. 120Hz at VSyncCount 2 => 60fps).");
_configDisplayFps = Config.Bind(
"Config",
"DisplayFPS",
false,
"Show an FPS counter");
if (_configVSyncCount.Value is > 0 and <= 4)
{
TargetFrameRate = Screen.currentResolution.refreshRate / _configVSyncCount.Value;
QualitySettings.vSyncCount = _configVSyncCount.Value;
Logger.LogInfo(
"VSync is enabled (VSyncCount={0}), target frame rate is {1}fps",
_configVSyncCount.Value,
TargetFrameRate);
}
else
{
TargetFrameRate = _configFrameRate.Value;
Application.targetFrameRate = TargetFrameRate;
QualitySettings.vSyncCount = 0;
Logger.LogInfo(
"VSync is disabled, target frame rate is {0}fps",
TargetFrameRate);
}
Time.fixedDeltaTime = 1f / TargetFrameRate * Time.timeScale;
Logger.LogDebug(
"Setting Time.fixedDeltaTime to {0}s",
Time.fixedDeltaTime);
Logger.LogDebug("Patching hardcoded frame time usages");
_harmony = new Harmony("io.github.beerpsi.sinmai.framerate");
_harmony.PatchAll();
}
private const int FpsSamples = 100;
private int _currentFps = 0;
private int _currentSampleCount = FpsSamples;
private float _totalTime = 0;
private void OnGUI()
{
if (!_configDisplayFps.Value)
{
return;
}
_totalTime += Time.deltaTime;
_currentSampleCount--;
if (_currentSampleCount == 0)
{
_currentFps = (int)(FpsSamples / _totalTime);
_totalTime = 0f;
_currentSampleCount = FpsSamples;
}
GUI.Label(new Rect(10f, 10f, 150f, 100f), "FPS: " + _currentFps);
}
private void OnDestroy()
{
_harmony?.UnpatchSelf();
}
}