UnlockFrameRate

This commit is contained in:
beerpsi 2024-06-01 19:30:03 +07:00
parent d0d3658e9a
commit 26c90f5343
8 changed files with 394 additions and 2 deletions

View File

@ -1,6 +1,6 @@
## sinmai-mods
Miscellaneous mods for maimai DX
Miscellaneous mods for maimai DX. Mods are MonoMod unless specified otherwise.
### CachedDataManager
Speeds up game reboots by caching loaded data. Cache is stored in the `dataCache` folder
@ -56,4 +56,13 @@ them before loading into the game.
- Since this chart format does not contain timing data, the song's BPM is retrieved
by loading the `Music.xml` associated with the chart, **and it is assumed that the
chart and `Music.xml` is in the same folder**. The SXT loader will not work if the
chart file is somehow in a different folder from `Music.xml`.
chart file is somehow in a different folder from `Music.xml`.
### UnlockFrameRate
Change the target FPS. Also comes with an FPS counter.
Unlike other mods in this collection, this is a **BepInEx** mod. You will need to
install BepInEx and drop this into `BepInEx/plugins` to enable the mod.
The configuration file for changing the FPS is at `BepInEx/config/io.github.beerpsi.sinmai.framerate.cfg`
and is already documented.

View File

@ -0,0 +1,103 @@
#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();
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BepInEx.Logging;
namespace UnlockFrameRate;
internal static class ManualLogSourceExtensions
{
public static void LogInfo(this ManualLogSource logger, string format, params object[] args)
{
logger.LogInfo(string.Format(format, args));
}
public static void LogDebug(this ManualLogSource logger, string format, params object[] args)
{
logger.LogDebug(string.Format(format, args));
}
}

View File

@ -0,0 +1,88 @@
// ReSharper disable InconsistentNaming
using HarmonyLib;
using Monitor;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Manager;
using Manager.UserDatas;
namespace UnlockFrameRate;
[HarmonyPatch]
internal class PatchFrameTime
{
private const float OriginalFrameRate = 60f;
private const float OriginalFrameTime = 1000f / OriginalFrameRate;
private const float OriginalFramePerMilliseconds = OriginalFrameRate / 1000;
private static IEnumerable<MethodBase> TargetMethods()
{
var noteJudge = AccessTools.TypeByName("NoteJudge");
var juggeTiming = AccessTools.Inner(noteJudge, "JuggeTiming"); // lol
yield return AccessTools.Constructor(juggeTiming);
yield return AccessTools.Method(typeof(UserOption), nameof(UserOption.GetAdjustMSec));
yield return AccessTools.Method(typeof(NoteBase), "IsNoteCheckTimeStart");
yield return AccessTools.Method(typeof(TouchNoteB), "GetNoteYPosition");
yield return AccessTools.Method(typeof(SlideRoot), "IsNoteCheckTimeStart");
yield return AccessTools.Method(typeof(NoteJudge), nameof(NoteJudge.GetJudgeTiming));
yield return AccessTools.Method(typeof(NoteJudge), nameof(NoteJudge.GetSlideJudgeTiming));
yield return AccessTools.Method(typeof(SlideJudge), nameof(SlideJudge.Initialize));
yield return AccessTools.Method(typeof(JudgeGrade), nameof(JudgeGrade.Initialize));
yield return AccessTools.Method(typeof(NotesManager), nameof(NotesManager.getPlayFirstMsec));
yield return AccessTools.Method(typeof(NotesManager), nameof(NotesManager.getPlayFinalMsec));
yield return AccessTools.Method(typeof(NotesManager), nameof(NotesManager.getCurrentDrawFrame));
yield return AccessTools.Method(typeof(NotesReader), nameof(NotesReader.calcFrame));
yield return AccessTools.Method(typeof(NotesReader), nameof(NotesReader.GetBPM_Frame));
yield return AccessTools.Method(typeof(NotesReader), nameof(NotesReader.getMeter_Frame));
yield return AccessTools.Method(typeof(NoteData), nameof(NoteData.getLengthFrame));
yield return AccessTools.Method(typeof(GameManager), nameof(GameManager.UpdateGameTimer));
yield return AccessTools.PropertyGetter(typeof(NotesTime), nameof(NotesTime.frame));
}
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
{
var targetFrameTime = 1000f / FrameRatePlugin.TargetFrameRate;
var targetFramePerMs = (float)FrameRatePlugin.TargetFrameRate / 1000;
var i = 0;
foreach (var instruction in instructions)
{
if (instruction.opcode != OpCodes.Ldc_R4 || instruction.operand is not float operand)
{
yield return instruction;
i++;
continue;
}
var overridden = false;
if (Math.Abs(operand - OriginalFrameTime) < float.Epsilon)
{
instruction.operand = targetFrameTime;
overridden = true;
}
else if (Math.Abs(operand - OriginalFramePerMilliseconds) < float.Epsilon)
{
instruction.operand = targetFramePerMs;
overridden = true;
}
if (overridden)
{
FrameRatePlugin.Logger.LogDebug(
"Overrode constant at opcode index {0} in {1}: {2} => {3}",
i,
__originalMethod.Name,
operand,
instruction.operand);
}
yield return instruction;
i++;
}
}
}

