commit fc970fa3d8a198040a6f407c183920fd1248039a Author: whoswhip Date: Thu Jul 23 08:59:10 2026 -0400 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6a182b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,429 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +*.env + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ + +[Dd]ebug/x64/ +[Dd]ebugPublic/x64/ +[Rr]elease/x64/ +[Rr]eleases/x64/ +bin/x64/ +obj/x64/ + +[Dd]ebug/x86/ +[Dd]ebugPublic/x86/ +[Rr]elease/x86/ +[Rr]eleases/x86/ +bin/x86/ +obj/x86/ + +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +[Aa][Rr][Mm]64[Ee][Cc]/ +bld/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Build results on 'Bin' directories +**/[Bb]in/* +# Uncomment if you have tasks that rely on *.refresh files to move binaries +# (https://github.com/github/gitignore/pull/3736) +#!**/[Bb]in/*.refresh + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* +*.trx + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Approval Tests result files +*.received.* + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +.artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.idb +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +**/.paket/paket.exe +paket-files/ + +# FAKE - F# Make +**/.fake/ + +# CodeRush personal settings +**/.cr/personal + +# Python Tools for Visual Studio (PTVS) +**/__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +#tools/** +#!tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog +MSBuild_Logs/ + +# AWS SAM Build and Temporary Artifacts folder +.aws-sam + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +**/.mfractor/ + +# Local History for Visual Studio +**/.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +**/.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4532d27 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 whoswhip + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ce4a6ac --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# RhythiaLib + +A .NET 10 C# library for reading and writing Rhythia replay and map files. + +Currently only `.rhr` replay files are supported, but `.rhm` map files are easy to implement in the coming days. + +This library is designed for the Steam version of Rhythia, but it may work with the open-source one as well if they end up using the same formats. As of now (July 2026) the open-source version supports `.rhm` maps. + +## Installation + +Install the package from Nuget: + +```bash +dotnet add package RhythiaLib +``` + +Or reference the project directly: + +```bash +dotnet add reference path/to/RhythiaLib/RhythiaLib/RhythiaLib.csproj +``` + +## Supported Formats + +| Extension | Status | Description | +| --------- | --------- | --------------------------- | +| .rhr | Supported | Rhythia replay file | +| .rhm | Planned | Rhythia map file/archive | +| .sspm | Possibly | Legacy/SoundSpace+ map file | + +## Usage + +- [RHR Files](./RhythiaLib/Rhr/USAGE.MD) + +## Testing + +Run all tests with: + +```bash +dotnet test +``` + +## License +Licensed under the MIT License. See [LICENSE](./LICENSE) for details. \ No newline at end of file diff --git a/RhythiaLib.Tests/Rhr/Fixtures/After-BeatmapHash-1.rhr b/RhythiaLib.Tests/Rhr/Fixtures/After-BeatmapHash-1.rhr new file mode 100644 index 0000000..57245bc Binary files /dev/null and b/RhythiaLib.Tests/Rhr/Fixtures/After-BeatmapHash-1.rhr differ diff --git a/RhythiaLib.Tests/Rhr/Fixtures/After-BeatmapHash-2.rhr b/RhythiaLib.Tests/Rhr/Fixtures/After-BeatmapHash-2.rhr new file mode 100644 index 0000000..ffdfd9f Binary files /dev/null and b/RhythiaLib.Tests/Rhr/Fixtures/After-BeatmapHash-2.rhr differ diff --git a/RhythiaLib.Tests/Rhr/Fixtures/After-FailTime-1.rhr b/RhythiaLib.Tests/Rhr/Fixtures/After-FailTime-1.rhr new file mode 100644 index 0000000..ae64352 Binary files /dev/null and b/RhythiaLib.Tests/Rhr/Fixtures/After-FailTime-1.rhr differ diff --git a/RhythiaLib.Tests/Rhr/Fixtures/After-FailTime-2.rhr b/RhythiaLib.Tests/Rhr/Fixtures/After-FailTime-2.rhr new file mode 100644 index 0000000..b3e6857 Binary files /dev/null and b/RhythiaLib.Tests/Rhr/Fixtures/After-FailTime-2.rhr differ diff --git a/RhythiaLib.Tests/Rhr/Fixtures/After-Int32Time.rhr b/RhythiaLib.Tests/Rhr/Fixtures/After-Int32Time.rhr new file mode 100644 index 0000000..ae64352 Binary files /dev/null and b/RhythiaLib.Tests/Rhr/Fixtures/After-Int32Time.rhr differ diff --git a/RhythiaLib.Tests/Rhr/RhrFileReadTests.cs b/RhythiaLib.Tests/Rhr/RhrFileReadTests.cs new file mode 100644 index 0000000..877285e --- /dev/null +++ b/RhythiaLib.Tests/Rhr/RhrFileReadTests.cs @@ -0,0 +1,36 @@ +using RhythiaLib.Rhr; + +namespace RhythiaLib.Tests.Rhr +{ + public sealed class RhrFileReadTests + { + [Fact] + public void Decode_ValidReplay_ReturnsExpectedValues() + { + RhrReplay original = RhrTestData.CreateCurrentReplay(); + byte[] bytes = RhrFile.Encode(original); + File.WriteAllBytes("test.rhr", bytes); + RhrReplay decoded = RhrFile.Decode(bytes); + + Assert.Equal(original.Version, decoded.Version); + Assert.Equal(original.ScoreData.TimestampTicks, decoded.ScoreData.TimestampTicks); + Assert.Equal("TestPlayerName", decoded.ScoreData.PlayerName); + Assert.Equal("test_legacy_map", decoded.ScoreData.LegacyMapId); + Assert.Equal(1234, decoded.ScoreData.MapId); + Assert.Equal(1f, decoded.ScoreData.Accuracy); + Assert.Equal(2, decoded.Frames.Count); + Assert.Equal(16, decoded.Frames[1].Time); + Assert.Equal(-0.5f, decoded.Frames[1].PositionY); + } + + [Fact] + public void Read_LeavesCallerStreamOpen() + { + byte[] bytes = RhrFile.Encode(RhrTestData.CreateCurrentReplay()); + + using var stream = new MemoryStream(bytes); + _ = RhrFile.Read(stream); + Assert.True(stream.CanRead); + } + } +} diff --git a/RhythiaLib.Tests/Rhr/RhrRoundTripTests.cs b/RhythiaLib.Tests/Rhr/RhrRoundTripTests.cs new file mode 100644 index 0000000..ce4d57e --- /dev/null +++ b/RhythiaLib.Tests/Rhr/RhrRoundTripTests.cs @@ -0,0 +1,33 @@ +using RhythiaLib.Rhr; + +namespace RhythiaLib.Tests.Rhr +{ + public sealed class RhrRoundTripTests + { + [Fact] + public void SyntheticReplay_RoundTripsExactly() + { + RhrReplay original = RhrTestData.CreateCurrentReplay(); + + byte[] firstEncoding = RhrFile.Encode(original); + + RhrReplay decoded = RhrFile.Decode(firstEncoding); + + byte[] secondEncoding = RhrFile.Encode(original); + + Assert.Equal(firstEncoding, secondEncoding); + } + + [Theory] + [MemberData(nameof(RhrTestData.FixturePaths), MemberType = typeof(RhrTestData))] + public void RealFixture_RoundTripsExactly(string path) + { + byte[] originalBytes = File.ReadAllBytes(path); + + RhrReplay replay = RhrFile.Decode(originalBytes); + byte[] encodedBytes = RhrFile.Encode(replay); + + Assert.Equal(originalBytes, encodedBytes); + } + } +} diff --git a/RhythiaLib.Tests/Rhr/RhrTestData.cs b/RhythiaLib.Tests/Rhr/RhrTestData.cs new file mode 100644 index 0000000..baaf239 --- /dev/null +++ b/RhythiaLib.Tests/Rhr/RhrTestData.cs @@ -0,0 +1,80 @@ +using RhythiaLib.Rhr; + +namespace RhythiaLib.Tests.Rhr +{ + internal static class RhrTestData + { + public static RhrReplay CreateCurrentReplay() + { + return new RhrReplay + { + Version = RhrVersions.BeatmapHash, + ScoreData = new RhrScoreData + { + TimestampTicks = new DateTime( + 2026, + 7, + 23, + 12, + 0, + 0, + DateTimeKind.Unspecified + ).Ticks, + PlayerName = "TestPlayerName", + LegacyMapId = "test_legacy_map", + MapId = 1234, + StartFrom = 0, + Mode = "online_profile", + Passed = true, + ModsJson = "[]", + Spin = false, + Speed = 1f, + TotalScore = 1_000_000, + Accuracy = 1f, + Hits = 100, + Misses = 0, + Points = 100f, + Failed = false, + FailTime = -1, + BeatmapHash = + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + }, + Frames = + [ + new RhrReplayFrame + { + Time = 0, + PositionX = 0f, + PositionY = 0f, + Health = 1f, + IsImportantFrame = 0, + }, + new RhrReplayFrame + { + Time = 16, + PositionX = 0.7f, + PositionY = -0.5f, + Health = 0.85f, + IsImportantFrame = 1, + }, + ], + }; + } + + public static TheoryData FixturePaths() + { + var data = new TheoryData(); + string directory = Path.Combine(AppContext.BaseDirectory, "Rhr", "Fixtures"); + + if (!Directory.Exists(directory)) + return data; + + foreach (string path in Directory.EnumerateFiles(directory, "*.rhr")) + { + data.Add(path); + } + + return data; + } + } +} diff --git a/RhythiaLib.Tests/Rhr/RhrVersionTests.cs b/RhythiaLib.Tests/Rhr/RhrVersionTests.cs new file mode 100644 index 0000000..b4ea36d --- /dev/null +++ b/RhythiaLib.Tests/Rhr/RhrVersionTests.cs @@ -0,0 +1,71 @@ +using RhythiaLib.Rhr; + +namespace RhythiaLib.Tests.Rhr +{ + public sealed class RhrVersionTests + { + [Fact] + public void LegacyTimeVersion_RoundTripsFrameTime() + { + RhrReplay replay = RhrTestData.CreateCurrentReplay(); + replay.Version = RhrVersions.Int32Time - 1; + replay.Frames = + [ + new RhrReplayFrame + { + Time = 1234, + PositionX = 0.5f, + PositionY = 0.2f, + Health = 1f, + IsImportantFrame = 0, + }, + ]; + + byte[] bytes = RhrFile.Encode(replay); + + RhrReplay decoded = RhrFile.Decode(bytes); + Assert.Equal(1234, decoded.Frames[0].Time); + } + + [Fact] + public void LegacyYVersion_PreservesY() + { + RhrReplay replay = RhrTestData.CreateCurrentReplay(); + replay.Version = RhrVersions.NegateY - 1; + replay.Frames = + [ + new RhrReplayFrame + { + Time = 1234, + PositionX = 0.5f, + PositionY = 0.2f, + Health = 1f, + IsImportantFrame = 0, + }, + ]; + + byte[] bytes = RhrFile.Encode(replay); + + RhrReplay decoded = RhrFile.Decode(bytes); + Assert.Equal(0.2f, decoded.Frames[0].PositionY); + } + + [Fact] + public void VersionBeforeExtendedFields_UsesDefaults() + { + RhrReplay replay = RhrTestData.CreateCurrentReplay(); + + replay.Version = RhrVersions.ExtendedFields - 1; + + byte[] bytes = RhrFile.Encode(replay); + + RhrReplay decoded = RhrFile.Decode(bytes); + + Assert.True(decoded.ScoreData.Passed); + Assert.Equal("[]", decoded.ScoreData.ModsJson); + Assert.False(decoded.ScoreData.Spin); + Assert.Equal(0f, decoded.ScoreData.Speed); + Assert.Equal(0, decoded.ScoreData.TotalScore); + } + } +} diff --git a/RhythiaLib.Tests/Rhr/RhrWriteTests.cs b/RhythiaLib.Tests/Rhr/RhrWriteTests.cs new file mode 100644 index 0000000..0895624 --- /dev/null +++ b/RhythiaLib.Tests/Rhr/RhrWriteTests.cs @@ -0,0 +1,41 @@ +using RhythiaLib.Rhr; + +namespace RhythiaLib.Tests.Rhr +{ + public sealed class RhrWriteTests + { + [Fact] + public void Write_LeavesCallerStreamOpen() + { + RhrReplay replay = RhrTestData.CreateCurrentReplay(); + + using var stream = new MemoryStream(); + RhrFile.Write(stream, replay); + + Assert.True(stream.CanWrite); + Assert.NotEqual(0, stream.Length); + } + + [Fact] + public void Encode_WritesFrameCount() + { + RhrReplay replay = RhrTestData.CreateCurrentReplay(); + + byte[] data = RhrFile.Encode(replay); + RhrReplay decoded = RhrFile.Decode(data); + + Assert.Equal(replay.Frames.Count, decoded.Frames.Count); + } + + [Fact] + public void Write_NonFiniteCoordinate_Throws() + { + RhrReplay replay = RhrTestData.CreateCurrentReplay(); + replay.Frames[0].PositionX = float.NaN; + + using var stream = new MemoryStream(); + + Assert.Throws(() => RhrFile.Write(stream, replay)); + } + } +} diff --git a/RhythiaLib.Tests/RhythiaLib.Tests.csproj b/RhythiaLib.Tests/RhythiaLib.Tests.csproj new file mode 100644 index 0000000..e07d8e2 --- /dev/null +++ b/RhythiaLib.Tests/RhythiaLib.Tests.csproj @@ -0,0 +1,29 @@ + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + diff --git a/RhythiaLib.slnx b/RhythiaLib.slnx new file mode 100644 index 0000000..7eda375 --- /dev/null +++ b/RhythiaLib.slnx @@ -0,0 +1,7 @@ + + + + diff --git a/RhythiaLib/Rhr/Internal/RhrFrameCodec.cs b/RhythiaLib/Rhr/Internal/RhrFrameCodec.cs new file mode 100644 index 0000000..a735af2 --- /dev/null +++ b/RhythiaLib/Rhr/Internal/RhrFrameCodec.cs @@ -0,0 +1,79 @@ +namespace RhythiaLib.Rhr.Internal +{ + internal static class RhrFrameCodec + { + public const int WireSize = 17; // total size of frame in bytes + + public static RhrReplayFrame Read(BinaryReader reader, int version) + { + ArgumentNullException.ThrowIfNull(reader); + + bool usesInt32Time = version >= RhrVersions.Int32Time; + float? legacyWireTime = usesInt32Time ? null : reader.ReadSingle(); + int time = usesInt32Time + ? reader.ReadInt32() + : ConvertLegacyTime(legacyWireTime!.Value); + + float positionX = reader.ReadSingle(); + float positionY = reader.ReadSingle(); + float health = reader.ReadSingle(); + byte isImportantFrame = reader.ReadByte(); + + if (version < RhrVersions.NegateY) + positionY = -positionY; + + return new RhrReplayFrame + { + Time = time, + PositionX = positionX, + PositionY = positionY, + Health = health, + IsImportantFrame = isImportantFrame, + LegacyWireTime = legacyWireTime, + DecodedLegacyTime = legacyWireTime.HasValue ? time : null, + }; + } + + public static void Write(BinaryWriter writer, RhrReplayFrame frame, int version) + { + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(frame); + + bool usesInt32Time = version >= RhrVersions.Int32Time; + bool negateY = version < RhrVersions.NegateY; + + if (usesInt32Time) + writer.Write(frame.Time); + else + writer.Write( + frame.LegacyWireTime.HasValue && frame.DecodedLegacyTime == frame.Time + ? frame.LegacyWireTime.Value + : (float)frame.Time + ); + + writer.Write(frame.PositionX); + writer.Write(negateY ? -frame.PositionY : frame.PositionY); + writer.Write(frame.Health); + writer.Write(frame.IsImportantFrame); + } + + private static int ConvertLegacyTime(float value) + { + if (!float.IsFinite(value)) + { + throw new InvalidRhrFormatException( + "A legacy replay frame contains a non finite time." + ); + } + + if (value > int.MaxValue || value < int.MinValue) + { + throw new InvalidRhrFormatException( + $"Legacy frame time {value} is outside the Int32 range." + ); + } + + return (int)value; + } + } +} diff --git a/RhythiaLib/Rhr/Internal/RhrReader.cs b/RhythiaLib/Rhr/Internal/RhrReader.cs new file mode 100644 index 0000000..f8cad2f --- /dev/null +++ b/RhythiaLib/Rhr/Internal/RhrReader.cs @@ -0,0 +1,54 @@ +using System.Text; + +namespace RhythiaLib.Rhr.Internal +{ + internal static class RhrReader + { + public static RhrReplay Read(Stream stream, RhrReadOptions options) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(options); + + if (!stream.CanRead) + throw new ArgumentException("The stream must be readable.", nameof(stream)); + + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); + + try + { + int version = reader.ReadInt32(); + + RhrScoreData scoreData = RhrScoreDataCodec.Read(reader, version); + + int frameCount = reader.ReadInt32(); + + RhrValidation.ValidateFrameCount(stream, frameCount, options); + + var frames = new List(frameCount); + + for (int index = 0; index < frameCount; index++) + { + RhrReplayFrame frame = RhrFrameCodec.Read(reader, version); + frames.Add(frame); + } + + RhrValidation.ValidateEndOfStream(stream); + + return new RhrReplay + { + Version = version, + ScoreData = scoreData, + Frames = frames, + }; + } + catch (EndOfStreamException exception) + { + throw new InvalidRhrFormatException("The replay is truncated.", exception); + } + catch (IOException exception) + { + throw new InvalidRhrFormatException("The replay could not be read.", exception); + } + } + } +} diff --git a/RhythiaLib/Rhr/Internal/RhrScoreDataCodec.cs b/RhythiaLib/Rhr/Internal/RhrScoreDataCodec.cs new file mode 100644 index 0000000..029e77e --- /dev/null +++ b/RhythiaLib/Rhr/Internal/RhrScoreDataCodec.cs @@ -0,0 +1,95 @@ +namespace RhythiaLib.Rhr.Internal +{ + internal static class RhrScoreDataCodec + { + public static RhrScoreData Read(BinaryReader reader, int version) + { + ArgumentNullException.ThrowIfNull(reader); + + var scoreData = new RhrScoreData + { + TimestampTicks = reader.ReadInt64(), + PlayerName = reader.ReadString(), + LegacyMapId = reader.ReadString(), + MapId = reader.ReadInt32(), + StartFrom = reader.ReadInt32(), + Mode = reader.ReadString(), + }; + + if (version >= RhrVersions.ExtendedFields) + { + scoreData.Passed = reader.ReadBoolean(); + scoreData.ModsJson = reader.ReadString(); + scoreData.Spin = reader.ReadBoolean(); + scoreData.Speed = reader.ReadSingle(); + scoreData.TotalScore = reader.ReadInt64(); + } + else + { + scoreData.Passed = true; + scoreData.ModsJson = "[]"; + scoreData.Spin = false; + scoreData.Speed = 0f; + scoreData.TotalScore = 0; + } + + scoreData.Accuracy = reader.ReadSingle(); + scoreData.Hits = reader.ReadInt32(); + scoreData.Misses = reader.ReadInt32(); + scoreData.Points = reader.ReadSingle(); + + if (version >= RhrVersions.FailTime) + { + scoreData.FailTime = reader.ReadInt32(); + scoreData.Failed = scoreData.FailTime >= 0; + } + else + { + scoreData.FailTime = -1; + scoreData.Failed = false; + } + + scoreData.BeatmapHash = + version >= RhrVersions.BeatmapHash ? reader.ReadString() : string.Empty; + + return scoreData; + } + + public static void Write(BinaryWriter writer, RhrScoreData scoreData, int version) + { + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(scoreData); + + writer.Write(scoreData.TimestampTicks); + writer.Write(scoreData.PlayerName); + writer.Write(scoreData.LegacyMapId); + writer.Write(scoreData.MapId); + writer.Write(scoreData.StartFrom); + writer.Write(scoreData.Mode); + + if (version >= RhrVersions.ExtendedFields) + { + writer.Write(scoreData.Passed); + writer.Write(scoreData.ModsJson); + writer.Write(scoreData.Spin); + writer.Write(scoreData.Speed); + writer.Write(scoreData.TotalScore); + } + + writer.Write(scoreData.Accuracy); + writer.Write(scoreData.Hits); + writer.Write(scoreData.Misses); + writer.Write(scoreData.Points); + + if (version >= RhrVersions.FailTime) + { + writer.Write(scoreData.Failed ? scoreData.FailTime : -1); + } + + if (version >= RhrVersions.BeatmapHash) + { + writer.Write(scoreData.BeatmapHash); + } + } + } +} diff --git a/RhythiaLib/Rhr/Internal/RhrValidation.cs b/RhythiaLib/Rhr/Internal/RhrValidation.cs new file mode 100644 index 0000000..90d1101 --- /dev/null +++ b/RhythiaLib/Rhr/Internal/RhrValidation.cs @@ -0,0 +1,104 @@ +namespace RhythiaLib.Rhr.Internal +{ + internal static class RhrValidation + { + public static void ValidateFrameCount( + Stream streamm, + int frameCount, + RhrReadOptions options + ) + { + ArgumentNullException.ThrowIfNull(streamm); + ArgumentNullException.ThrowIfNull(options); + + if (frameCount < 0) + throw new InvalidRhrFormatException($"Negative frame count: {frameCount}."); + + if (frameCount > options.MaximumFrameCount) + throw new InvalidRhrFormatException( + $"Frame count {frameCount} exceeded the configured maximum of {options.MaximumFrameCount}" + ); + + if (!streamm.CanSeek) + return; + + long requiredBytes = checked((long)frameCount * RhrFrameCodec.WireSize); + long remainingBytes = streamm.Length - streamm.Position; + + if (remainingBytes < requiredBytes) + { + throw new InvalidRhrFormatException( + $"The replay declares {frameCount} frames, " + + $"requiring {requiredBytes} bytes, " + + $"but only {remainingBytes} bytes remain" + ); + } + } + + public static void ValidateEndOfStream(Stream stream) + { + if (!stream.CanSeek) + return; + + if (stream.Position != stream.Length) + { + long trailingByteCount = stream.Length - stream.Position; + + throw new InvalidRhrFormatException( + $"The replay contains {trailingByteCount} unexpected trailing bytes." + ); + } + } + + public static void ValidateReplay(RhrReplay replay) + { + ArgumentNullException.ThrowIfNull(replay); + ArgumentNullException.ThrowIfNull(replay.ScoreData); + ArgumentNullException.ThrowIfNull(replay.Frames); + + ValidateScoreData(replay.ScoreData); + + for (int index = 0; index < replay.Frames.Count; index++) + { + RhrReplayFrame frame = + replay.Frames[index] + ?? throw new ArgumentException($"Frame {index} is null", nameof(replay)); + + ValidateFrame(frame, index); + } + } + + private static void ValidateScoreData(RhrScoreData scoreData) + { + ArgumentNullException.ThrowIfNull(scoreData.PlayerName); + ArgumentNullException.ThrowIfNull(scoreData.LegacyMapId); + ArgumentNullException.ThrowIfNull(scoreData.Mode); + ArgumentNullException.ThrowIfNull(scoreData.ModsJson); + ArgumentNullException.ThrowIfNull(scoreData.BeatmapHash); + + if (!float.IsFinite(scoreData.Speed)) + throw new ArgumentException("Replay speed must be finite."); + + if (!float.IsFinite(scoreData.Accuracy)) + throw new ArgumentException("Replay accuracy must be finite."); + + if (!float.IsFinite(scoreData.Points)) + throw new ArgumentException("Replay points must be finite."); + + if (scoreData.Failed && scoreData.FailTime < 0) + throw new ArgumentException("A failed replay must have a non-negative fail time."); + } + + private static void ValidateFrame(RhrReplayFrame frame, int index) + { + if ( + !float.IsFinite(frame.PositionX) + || !float.IsFinite(frame.PositionY) + || !float.IsFinite(frame.Health) + ) + { + throw new ArgumentException($"Frame {index} contains a non-finite value."); + } + } + } +} diff --git a/RhythiaLib/Rhr/Internal/RhrWriter.cs b/RhythiaLib/Rhr/Internal/RhrWriter.cs new file mode 100644 index 0000000..3333f72 --- /dev/null +++ b/RhythiaLib/Rhr/Internal/RhrWriter.cs @@ -0,0 +1,31 @@ +using System.Text; + +namespace RhythiaLib.Rhr.Internal +{ + internal static class RhrWriter + { + public static void Write(Stream stream, RhrReplay replay) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(replay); + + if (!stream.CanWrite) + throw new ArgumentException("The stream must be writable.", nameof(stream)); + + RhrValidation.ValidateReplay(replay); + + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + + writer.Write(replay.Version); + + RhrScoreDataCodec.Write(writer, replay.ScoreData, replay.Version); + + writer.Write(replay.Frames.Count); + + foreach (RhrReplayFrame frame in replay.Frames) + { + RhrFrameCodec.Write(writer, frame, replay.Version); + } + } + } +} diff --git a/RhythiaLib/Rhr/InvalidRhrFormatException.cs b/RhythiaLib/Rhr/InvalidRhrFormatException.cs new file mode 100644 index 0000000..e7fb69e --- /dev/null +++ b/RhythiaLib/Rhr/InvalidRhrFormatException.cs @@ -0,0 +1,11 @@ +namespace RhythiaLib.Rhr +{ + public sealed class InvalidRhrFormatException : Exception + { + public InvalidRhrFormatException(string message) + : base(message) { } + + public InvalidRhrFormatException(string message, Exception exception) + : base(message, exception) { } + } +} diff --git a/RhythiaLib/Rhr/RhrFile.cs b/RhythiaLib/Rhr/RhrFile.cs new file mode 100644 index 0000000..1d3d653 --- /dev/null +++ b/RhythiaLib/Rhr/RhrFile.cs @@ -0,0 +1,47 @@ +using RhythiaLib.Rhr.Internal; + +namespace RhythiaLib.Rhr +{ + public static class RhrFile + { + public static RhrReplay Read(string path, RhrReadOptions? options = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(path); + + using FileStream stream = File.OpenRead(path); + return Read(stream, options); + } + + public static RhrReplay Read(Stream stream, RhrReadOptions? options = null) + { + return RhrReader.Read(stream, options ?? new RhrReadOptions()); + } + + public static void Write(string path, RhrReplay replay) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(path); + using FileStream stream = File.OpenWrite(path); + Write(stream, replay); + } + + public static void Write(Stream stream, RhrReplay replay) + { + RhrWriter.Write(stream, replay); + } + + public static byte[] Encode(RhrReplay replay) + { + using var stream = new MemoryStream(); + Write(stream, replay); + return stream.ToArray(); + } + + public static RhrReplay Decode(ReadOnlySpan data, RhrReadOptions? options = null) + { + byte[] buffer = data.ToArray(); + using var stream = new MemoryStream(buffer, writable: false); + + return Read(stream, options); + } + } +} diff --git a/RhythiaLib/Rhr/RhrReadOptions.cs b/RhythiaLib/Rhr/RhrReadOptions.cs new file mode 100644 index 0000000..ac463e0 --- /dev/null +++ b/RhythiaLib/Rhr/RhrReadOptions.cs @@ -0,0 +1,7 @@ +namespace RhythiaLib.Rhr +{ + public sealed class RhrReadOptions + { + public int MaximumFrameCount { get; init; } = 10_000_000; + } +} diff --git a/RhythiaLib/Rhr/RhrReplay.cs b/RhythiaLib/Rhr/RhrReplay.cs new file mode 100644 index 0000000..c418220 --- /dev/null +++ b/RhythiaLib/Rhr/RhrReplay.cs @@ -0,0 +1,9 @@ +namespace RhythiaLib.Rhr +{ + public sealed class RhrReplay + { + public int Version { get; set; } + public RhrScoreData ScoreData { get; set; } = new(); + public List Frames { get; set; } = []; + } +} diff --git a/RhythiaLib/Rhr/RhrReplayFrame.cs b/RhythiaLib/Rhr/RhrReplayFrame.cs new file mode 100644 index 0000000..fdb86ca --- /dev/null +++ b/RhythiaLib/Rhr/RhrReplayFrame.cs @@ -0,0 +1,14 @@ +namespace RhythiaLib.Rhr +{ + public sealed class RhrReplayFrame + { + public int Time { get; set; } + public float PositionX { get; set; } + public float PositionY { get; set; } + public float Health { get; set; } + public byte IsImportantFrame { get; set; } // im ngl, i have NO clue what this is/does + + internal float? LegacyWireTime { get; set; } + internal int? DecodedLegacyTime { get; set; } + } +} diff --git a/RhythiaLib/Rhr/RhrScoreData.cs b/RhythiaLib/Rhr/RhrScoreData.cs new file mode 100644 index 0000000..55d8d23 --- /dev/null +++ b/RhythiaLib/Rhr/RhrScoreData.cs @@ -0,0 +1,42 @@ +namespace RhythiaLib.Rhr +{ + public sealed class RhrScoreData + { + public long TimestampTicks { get; set; } + public string PlayerName { get; set; } = string.Empty; + public string LegacyMapId { get; set; } = string.Empty; + public int MapId { get; set; } + public int StartFrom { get; set; } + public string Mode { get; set; } = string.Empty; + public bool Passed { get; set; } = true; + public string ModsJson { get; set; } = "[]"; + public bool Spin { get; set; } + public float Speed { get; set; } + public long TotalScore { get; set; } + public float Accuracy { get; set; } + public int Hits { get; set; } + public int Misses { get; set; } + public float Points { get; set; } + public bool Failed { get; set; } + public int FailTime { get; set; } = -1; + public string BeatmapHash { get; set; } = string.Empty; + + public DateTime DatePlayed + { + get + { + try + { + return new DateTime(TimestampTicks, DateTimeKind.Unspecified); + } + catch (ArgumentOutOfRangeException exception) + { + throw new InvalidRhrFormatException( + $"Invalid timestamp value: {TimestampTicks}.", + exception + ); + } + } + } + } +} diff --git a/RhythiaLib/Rhr/RhrVersions.cs b/RhythiaLib/Rhr/RhrVersions.cs new file mode 100644 index 0000000..97307e5 --- /dev/null +++ b/RhythiaLib/Rhr/RhrVersions.cs @@ -0,0 +1,14 @@ +// version dates & info from: +// https://github.com/yo-ru/rhrParse/blob/69642c3347724c73fc95df18474fe0cf1c1ddb76/include/rhrParse/rhrParse.h#L79-L100 + +namespace RhythiaLib.Rhr +{ + public static class RhrVersions + { + public const int NegateY = 2026_01_18; + public const int ExtendedFields = 2026_01_25; + public const int FailTime = 2026_02_22; + public const int Int32Time = 2026_05_10; + public const int BeatmapHash = 2026_05_17; + } +} diff --git a/RhythiaLib/Rhr/USAGE.MD b/RhythiaLib/Rhr/USAGE.MD new file mode 100644 index 0000000..d41738b --- /dev/null +++ b/RhythiaLib/Rhr/USAGE.MD @@ -0,0 +1,55 @@ +## Basic usage + +### Read an RHR file + +```csharp +using RhythiaLib.Rhr; + +RhrReplay replay = RhrFile.Read("replay.rhr"); + +Console.WriteLine($"Version: {replay.Version}"); +Console.WriteLine($"Player: {replay.ScoreData.PlayerName}"); +Console.WriteLine($"Map: {replay.ScoreData.LegacyMapId}"); +Console.WriteLine($"Accuracy: {replay.ScoreData.Accuracy}%"); +Console.WriteLine($"Score: {replay.ScoreData.TotalScore}"); +Console.WriteLine($"Frames: {replay.Frames.Count}"); +``` + +### Read from a stream + +```csharp +using RhythiaLib.Rhr; + +using var stream = File.OpenRead("replay.rhr"); +RhrReplay replay = RhrFile.Read(stream); +``` + +### Decode from bytes + + +```csharp +using RhythiaLib.Rhr; + +byte[] data = File.ReadAllBytes("score-replay.rhr"); +RhrReplay replay = RhrFile.Decode(data); +``` + +### Write an RHR file + +```csharp +using RhythiaLib.Rhr; + +RhrReplay replay = RhrFile.Read("replay.rhr"); +replay.ScoreData.PlayerName = "NewPlayerName"; +RhrFile.Write("new-replay.rhr", replay); +``` + +### Encode to bytes + +```csharp +using RhythiaLib.Rhr; + +RhrReplay replay = RhrFile.Read("replay.rhr"); +byte[] data = RhrFile.Encode(replay); +File.WriteAllBytes("new-replay.rhr", data); +``` \ No newline at end of file diff --git a/RhythiaLib/RhythiaLib.csproj b/RhythiaLib/RhythiaLib.csproj new file mode 100644 index 0000000..3c64545 --- /dev/null +++ b/RhythiaLib/RhythiaLib.csproj @@ -0,0 +1,10 @@ + + + net10.0 + RhythiaLib + enable + enable + True + $(AssemblyName) + + diff --git a/dotnet-tools.json b/dotnet-tools.json new file mode 100644 index 0000000..6e2e244 --- /dev/null +++ b/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "1.3.0", + "commands": [ + "csharpier" + ], + "rollForward": false + } + } +} \ No newline at end of file