View File

@ -0,0 +1,43 @@
using HarmonyLib;
using Monitor;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace UnlockFrameRate;
[HarmonyPatch(typeof(NoteBase), "GetMaiBugAdjustMSec")]
internal class PatchGetMaiBugAdjustMSec
{
private const float OriginalFrameRate = 60f;
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
{
var i = 0;
foreach (var instruction in instructions)
{
if (instruction.opcode != OpCodes.Ldc_R4 || instruction.operand is not float operand)
{
yield return instruction;
i++;
continue;
}
if (Math.Abs(operand - OriginalFrameRate) < float.Epsilon)
{
instruction.operand = (float)FrameRatePlugin.TargetFrameRate;
FrameRatePlugin.Logger.LogDebug(
"Overrode constant at opcode index {0} in {1}: {2} => {3}",
i,
__originalMethod.Name,
operand,
instruction.operand);
}
yield return instruction;
i++;
}
}
}

View File

@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UnlockFrameRate")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnlockFrameRate")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03F046DF-EE3C-4596-87F3-F5AA131EF401")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{03F046DF-EE3C-4596-87F3-F5AA131EF401}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UnlockFrameRate</RootNamespace>
<AssemblyName>UnlockFrameRate</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<LangVersion>latest</LangVersion>
<RestoreAdditionalProjectSources>
https://api.nuget.org/v3/index.json;
https://nuget.bepinex.dev/v3/index.json;
https://nuget.samboy.dev/v3/index.json
</RestoreAdditionalProjectSources>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>..\External\Assembly-CSharp.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<PackageReference Include="BepInEx.Analyzers" Version="1.*" PrivateAssets="all" />
<PackageReference Include="BepInEx.Core" Version="5.*" PrivateAssets="all" />
<PackageReference Include="HarmonyX" Version="2.12.0" />
<Reference Include="UnityEngine">
<HintPath>..\External\UnityEngine.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.CoreModule">
<HintPath>..\External\UnityEngine.CoreModule.dll</HintPath>
</Reference>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="all" />
<Reference Include="UnityEngine.IMGUIModule">
<HintPath>..\External\UnityEngine.IMGUIModule.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="FrameRatePlugin.cs" />
<Compile Include="ManualLogSourceExtensions.cs" />
<Compile Include="PatchFrameTime.cs" />
<Compile Include="PatchGetMaiBugAdjustMSec.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -1,5 +1,8 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CachedDataManager", "CachedDataManager\CachedDataManager.csproj", "{F1C1B6BF-626C-4F10-8672-2F9596706CA6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FixLocaleIssues", "FixLocaleIssues\FixLocaleIssues.csproj", "{48B5F480-D749-48E9-9D26-E0E5260D95DE}"
@ -10,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LooseDBTables.GeneratePatch
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MoreChartFormats", "MoreChartFormats\MoreChartFormats.csproj", "{A375F626-7238-4227-95C9-2BB1E5E099F6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnlockFrameRate", "UnlockFrameRate\UnlockFrameRate.csproj", "{03F046DF-EE3C-4596-87F3-F5AA131EF401}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -36,5 +41,15 @@ Global
{A375F626-7238-4227-95C9-2BB1E5E099F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A375F626-7238-4227-95C9-2BB1E5E099F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A375F626-7238-4227-95C9-2BB1E5E099F6}.Release|Any CPU.Build.0 = Release|Any CPU
{03F046DF-EE3C-4596-87F3-F5AA131EF401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03F046DF-EE3C-4596-87F3-F5AA131EF401}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03F046DF-EE3C-4596-87F3-F5AA131EF401}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03F046DF-EE3C-4596-87F3-F5AA131EF401}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DDE68F38-1E1E-40F9-AD55-2F5F6C804758}
EndGlobalSection
EndGlobal