From 7ec61d18e62c484a39a6fc521b19bbac459601aa Mon Sep 17 00:00:00 2001 From: donnyjang Date: Thu, 15 Oct 2026 16:14:17 -0700 Subject: [PATCH] binding: YGOLegacy.Engine carries the wire protocol; CI builds, tests and ships ygol-engine-binding.zip (TICKET-397) binding/YGOLegacy.Engine (netstandard2.1, LangVersion 9, unsafe, no package, no Unity reference) holds the Unity repo's Assets/YGOLegacy/Scripts/Protocol/ as Protocol/{Contracts,Codecs,Framing,Routing}: 12 files copied byte-identical (LF), namespaces YGOLegacy.Protocol.* unchanged. EngineVersion (default local) is stamped as the informational version, so the DLL's ProductVersion is the tag it was built for. binding/YGOLegacy.Engine.Tests (net8.0, NUnit 3.14) holds the six fixtures. 114 tests pass, the Unity Edit Mode count. Two deviations from "as-is", lead-approved 2026-10-15: LegacyReaders.cs is a frozen test-only copy of the legacy MDPro3 / YGOSharp readers and enums the parity tests compare against (they live only in the Unity repo), and FrameCodecTests.cs line 35 casts (short) instead of (byte): BitConverter.GetBytes((byte)) is ambiguous on net8.0 (the Half overload), same bytes written. The windows job builds and tests the binding after the native gates (both with -p:EngineVersion so the test's project reference does not restamp the DLL as local), checks the ProductVersion and stages ygol-engine-binding.zip (YGOLegacy.Engine.dll + .pdb) beside ygol-engine-win64.zip; attach-windows attaches both. engine.json gains "binding": "" on every platform (windows.ps1 and the Dockerfile's export-gate, the only writers) and the release job's agreement check includes it. README gains the Binding section and the asset row; .gitignore ignores binding/**/bin and obj. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DJUFwdiGCHipsxLkgxssSR --- .gitea/workflows/release.yml | 58 +- .gitignore | 2 + README.md | 39 +- .../YGOLegacy.Engine.Tests/CtosCodecTests.cs | 252 +++++++ .../FeatureCodecTests.cs | 523 +++++++++++++++ .../YGOLegacy.Engine.Tests/FrameCodecTests.cs | 312 +++++++++ .../YGOLegacy.Engine.Tests/LegacyReaders.cs | 156 +++++ .../ProtocolCodecTests.cs | 304 +++++++++ .../YGOLegacy.Engine.Tests/StocCodecTests.cs | 406 ++++++++++++ .../YGOLegacy.Engine.Tests/StocRouterTests.cs | 180 +++++ .../YGOLegacy.Engine.Tests.csproj | 21 + .../Protocol/Codecs/DuelCodecs.cs | 67 ++ .../Protocol/Codecs/FeatureCodecs.cs | 600 +++++++++++++++++ .../Protocol/Codecs/LobbyCodecs.cs | 205 ++++++ .../Protocol/Codecs/StocCodecs.cs | 393 +++++++++++ .../Protocol/Codecs/UnicodeCodec.cs | 81 +++ .../Protocol/Contracts/DuelPayloads.cs | 34 + .../Protocol/Contracts/FeaturePayloads.cs | 615 ++++++++++++++++++ .../Protocol/Contracts/LobbyPayloads.cs | 76 +++ .../Protocol/Contracts/MessageIds.cs | 83 +++ .../Protocol/Contracts/StocPayloads.cs | 205 ++++++ .../Protocol/Framing/FrameCodec.cs | 116 ++++ .../Protocol/Routing/StocRouter.cs | 71 ++ .../YGOLegacy.Engine/YGOLegacy.Engine.csproj | 19 + build/Dockerfile | 6 +- build/windows.ps1 | 9 +- 26 files changed, 4802 insertions(+), 31 deletions(-) create mode 100644 binding/YGOLegacy.Engine.Tests/CtosCodecTests.cs create mode 100644 binding/YGOLegacy.Engine.Tests/FeatureCodecTests.cs create mode 100644 binding/YGOLegacy.Engine.Tests/FrameCodecTests.cs create mode 100644 binding/YGOLegacy.Engine.Tests/LegacyReaders.cs create mode 100644 binding/YGOLegacy.Engine.Tests/ProtocolCodecTests.cs create mode 100644 binding/YGOLegacy.Engine.Tests/StocCodecTests.cs create mode 100644 binding/YGOLegacy.Engine.Tests/StocRouterTests.cs create mode 100644 binding/YGOLegacy.Engine.Tests/YGOLegacy.Engine.Tests.csproj create mode 100644 binding/YGOLegacy.Engine/Protocol/Codecs/DuelCodecs.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Codecs/FeatureCodecs.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Codecs/LobbyCodecs.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Codecs/StocCodecs.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Codecs/UnicodeCodec.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Contracts/DuelPayloads.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Contracts/FeaturePayloads.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Contracts/LobbyPayloads.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Contracts/MessageIds.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Contracts/StocPayloads.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Framing/FrameCodec.cs create mode 100644 binding/YGOLegacy.Engine/Protocol/Routing/StocRouter.cs create mode 100644 binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 37d3dec..ca28ce5 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -4,6 +4,7 @@ # CHANGELOG section for that version as the body. A gate failure in any build means no release. # # ygol-engine-win64.zip ygol-engine.dll, ygol-engine.pdb, engine.json +# ygol-engine-binding.zip YGOLegacy.Engine.dll, YGOLegacy.Engine.pdb (the C# binding, built and tested by dotnet) # ygol-engine-linux-x64.tar.gz libygol-engine.so, engine.json # ygoserver-linux-x64.tar.gz ygoserver, engine.json # ygol-engine-android-arm64.tar.gz libygol-engine.so, engine.json @@ -80,6 +81,25 @@ jobs: if ($LASTEXITCODE -ne 0) { exit 1 } Get-ChildItem $stage | Format-Table Name, Length + - name: Binding (dotnet build + test, ygol-engine-binding.zip) + run: | + $version = "local" + if ($env:GITHUB_REF -like "refs/tags/v*") { $version = $env:GITHUB_REF_NAME } + Set-Location $env:CHECKOUT_DIR + dotnet build binding\YGOLegacy.Engine -c Release -p:EngineVersion=$version + if ($LASTEXITCODE -ne 0) { exit 1 } + dotnet test binding\YGOLegacy.Engine.Tests -c Release -p:EngineVersion=$version + if ($LASTEXITCODE -ne 0) { exit 1 } + $bin = "$env:CHECKOUT_DIR\binding\YGOLegacy.Engine\bin\Release\netstandard2.1" + $got = (Get-Item "$bin\YGOLegacy.Engine.dll").VersionInfo.ProductVersion + Write-Host "YGOLegacy.Engine.dll ProductVersion = $got" + if ($got -ne $version) { Write-Host "##[error]YGOLegacy.Engine.dll is stamped '$got', expected '$version'"; exit 1 } + $stage = "$env:OUT_DIR\$version" + Copy-Item "$bin\YGOLegacy.Engine.dll", "$bin\YGOLegacy.Engine.pdb" $stage + tar.exe -a -cf "$stage\ygol-engine-binding.zip" -C $stage YGOLegacy.Engine.dll YGOLegacy.Engine.pdb + if ($LASTEXITCODE -ne 0) { exit 1 } + Get-ChildItem $stage | Format-Table Name, Length + linux: runs-on: ubuntu-latest steps: @@ -139,16 +159,16 @@ jobs: run: | set -eu tag="$GITHUB_REF_NAME" - for f in dist/linux-x64/engine.json dist/android-arm64/engine.json; do - v=$(jq -r .version "$f"); [ "$v" = "$tag" ] || { echo "::error::$f says version $v, tag is $tag"; exit 1; } - done echo "$WINDOWS_ENGINE" | jq -c . > dist/engine-windows.json - [ "$(jq -r .version dist/engine-windows.json)" = "$tag" ] || { echo "::error::Windows engine.json does not say $tag"; exit 1; } - # the export count is per platform; protocol and capabilities must agree everywhere for f in dist/engine-windows.json dist/linux-x64/engine.json dist/android-arm64/engine.json; do - jq -c '{version, protocol, capabilities}' "$f" + v=$(jq -r .version "$f"); [ "$v" = "$tag" ] || { echo "::error::$f says version $v, tag is $tag"; exit 1; } + b=$(jq -r .binding "$f"); [ "$b" = "$tag" ] || { echo "::error::$f says binding $b, tag is $tag"; exit 1; } + done + # the export count is per platform; version, protocol, capabilities and binding must agree everywhere + for f in dist/engine-windows.json dist/linux-x64/engine.json dist/android-arm64/engine.json; do + jq -c '{version, protocol, capabilities, binding}' "$f" done | sort -u | tee dist/agree.txt - [ "$(wc -l < dist/agree.txt)" -eq 1 ] || { echo "::error::the platforms disagree on version / protocol / capabilities"; exit 1; } + [ "$(wc -l < dist/agree.txt)" -eq 1 ] || { echo "::error::the platforms disagree on version / protocol / capabilities / binding"; exit 1; } cp dist/linux-x64/engine.json dist/engine.json - name: The CHANGELOG section for this version is the release body run: | @@ -191,19 +211,21 @@ jobs: run: shell: powershell steps: - - name: Attach ygol-engine-win64.zip + - name: Attach ygol-engine-win64.zip and ygol-engine-binding.zip run: | $tag = $env:GITHUB_REF_NAME - $zip = "$env:OUT_DIR\$tag\ygol-engine-win64.zip" - if (-not (Test-Path $zip)) { Write-Host "##[error]$zip is missing"; exit 1 } $id = "${{ needs.release.outputs.id }}" $respFile = Join-Path $env:TEMP "ygol-engine-upload.txt" - $status = & curl.exe -s -o $respFile -w "%{http_code}" -X POST ` - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -F "attachment=@$zip" ` - "$env:API/releases/$id/assets?name=ygol-engine-win64.zip" - if ($LASTEXITCODE -ne 0 -or [int]$status -ge 400) { - Write-Host "curl exit=$LASTEXITCODE http=$status" - if (Test-Path $respFile) { Get-Content $respFile -TotalCount 20 } - exit 1 + foreach ($name in @("ygol-engine-win64.zip", "ygol-engine-binding.zip")) { + $zip = "$env:OUT_DIR\$tag\$name" + if (-not (Test-Path $zip)) { Write-Host "##[error]$zip is missing"; exit 1 } + $status = & curl.exe -s -o $respFile -w "%{http_code}" -X POST ` + -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -F "attachment=@$zip" ` + "$env:API/releases/$id/assets?name=$name" + if ($LASTEXITCODE -ne 0 -or [int]$status -ge 400) { + Write-Host "curl exit=$LASTEXITCODE http=$status" + if (Test-Path $respFile) { Get-Content $respFile -TotalCount 20 } + exit 1 + } + Write-Host "attached $name to release $id ($tag)" } - Write-Host "attached ygol-engine-win64.zip to release $id ($tag)" diff --git a/.gitignore b/.gitignore index 9f335e1..161fb55 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ /server/obj/ /server/bin/ /out/ +binding/**/bin/ +binding/**/obj/ # what libevent's Windows prebuild step copies from WIN32-Code into include/ /server/event/include/evconfig-private.h diff --git a/README.md b/README.md index 808991e..578b856 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ library per platform, `ygol-engine`, behind a written contract. Proposal 47 in t | `build/windows.ps1` | Builds `out/win64/ygol-engine.dll` (+ `engine.json`), checks the contract header, runs the export gate. | | `build/Dockerfile` | The Linux x64 and Android arm64 builds, targets `linux` and `android`, same checks and gates. | | `build/linux.sh`, `build/android.sh` | Run the Docker targets into `out/linux-x64/` and `out/android-arm64/`. Need Docker and nothing else. | +| `binding/` | The C# binding `YGOLegacy.Engine` (the wire protocol: contracts, codecs, framing, routing) and its NUnit tests. See "Binding". | | `contract/` | The contract: `engine-contract.md` (the one spec), `ocgapi.h` (the public header), `probe-feature-messages.py` (the wire gate), `lua-reference/` (the generated Lua API). | | `CHANGELOG.md` | One row per contract change; the replayed patches 0001-0024 first. | @@ -74,8 +75,9 @@ pwsh C:\ygol-engine\build\windows.ps1 -Version v0.0.1 - Before building, the script checks `contract/ocgapi.h` against `core/ocgapi.h` + the server's `YGOSERVER_API` lines in `gframe/serverapi.h`; a drift fails the build. - Output: `out/win64/ygol-engine.dll` (+ `.pdb`) and `out/win64/engine.json` - (`{ version, exports, protocol, capabilities }`; protocol and capabilities are read from - `gframe/network.h` and the `cap.flags` line of `single_duel.cpp` / `tag_duel.cpp`, never typed in). + (`{ version, exports, protocol, capabilities, binding }`; protocol and capabilities are read from + `gframe/network.h` and the `cap.flags` line of `single_duel.cpp` / `tag_duel.cpp`, never typed in; + `binding` is the version of the C# binding released with this engine, the same string as `version`). ### The export gate is the truth @@ -125,6 +127,29 @@ Windows VM: it has no nested virtualisation). From a clean clone on any Linux bo number belongs to the pinned base image). `engine.json` is written the same way as on Windows. A `docker build` that fails the gate leaves nothing in `out/`. +## Binding + +`binding/YGOLegacy.Engine/` is the managed side of the engine: a `netstandard2.1` class library +(`YGOLegacy.Engine.dll`, LangVersion 9, unsafe allowed, no package and no Unity reference) that +holds the wire protocol under `Protocol/` in the namespaces `YGOLegacy.Protocol.{Contracts, +Codecs, Framing, Routing}`: the message ids and payload records, the CTOS / STOC codecs, the +frame codec and the STOC router. Unity, the tools and the server repo's card-tester consume this +DLL instead of their own copies of the sources. `binding/YGOLegacy.Engine.Tests/` (`net8.0`, +NUnit) holds the fixtures; nothing in either project touches the native library. + +```powershell +dotnet build binding\YGOLegacy.Engine -c Release -p:EngineVersion=v0.0.1 +dotnet test binding\YGOLegacy.Engine.Tests -c Release +(Get-Item binding\YGOLegacy.Engine\bin\Release\netstandard2.1\YGOLegacy.Engine.dll).VersionInfo.ProductVersion +``` + +`EngineVersion` is stamped into the assembly's informational version (`local` when not given), so +`ProductVersion` prints the tag the DLL was built for. The release workflow's `windows` job builds +and tests the binding after the native gates and ships `ygol-engine-binding.zip` +(`YGOLegacy.Engine.dll`, `YGOLegacy.Engine.pdb`); `engine.json`'s `binding` field names the same tag. +The binding is built on Windows only (the Linux and Android jobs run in Docker without dotnet); it +needs the dotnet 8 SDK, and the test project restores NUnit from nuget.org. + ## Release `.gitea/workflows/release.yml`. Every push and pull request runs the three builds and their gates @@ -137,12 +162,13 @@ git tag vX.Y.Z && git push gitea main vX.Y.Z ``` Then wait for the run (`Actions` tab). The release named after the tag appears only when every -build passed its gate, every platform's `engine.json` names the tag and agrees on protocol and -capabilities, and `ygol_engine_version()` on the Windows DLL returns the tag. A tag whose release +build passed its gate, the binding built and its tests passed, every platform's `engine.json` names +the tag (as `version` and `binding`) and agrees on protocol and capabilities, and +`ygol_engine_version()` on the Windows DLL returns the tag. A tag whose release already exists is refused: a bad release gets a new patch tag, never a re-upload. The Windows runner needs premake 5.0.0-beta8 at `C:\premake\premake5.exe`, VS 2022 Build Tools with -the C++ workload, Python 3 and `tar.exe` (Windows 10+); its checkout is +the C++ workload, Python 3, the dotnet 8 SDK (the binding) and `tar.exe` (Windows 10+); its checkout is `C:\gitea-runner\checkout\yugioh-legacy-engine` (no spaces) and the Windows bundle is staged under `C:\gitea-runner\release-out\ygol-engine\\` for the last job to attach. The release token is the run's own `GITHUB_TOKEN`. @@ -154,10 +180,11 @@ the run's own `GITHUB_TOKEN`. | Asset | Contents | |---|---| | `ygol-engine-win64.zip` | `ygol-engine.dll`, `ygol-engine.pdb`, `engine.json` | +| `ygol-engine-binding.zip` | `YGOLegacy.Engine.dll`, `YGOLegacy.Engine.pdb` (the C# binding; its `ProductVersion` is the tag) | | `ygol-engine-linux-x64.tar.gz` | `libygol-engine.so`, `engine.json` | | `ygoserver-linux-x64.tar.gz` | `ygoserver` (the plain server executable), `engine.json` | | `ygol-engine-android-arm64.tar.gz` | `libygol-engine.so`, `engine.json` | -| `engine.json` | `{ version, exports, protocol, capabilities }`; a copy of the Linux bundle's. `version`, `protocol` and `capabilities` are identical in every bundle (the release job checks); `exports` is each platform's own count (334 / 855 / 849) | +| `engine.json` | `{ version, exports, protocol, capabilities, binding }`; a copy of the Linux bundle's. `version`, `protocol`, `capabilities` and `binding` are identical in every bundle (the release job checks); `exports` is each platform's own count (334 / 855 / 849) | ## Line endings diff --git a/binding/YGOLegacy.Engine.Tests/CtosCodecTests.cs b/binding/YGOLegacy.Engine.Tests/CtosCodecTests.cs new file mode 100644 index 0000000..57ee783 --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/CtosCodecTests.cs @@ -0,0 +1,252 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using NUnit.Framework; +using YGOLegacy.Protocol.Codecs; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Tests +{ + public class CtosCodecTests + { + private static byte[] Bytes(Action write) + { + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + write(writer); + writer.Flush(); + return stream.ToArray(); + } + } + + private static BinaryReader Reader(byte[] bytes) + { + return new BinaryReader(new MemoryStream(bytes)); + } + + private static byte[] Utf16(string text) + { + return Encoding.Unicode.GetBytes(text); + } + + private static byte[] Concat(params byte[][] parts) + { + return parts.SelectMany(p => p).ToArray(); + } + + private static byte[] Packet(CtosMessage id, Action write) + { + var writer = CtosPacket.Begin(id); + write(writer); + writer.Flush(); + return ((MemoryStream)writer.BaseStream).ToArray(); + } + + private static byte[] LegacyWindBotIntPacket(CtosMessage id, int value) + { + return Bytes(w => + { + w.Write((byte)id); + w.Write(value); + }); + } + + private static byte[] LegacyUnityChat(string text) + { + return Bytes(w => MDPro3.BinaryExtensions.WriteUnicode(w, text, text.Length + 1)); + } + + private static byte[] LegacyWindBotChat(string text) + { + return Bytes(w => YGOSharp.Network.Utils.BinaryExtensions.WriteUnicodeAutoLength(w, text, 255)); + } + + [Test] + public void Response_WritesTheEngineBytesUnchanged() + { + var answer = new byte[] { 0x02, 0x00, 0x00, 0x00 }; + var ours = Bytes(w => DuelCodecs.Response.Write(w, new Response(answer))); + var unity = Bytes(w => w.Write(answer)); + + Assert.That(ours, Is.EqualTo(answer)); + Assert.That(ours, Is.EqualTo(unity)); + Assert.That(DuelCodecs.Response.Read(Reader(ours)).Bytes, Is.EqualTo(answer)); + } + + [Test] + public void Response_WriteInt_EqualsBinaryWriterInt32() + { + var ours = Bytes(w => DuelCodecs.Response.Write(w, -1)); + var legacy = Bytes(w => w.Write(-1)); + + Assert.That(ours, Is.EqualTo(legacy)); + Assert.That(ours, Is.EqualTo(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF })); + Assert.That(Packet(DuelCodecs.Response.Id, w => DuelCodecs.Response.Write(w, 7)), Is.EqualTo(LegacyWindBotIntPacket(CtosMessage.Response, 7))); + } + + [Test] + public void Response_Packet_MatchesTheOldFactoryForm() + { + var answer = new byte[] { 0x01, 0x03, 0x05 }; + var ours = Packet(DuelCodecs.Response.Id, w => DuelCodecs.Response.Write(w, new Response(answer))); + + Assert.That(ours, Is.EqualTo(Concat(new byte[] { 0x01 }, answer))); + } + + [Test] + public void Response_Null_WritesNothing() + { + Assert.That(Bytes(w => DuelCodecs.Response.Write(w, default(Response))), Is.Empty); + Assert.That(Bytes(w => DuelCodecs.Response.Write(w, new Response(null))), Is.Empty); + } + + [Test] + public void HandResult_IsOneByte_OnBothClients() + { + var ours = Bytes(w => DuelCodecs.HandResult.Write(w, new HandResult(2))); + var unity = Bytes(w => w.Write((byte)2)); + var packet = Packet(DuelCodecs.HandResult.Id, w => DuelCodecs.HandResult.Write(w, new HandResult(2))); + + Assert.That(ours, Is.EqualTo(unity)); + Assert.That(packet, Is.EqualTo(new byte[] { 0x03, 0x02 })); + Assert.That(packet, Is.Not.EqualTo(LegacyWindBotIntPacket(CtosMessage.HandResult, 2))); + Assert.That(LegacyWindBotIntPacket(CtosMessage.HandResult, 2).Length, Is.EqualTo(5)); + Assert.That(DuelCodecs.HandResult.Read(Reader(ours)).Result, Is.EqualTo(2)); + } + + [Test] + public void TpResult_IsOneByte_OnBothClients() + { + var first = Packet(DuelCodecs.TpResult.Id, w => DuelCodecs.TpResult.Write(w, new TpResult(true))); + var second = Packet(DuelCodecs.TpResult.Id, w => DuelCodecs.TpResult.Write(w, new TpResult(false))); + + Assert.That(first, Is.EqualTo(new byte[] { 0x04, 0x01 })); + Assert.That(second, Is.EqualTo(new byte[] { 0x04, 0x00 })); + Assert.That(first.Skip(1), Is.EqualTo(Bytes(w => w.Write((byte)1)))); + Assert.That(first, Is.Not.EqualTo(LegacyWindBotIntPacket(CtosMessage.TpResult, 1))); + Assert.That(DuelCodecs.TpResult.Read(Reader(first.Skip(1).ToArray())).GoFirst, Is.True); + Assert.That(DuelCodecs.TpResult.Read(Reader(second.Skip(1).ToArray())).GoFirst, Is.False); + } + + [Test] + public void NoDataIds_WriteZeroBytes() + { + var codecs = new[] + { + LobbyCodecs.LeaveGame, DuelCodecs.Surrender, DuelCodecs.TimeConfirm, + LobbyCodecs.HsToDuelist, LobbyCodecs.HsToObserver, LobbyCodecs.HsReady, + LobbyCodecs.HsNotReady, LobbyCodecs.HsStart, + }; + var expected = new[] + { + CtosMessage.LeaveGame, CtosMessage.Surrender, CtosMessage.TimeConfirm, + CtosMessage.HsToDuelist, CtosMessage.HsToObserver, CtosMessage.HsReady, + CtosMessage.HsNotReady, CtosMessage.HsStart, + }; + + for (var i = 0; i < codecs.Length; i++) + { + Assert.That(codecs[i].Id, Is.EqualTo(expected[i])); + Assert.That(Bytes(w => codecs[i].Write(w)), Is.Empty, expected[i].ToString()); + Assert.That(Bytes(w => codecs[i].Write(w, default(NoPayload))), Is.Empty, expected[i].ToString()); + Assert.That(Packet(codecs[i].Id, w => codecs[i].Write(w)), Is.EqualTo(new[] { (byte)expected[i] })); + } + } + + [Test] + public void Kick_IsOneByte() + { + var ours = Bytes(w => LobbyCodecs.HsKick.Write(w, new Kick(1))); + var packet = Packet(LobbyCodecs.HsKick.Id, w => LobbyCodecs.HsKick.Write(w, new Kick(1))); + + Assert.That(ours, Is.EqualTo(Bytes(w => w.Write((byte)1)))); + Assert.That(packet, Is.EqualTo(new byte[] { 0x24, 0x01 })); + Assert.That(LobbyCodecs.HsKick.Read(Reader(ours)).Position, Is.EqualTo(1)); + } + + [Test] + public void Chat_ShortText_MatchesBothClientsExactly() + { + const string text = "gg wp"; + var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text))); + + Assert.That(ours, Is.EqualTo(Utf16(text + "\0"))); + Assert.That(ours, Is.EqualTo(LegacyUnityChat(text))); + Assert.That(ours, Is.EqualTo(LegacyWindBotChat(text))); + Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text)); + } + + [Test] + public void Chat_Empty_WritesTheTerminatorOnly() + { + Assert.That(Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(""))), Is.EqualTo(new byte[] { 0, 0 })); + Assert.That(Bytes(w => LobbyCodecs.Chat.Write(w, default(Chat))), Is.EqualTo(new byte[] { 0, 0 })); + } + + [Test] + public void Chat_300Chars_ClipsTo255UnitsPlusTerminator() + { + var text = new string('x', 300); + var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text))); + + Assert.That(ours.Length, Is.EqualTo(512)); + Assert.That(ours.Skip(510), Is.All.EqualTo(0)); + Assert.That(ours.Take(510), Is.EqualTo(Utf16(text.Substring(0, 255)))); + Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text.Substring(0, 255))); + Assert.That(LegacyUnityChat(text).Length, Is.EqualTo(602)); + } + + [Test] + public void Chat_255Chars_KeepsAll_WhereWindBotKept254() + { + var text = new string('y', 255); + var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text))); + + Assert.That(ours.Length, Is.EqualTo(512)); + Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text)); + Assert.That(ours, Is.EqualTo(LegacyUnityChat(text))); + } + + [Test] + public void Chat_SurrogatePairAtTheCap_IsNotSplit() + { + var text = new string('a', 254) + "\U0001F600"; + var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text))); + + Assert.That(text.Length, Is.EqualTo(256)); + Assert.That(ours.Length, Is.EqualTo(510)); + Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(new string('a', 254))); + } + + [Test] + public void Chat_SurrogatePairThatFits_RoundTrips() + { + var text = new string('a', 253) + "\U0001F600"; + var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text))); + + Assert.That(ours.Length, Is.EqualTo(512)); + Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text)); + } + + [Test] + public void CodecIds_MatchTheCatalog() + { + Assert.That((int)DuelCodecs.Response.Id, Is.EqualTo(0x01)); + Assert.That((int)DuelCodecs.HandResult.Id, Is.EqualTo(0x03)); + Assert.That((int)DuelCodecs.TpResult.Id, Is.EqualTo(0x04)); + Assert.That((int)LobbyCodecs.LeaveGame.Id, Is.EqualTo(0x13)); + Assert.That((int)DuelCodecs.Surrender.Id, Is.EqualTo(0x14)); + Assert.That((int)DuelCodecs.TimeConfirm.Id, Is.EqualTo(0x15)); + Assert.That((int)LobbyCodecs.Chat.Id, Is.EqualTo(0x16)); + Assert.That((int)LobbyCodecs.HsToDuelist.Id, Is.EqualTo(0x20)); + Assert.That((int)LobbyCodecs.HsToObserver.Id, Is.EqualTo(0x21)); + Assert.That((int)LobbyCodecs.HsReady.Id, Is.EqualTo(0x22)); + Assert.That((int)LobbyCodecs.HsNotReady.Id, Is.EqualTo(0x23)); + Assert.That((int)LobbyCodecs.HsKick.Id, Is.EqualTo(0x24)); + Assert.That((int)LobbyCodecs.HsStart.Id, Is.EqualTo(0x25)); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/FeatureCodecTests.cs b/binding/YGOLegacy.Engine.Tests/FeatureCodecTests.cs new file mode 100644 index 0000000..a234921 --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/FeatureCodecTests.cs @@ -0,0 +1,523 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using NUnit.Framework; +using YGOLegacy.Protocol.Codecs; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Tests +{ + public class FeatureCodecTests + { + private static byte[] Bytes(Action write) + { + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + write(writer); + writer.Flush(); + return stream.ToArray(); + } + } + + private static BinaryReader Reader(byte[] bytes) + { + return new BinaryReader(new MemoryStream(bytes)); + } + + private static byte[] Utf16(string text) + { + return Encoding.Unicode.GetBytes(text); + } + + private static byte[] Utf16Fixed(string text, int chars) + { + return Concat(Utf16(text), Zeros(chars * 2 - text.Length * 2)); + } + + private static byte[] Concat(params byte[][] parts) + { + return parts.SelectMany(p => p).ToArray(); + } + + private static byte[] Le16(int value) + { + return new[] { (byte)value, (byte)(value >> 8) }; + } + + private static byte[] Le32(int value) + { + return new[] { (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24) }; + } + + private static byte[] Zeros(int count) + { + return new byte[count]; + } + + // The probe's reference bytes: appearance_bytes(1), dialogue_bytes(4), capability_bytes(). + private static readonly int[] ProbeItems = { 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017 }; + + private static byte[] ProbeAppearance() + { + return Concat( + Concat(ProbeItems.Select(Le32).ToArray()), + Utf16Fixed("deck-1", 48), + Utf16Fixed("character-1", 64), + Utf16Fixed("group-1", 48)); + } + + private static byte[] ProbeDialogue() + { + return Concat( + new byte[] { 1, 1 }, + Le16(4), + Le32(4004), + Le32(5004), + Utf16Fixed("corpus-4", 48), + Utf16Fixed("event-4", 48)); + } + + [Test] + public void Ids_MatchTheCatalog_InTheForkBlock() + { + Assert.That((int)LobbyCodecs.Capability.Id, Is.EqualTo(0x40)); + Assert.That((int)LobbyCodecs.Appearance.Id, Is.EqualTo(0x41)); + Assert.That((int)LobbyCodecs.Dialogue.Id, Is.EqualTo(0x42)); + Assert.That(StocCodecs.Capability.Id, Is.EqualTo(StocMessage.Capability)); + Assert.That(StocCodecs.Appearance.Id, Is.EqualTo(StocMessage.Appearance)); + Assert.That(StocCodecs.Dialogue.Id, Is.EqualTo(StocMessage.Dialogue)); + Assert.That((int)StocMessage.Capability, Is.EqualTo(0x40)); + Assert.That((int)StocMessage.Appearance, Is.EqualTo(0x41)); + Assert.That((int)StocMessage.Dialogue, Is.EqualTo(0x42)); + Assert.That(StocCodecs.SetupPairs.Id, Is.EqualTo(StocMessage.SetupPairs)); + Assert.That((int)StocMessage.SetupPairs, Is.EqualTo(0x43)); + Assert.That((int)LobbyCodecs.SeatPlan.Id, Is.EqualTo(0x50)); + Assert.That((int)LobbyCodecs.SeatRequest.Id, Is.EqualTo(0x51)); + Assert.That((int)LobbyCodecs.SeatSwap.Id, Is.EqualTo(0x52)); + Assert.That((int)LobbyCodecs.SeatMove.Id, Is.EqualTo(0x53)); + Assert.That((int)StocCodecs.SeatPlan.Id, Is.EqualTo(0x50)); + } + + [Test] + public void SeatPlan_Ctos_Is91Bytes_AndRoundTripsTokens() + { + var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + var plan = new SeatPlan(null, 0, 7, 4, new[] { SeatPlanKind.Open, SeatPlanKind.Cpu, SeatPlanKind.Open, SeatPlanKind.Cpu }, new[] { null, token, null, token }); + var bytes = Bytes(w => LobbyCodecs.SeatPlan.Write(w, plan)); + + Assert.That(bytes.Length, Is.EqualTo(91)); + Assert.That(bytes.Skip(20).Take(7), Is.EqualTo(Concat(Le16(7), new byte[] { 4, 0, 1, 0, 1 }))); + Assert.That(bytes.Skip(27 + 16).Take(16), Is.EqualTo(token)); + + var read = LobbyCodecs.SeatPlan.Read(Reader(bytes)); + Assert.That(read.Revision, Is.EqualTo(7)); + Assert.That(read.Kind(3), Is.EqualTo(SeatPlanKind.Cpu)); + Assert.That(read.Tokens[0], Is.EqualTo(Zeros(16))); + Assert.That(SeatIds.FromHex(SeatIds.ToHex(token)), Is.EqualTo(token)); + } + + [Test] + public void SeatPlan_Stoc_Is25Bytes_CarriesNoTokens_AndAShortReadThrows() + { + var plan = new SeatPlan(null, 9, 3, 2, new[] { SeatPlanKind.Open, SeatPlanKind.Cpu }, new[] { Zeros(16), Zeros(16) }); + var bytes = Bytes(w => StocCodecs.SeatPlan.Write(w, new Stamped(0xFF, plan))); + + Assert.That(bytes.Length, Is.EqualTo(25)); + Assert.That(bytes.Skip(18), Is.EqualTo(Concat(Le16(3), new byte[] { 2, 0, 1, 0, 0 }))); + var read = StocCodecs.SeatPlan.Read(Reader(bytes)); + Assert.That(read.Seat, Is.EqualTo(Capability.ServerSender)); + Assert.That(read.Payload.Kind(1), Is.EqualTo(SeatPlanKind.Cpu)); + Assert.That(read.Payload.Kind(3), Is.EqualTo(SeatPlanKind.Open)); + Assert.Throws(() => StocCodecs.SeatPlan.Read(Reader(bytes.Take(24).ToArray()))); + } + + [Test] + public void SeatRequest_SwapAndMove_HaveTheirPinnedSizes() + { + Assert.That(Bytes(w => LobbyCodecs.SeatRequest.Write(w, new SeatRequest(2, null, 3, null))).Length, Is.EqualTo(35)); + Assert.That(Bytes(w => LobbyCodecs.SeatSwap.Write(w, new SeatSwap(0, 3))), Is.EqualTo(new byte[] { 0, 3 })); + Assert.That(Bytes(w => LobbyCodecs.SeatMove.Write(w, new SeatMove(1, SeatMove.Watchers))), Is.EqualTo(new byte[] { 1, 0xFF })); + var request = LobbyCodecs.SeatRequest.Read(Reader(Bytes(w => LobbyCodecs.SeatRequest.Write(w, new SeatRequest(2, null, 3, Enumerable.Repeat((byte)9, 16).ToArray()))))); + Assert.That(request.Seat, Is.EqualTo(3)); + Assert.That(request.Token[15], Is.EqualTo(9)); + } + + [Test] + public void Restart_Ids_AndCtosSizes_ArePinned_101_17_17_18_32() + { + Assert.That((int)LobbyCodecs.RestartPrepare.Id, Is.EqualTo(0x54)); + Assert.That((int)LobbyCodecs.RestartAck.Id, Is.EqualTo(0x55)); + Assert.That((int)LobbyCodecs.RestartControl.Id, Is.EqualTo(0x56)); + Assert.That((int)LobbyCodecs.SeatResume.Id, Is.EqualTo(0x57)); + Assert.That((int)LobbyCodecs.RestartOpen.Id, Is.EqualTo(0x58)); + Assert.That((int)StocCodecs.RoomRestarting.Id, Is.EqualTo(0x54)); + Assert.That((int)StocCodecs.RestartStatus.Id, Is.EqualTo(0x56)); + Assert.That((int)StocCodecs.SeatResumeResult.Id, Is.EqualTo(0x57)); + Assert.That((int)StocCodecs.RestartOpened.Id, Is.EqualTo(0x58)); + Assert.That(FeatureFlags.RulesRestart, Is.EqualTo(0x10)); + Assert.That(FeatureFlags.All, Is.EqualTo(0x7FB)); + + var id = Enumerable.Repeat((byte)0xAB, 16).ToArray(); + var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + var prepare = Bytes(w => LobbyCodecs.RestartPrepare.Write(w, new RestartPrepare(id, 30000, 2, new[] { token, null }, token))); + Assert.That(prepare.Length, Is.EqualTo(101)); + Assert.That(prepare, Is.EqualTo(Concat(id, Le32(30000), new byte[] { 2 }, token, Zeros(48), token))); + Assert.That(Bytes(w => LobbyCodecs.RestartAck.Write(w, new RestartAck(id, RestartPhase.Commit))), Is.EqualTo(Concat(id, new byte[] { 2 }))); + Assert.That(Bytes(w => LobbyCodecs.RestartControl.Write(w, new RestartControl(id, RestartPhase.Abort))), Is.EqualTo(Concat(id, new byte[] { 3 }))); + Assert.That(Bytes(w => LobbyCodecs.SeatResume.Write(w, new SeatResume(id, SeatResumeAction.Release, 7))), Is.EqualTo(Concat(id, new byte[] { 2, 7 }))); + Assert.That(Bytes(w => LobbyCodecs.RestartOpen.Write(w, new RestartOpen(id, token))), Is.EqualTo(Concat(id, token))); + var read = LobbyCodecs.RestartPrepare.Read(Reader(prepare)); + Assert.That(read.SeatTokens[0], Is.EqualTo(token)); + Assert.That(read.SeatTokens[1], Is.EqualTo(Zeros(16))); + Assert.That(read.ObserverToken, Is.EqualTo(token)); + } + + [Test] + public void MatchOver_Id_Flag_AndSize_ArePinned_0x5A_0x40_8() + { + Assert.That((int)StocCodecs.MatchOver.Id, Is.EqualTo(0x5A)); + Assert.That(FeatureFlags.LobbyAfterMatch, Is.EqualTo(0x40)); + var over = Bytes(w => StocCodecs.MatchOver.Write(w, new Stamped(0xFF, new MatchOver(4, new[] { false, true, true, true })))); + Assert.That(over, Is.EqualTo(Concat(Le16(0xFF), new byte[] { 1, 4, 0, 1, 1, 1 }))); + var read = StocCodecs.MatchOver.Read(Reader(over)); + Assert.That(read.Seat, Is.EqualTo(0xFF)); + Assert.That(read.Payload.Version, Is.EqualTo(1)); + Assert.That(read.Payload.SeatCount, Is.EqualTo(4)); + Assert.That(new[] { read.Payload.Occupied(0), read.Payload.Occupied(1), read.Payload.Occupied(2), read.Payload.Occupied(3) }, Is.EqualTo(new[] { false, true, true, true })); + Assert.Throws(() => StocCodecs.MatchOver.Read(Reader(over.Take(7).ToArray()))); + } + + [Test] + public void CoinToss_Id_Flag_Protocol_AndSize_ArePinned_0x5B_0x80_5_4() + { + Assert.That((int)StocCodecs.CoinToss.Id, Is.EqualTo(0x5B)); + Assert.That(FeatureFlags.CoinToss, Is.EqualTo(0x80)); + var toss = Bytes(w => StocCodecs.CoinToss.Write(w, new CoinTossAnnounce(2, CoinTossAnnounce.Tails, 30))); + Assert.That(toss, Is.EqualTo(new byte[] { 1, 2, 1, 30 })); + var read = StocCodecs.CoinToss.Read(Reader(toss)); + Assert.That(read.Version, Is.EqualTo(1)); + Assert.That(read.ChooserSeat, Is.EqualTo(2)); + Assert.That(read.Face, Is.EqualTo(CoinTossAnnounce.Tails)); + Assert.That(read.ChooseSeconds, Is.EqualTo(30)); + Assert.That(StocCodecs.CoinToss.Read(Reader(new byte[] { 1, 0, 0xFF, 15 })).Tossed, Is.False); + Assert.Throws(() => StocCodecs.CoinToss.Read(Reader(toss.Take(3).ToArray()))); + } + + [Test] + public void Profile_Id_Flag_Protocol_AndSizes_ArePinned_0x5D_0x200_7_98_100() + { + Assert.That((int)LobbyCodecs.Profile.Id, Is.EqualTo(0x5D)); + Assert.That((int)StocCodecs.Profile.Id, Is.EqualTo(0x5D)); + Assert.That(FeatureFlags.Profile, Is.EqualTo(0x200)); + Assert.That(FeatureFlags.All & FeatureFlags.Profile, Is.EqualTo(FeatureFlags.Profile)); + Assert.That(Capability.ProtocolVersion, Is.EqualTo(8)); + Assert.That(ProfileCodec.Size, Is.EqualTo(98)); + Assert.That(ProfileCodec.StampedSize, Is.EqualTo(100)); + var sent = Bytes(w => LobbyCodecs.Profile.Write(w, new ProfileState("atem", "gold"))); + Assert.That(sent.Length, Is.EqualTo(98)); + Assert.That(sent.Take(2), Is.EqualTo(new byte[] { 1, 0 })); + Assert.That(sent.Skip(2).Take(8), Is.EqualTo(new byte[] { (byte)'a', 0, (byte)'t', 0, (byte)'e', 0, (byte)'m', 0 })); + Assert.That(sent.Skip(10).Take(56), Is.EqualTo(Zeros(56))); + Assert.That(sent.Skip(66).Take(8), Is.EqualTo(new byte[] { (byte)'g', 0, (byte)'o', 0, (byte)'l', 0, (byte)'d', 0 })); + var stamped = Bytes(w => StocCodecs.Profile.Write(w, new Stamped(3, new ProfileState("mai-ori", string.Empty)))); + Assert.That(stamped.Length, Is.EqualTo(100)); + Assert.That(stamped.Take(2), Is.EqualTo(Le16(3))); + var read = StocCodecs.Profile.Read(Reader(stamped)); + Assert.That(read.Seat, Is.EqualTo(3)); + Assert.That(read.Payload.Version, Is.EqualTo(1)); + Assert.That(read.Payload.AvatarId, Is.EqualTo("mai-ori")); + Assert.That(read.Payload.FrameId, Is.EqualTo(string.Empty)); + var longId = Bytes(w => LobbyCodecs.Profile.Write(w, new ProfileState(new string('x', 40), new string('y', 20)))); + Assert.That(longId.Length, Is.EqualTo(98)); + var clipped = LobbyCodecs.Profile.Read(Reader(longId)); + Assert.That(clipped.AvatarId.Length, Is.EqualTo(31)); + Assert.That(clipped.FrameId.Length, Is.EqualTo(15)); + Assert.Throws(() => StocCodecs.Profile.Read(Reader(stamped.Take(99).ToArray()))); + } + + [Test] + public void AttackPreview_Id_Flag_Protocol_AndSizes_ArePinned_0x5E_0x400_8_4_28() + { + Assert.That((int)LobbyCodecs.AttackPreview.Id, Is.EqualTo(0x5E)); + Assert.That((int)StocCodecs.AttackPreview.Id, Is.EqualTo(0x5E)); + Assert.That(FeatureFlags.AttackPreview, Is.EqualTo(0x400)); + Assert.That(FeatureFlags.All & FeatureFlags.AttackPreview, Is.EqualTo(FeatureFlags.AttackPreview)); + Assert.That(Capability.ProtocolVersion, Is.EqualTo(8)); + Assert.That(AttackPreviewPair.Size, Is.EqualTo(4)); + Assert.That(AttackPreviewEntry.Size, Is.EqualTo(28)); + + var query = new AttackPreviewQuery(new[] { new AttackPreviewPair(0x04, 2, 0x04, 1), AttackPreviewPair.Direct(0x04, 2) }); + var asked = Bytes(w => LobbyCodecs.AttackPreview.Write(w, query)); + Assert.That(asked, Is.EqualTo(new byte[] { 1, 2, 0x04, 2, 0x04, 1, 0x04, 2, 0xFF, 0 })); + var readQuery = LobbyCodecs.AttackPreview.Read(Reader(asked)); + Assert.That(readQuery.Version, Is.EqualTo(1)); + Assert.That(readQuery.Pairs.Length, Is.EqualTo(2)); + Assert.That(readQuery.Pairs[1].IsDirect, Is.True); + Assert.That(readQuery.Pairs[0].TargetSequence, Is.EqualTo(1)); + Assert.That(Bytes(w => LobbyCodecs.AttackPreview.Write(w, new AttackPreviewQuery(null))), Is.EqualTo(new byte[] { 1, 0 })); + + var answer = Enumerable.Range(0, 24).Select(i => (byte)(100 + i)).ToArray(); + var result = new AttackPreviewResult(new[] { new AttackPreviewEntry(query.Pairs[0], answer) }); + var answered = Bytes(w => StocCodecs.AttackPreview.Write(w, result)); + Assert.That(answered.Length, Is.EqualTo(2 + 28)); + Assert.That(answered, Is.EqualTo(Concat(new byte[] { 1, 1, 0x04, 2, 0x04, 1 }, answer))); + var readResult = StocCodecs.AttackPreview.Read(Reader(answered)); + Assert.That(readResult.Version, Is.EqualTo(1)); + Assert.That(readResult.Entries.Length, Is.EqualTo(1)); + Assert.That(readResult.Entries[0].Pair.AttackerSequence, Is.EqualTo(2)); + Assert.That(readResult.Entries[0].Answer, Is.EqualTo(answer)); + Assert.That(StocCodecs.AttackPreview.Read(Reader(new byte[] { 1, 0 })).Entries, Is.Empty); + Assert.Throws(() => StocCodecs.AttackPreview.Read(Reader(answered.Take(29).ToArray()))); + Assert.Throws(() => StocCodecs.AttackPreview.Read(Reader(new byte[] { 1 }))); + } + + [Test] + public void SeatState_Id_Flag_AndSizes_ArePinned_0x59_0x20_4_6() + { + Assert.That((int)LobbyCodecs.SeatState.Id, Is.EqualTo(0x59)); + Assert.That((int)StocCodecs.SeatState.Id, Is.EqualTo(0x59)); + Assert.That(FeatureFlags.SeatState, Is.EqualTo(0x20)); + var picking = Bytes(w => LobbyCodecs.SeatState.Write(w, new SeatState(SeatStateKind.PickingDeck))); + Assert.That(picking, Is.EqualTo(new byte[] { 1, 1, 0, 0 })); + var none = Bytes(w => LobbyCodecs.SeatState.Write(w, new SeatState(SeatStateKind.None))); + Assert.That(none, Is.EqualTo(new byte[] { 1, 0, 0, 0 })); + var stamped = Bytes(w => StocCodecs.SeatState.Write(w, new Stamped(2, new SeatState(SeatStateKind.PickingDeck, 7)))); + Assert.That(stamped, Is.EqualTo(Concat(Le16(2), new byte[] { 1, 1 }, Le16(7)))); + var read = StocCodecs.SeatState.Read(Reader(stamped)); + Assert.That(read.Seat, Is.EqualTo(2)); + Assert.That(read.Payload.Kind, Is.EqualTo(SeatStateKind.PickingDeck)); + Assert.That(read.Payload.Value, Is.EqualTo(7)); + Assert.Throws(() => StocCodecs.SeatState.Read(Reader(stamped.Take(5).ToArray()))); + } + + [Test] + public void Restart_StocSizes_ArePinned_40_23_21_19_AndShortReadsThrow() + { + var id = Enumerable.Repeat((byte)0xAB, 16).ToArray(); + var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + var restarting = Bytes(w => StocCodecs.RoomRestarting.Write(w, new Stamped(0xFF, new RoomRestarting(RestartPhase.Prepare, id, 0xFF, token, 30000)))); + Assert.That(restarting.Length, Is.EqualTo(40)); + Assert.That(restarting, Is.EqualTo(Concat(Le16(0xFF), new byte[] { 1 }, id, new byte[] { 0xFF }, token, Le32(30000)))); + var readRestarting = StocCodecs.RoomRestarting.Read(Reader(restarting)); + Assert.That(readRestarting.Payload.Phase, Is.EqualTo(RestartPhase.Prepare)); + Assert.That(readRestarting.Payload.Seat, Is.EqualTo(SeatRequest.Observer)); + Assert.That(readRestarting.Payload.Token, Is.EqualTo(token)); + Assert.Throws(() => StocCodecs.RoomRestarting.Read(Reader(restarting.Take(39).ToArray()))); + + var status = Bytes(w => StocCodecs.RestartStatus.Write(w, new Stamped(0xFF, new RestartStatus(RestartPhase.Commit, id, 2, 3, false, RestartReason.AckTimeout)))); + Assert.That(status.Length, Is.EqualTo(23)); + Assert.That(status, Is.EqualTo(Concat(Le16(0xFF), new byte[] { 2 }, id, new byte[] { 2, 3, 0, 2 }))); + Assert.That(StocCodecs.RestartStatus.Read(Reader(status)).Payload.Reason, Is.EqualTo(RestartReason.AckTimeout)); + + var result = Bytes(w => StocCodecs.SeatResumeResult.Write(w, new Stamped(0xFF, new SeatResumeResult(id, true, 1, 0)))); + Assert.That(result.Length, Is.EqualTo(21)); + Assert.That(result, Is.EqualTo(Concat(Le16(0xFF), id, new byte[] { 1, 1, 0 }))); + Assert.That(StocCodecs.SeatResumeResult.Read(Reader(result)).Payload.Accepted, Is.True); + + var opened = Bytes(w => StocCodecs.RestartOpened.Write(w, new Stamped(0xFF, new RestartOpened(id, true)))); + Assert.That(opened.Length, Is.EqualTo(19)); + Assert.That(opened, Is.EqualTo(Concat(Le16(0xFF), id, new byte[] { 1 }))); + Assert.Throws(() => StocCodecs.RestartOpened.Read(Reader(opened.Take(18).ToArray()))); + Assert.That(SeatIds.Same(id, SeatIds.Fixed(id)), Is.True); + Assert.That(SeatIds.IsZero(Zeros(16)), Is.True); + } + + [Test] + public void SetupPairs_GoldenBytes_MatchPatch0009_AndRoundTrip() + { + var tokens = new[] { "ygol.ruleset=rush", "ygol.scripts=a.lua,b%20c.lua" }; + var golden = Concat(Le16(0xFF), Le16(2), + Le16(tokens[0].Length), Encoding.ASCII.GetBytes(tokens[0]), + Le16(tokens[1].Length), Encoding.ASCII.GetBytes(tokens[1])); + var pairs = tokens.Select(SetupPair.FromToken).ToList(); + + Assert.That(Bytes(w => StocCodecs.SetupPairs.Write(w, new Stamped>(0xFF, pairs))), Is.EqualTo(golden)); + var read = StocCodecs.SetupPairs.Read(Reader(golden)); + Assert.That(read.Seat, Is.EqualTo(Capability.ServerSender)); + Assert.That(read.Payload.Select(p => p.Key), Is.EqualTo(new[] { "ygol.ruleset", "ygol.scripts" })); + Assert.That(read.Payload.Select(p => p.Value), Is.EqualTo(new[] { "rush", "a.lua,b%20c.lua" })); + Assert.That(SetupPair.FromToken("ygol.x=a=b").Value, Is.EqualTo("a=b")); + } + + [Test] + public void SetupPairs_EmptyBlock_IsFourBytes_AndATruncatedTokenThrows() + { + var empty = Bytes(w => StocCodecs.SetupPairs.Write(w, new Stamped>(0xFF, new SetupPair[0]))); + Assert.That(empty, Is.EqualTo(new byte[] { 0xFF, 0, 0, 0 })); + Assert.That(StocCodecs.SetupPairs.Read(Reader(empty)).Payload, Is.Empty); + var truncated = Concat(Le16(0xFF), Le16(1), Le16(10), Encoding.ASCII.GetBytes("ygol.a")); + Assert.Throws(() => StocCodecs.SetupPairs.Read(Reader(truncated))); + } + + [Test] + public void SetupPairs_ReplayBlock_IsLengthPrefixed_AndLeavesTheNamesNext() + { + var pairs = new[] { SetupPair.FromToken("ygol.ruleset=rush") }; + var bytes = Bytes(w => + { + SetupPairsCodec.WriteReplayBlock(w, pairs); + w.Write(Utf16Fixed("Alice", 20)); + }); + Assert.That(bytes.Take(4), Is.EqualTo(Le32(2 + 2 + 17))); + using var reader = Reader(bytes); + Assert.That(SetupPairsCodec.ReadReplayBlock(reader).Single().Token, Is.EqualTo("ygol.ruleset=rush")); + Assert.That(Encoding.Unicode.GetString(reader.ReadBytes(10)), Is.EqualTo("Alice")); + } + + [Test] + public void Sizes_ArePinned_6_8_352_354_204_206() + { + Assert.That(CapabilityCodec.Size, Is.EqualTo(6)); + Assert.That(CapabilityCodec.StampedSize, Is.EqualTo(8)); + Assert.That(AppearanceCodec.Size, Is.EqualTo(352)); + Assert.That(AppearanceCodec.StampedSize, Is.EqualTo(354)); + Assert.That(DialogueCodec.Size, Is.EqualTo(204)); + Assert.That(DialogueCodec.StampedSize, Is.EqualTo(206)); + Assert.That(StocCodecs.Capability.Size, Is.EqualTo(8)); + Assert.That(StocCodecs.Appearance.Size, Is.EqualTo(354)); + Assert.That(StocCodecs.Dialogue.Size, Is.EqualTo(206)); + } + + [Test] + public void Capability_GoldenBytes_MatchTheProbe_AndRoundTrip() + { + var bytes = Bytes(w => LobbyCodecs.Capability.Write(w, new Capability(Capability.ProtocolVersion, FeatureFlags.All))); + + Assert.That(bytes, Is.EqualTo(Concat(Le16(8), Le32(0x7FB)))); + + var read = LobbyCodecs.Capability.Read(Reader(bytes)); + Assert.That(read.Protocol, Is.EqualTo(Capability.ProtocolVersion)); + Assert.That(read.Flags, Is.EqualTo(FeatureFlags.All)); + Assert.That(read.Has(FeatureFlags.Appearance), Is.True); + Assert.That(read.Has(FeatureFlags.Dialogue), Is.True); + + var appearanceOnly = LobbyCodecs.Capability.Read(Reader(Concat(Le16(1), Le32(1)))); + Assert.That(appearanceOnly.Has(FeatureFlags.Appearance), Is.True); + Assert.That(appearanceOnly.Has(FeatureFlags.Dialogue), Is.False); + } + + [Test] + public void Capability_TheServersOwnLine_ReadsAsSeat0xFF() + { + var bytes = Concat(Le16(0xFF), Le16(1), Le32(3)); + + var read = StocCodecs.Capability.Read(Reader(bytes)); + + Assert.That(bytes.Length, Is.EqualTo(8)); + Assert.That(read.Seat, Is.EqualTo(Capability.ServerSender)); + Assert.That(read.Payload.Protocol, Is.EqualTo(1)); + Assert.That(read.Payload.Flags, Is.EqualTo(3)); + + var seated = StocCodecs.Capability.Read(Reader(Bytes(w => + StocCodecs.Capability.Write(w, new Stamped(2, new Capability(1, 1)))))); + Assert.That(seated.Seat, Is.EqualTo(2)); + Assert.That(seated.Payload.Flags, Is.EqualTo(1)); + + Assert.Throws(() => StocCodecs.Capability.Read(Reader(Concat(Le16(0xFF), Le16(1))))); + } + + [Test] + public void Appearance_GoldenBytes_MatchTheProbe_AndRoundTrip() + { + var state = new AppearanceState(ProbeItems, "deck-1", "character-1", "group-1"); + var bytes = Bytes(w => LobbyCodecs.Appearance.Write(w, state)); + + Assert.That(bytes.Length, Is.EqualTo(352)); + Assert.That(bytes, Is.EqualTo(ProbeAppearance())); + + var read = LobbyCodecs.Appearance.Read(Reader(bytes)); + Assert.That(read.Items, Is.EqualTo(ProbeItems)); + Assert.That(read.DeckName, Is.EqualTo("deck-1")); + Assert.That(read.CharacterId, Is.EqualTo("character-1")); + Assert.That(read.DeckGroup, Is.EqualTo("group-1")); + } + + [Test] + public void Appearance_Stamped_Is354Bytes_AndA353ByteReadThrows() + { + var bytes = Bytes(w => StocCodecs.Appearance.Write(w, + new Stamped(1, new AppearanceState(ProbeItems, "deck-1", "character-1", "group-1")))); + + Assert.That(bytes.Length, Is.EqualTo(354)); + Assert.That(bytes, Is.EqualTo(Concat(Le16(1), ProbeAppearance()))); + + var read = StocCodecs.Appearance.Read(Reader(bytes)); + Assert.That(read.Seat, Is.EqualTo(1)); + Assert.That(read.Payload.DeckName, Is.EqualTo("deck-1")); + Assert.That(read.Payload.Items[7], Is.EqualTo(1017)); + + var short353 = bytes.Take(353).ToArray(); + Assert.Throws(() => StocCodecs.Appearance.Read(Reader(short353))); + } + + [Test] + public void Appearance_A49CharDeckName_ClipsTo47PlusTerminator() + { + var name = new string('x', 49); + var bytes = Bytes(w => LobbyCodecs.Appearance.Write(w, new AppearanceState(ProbeItems, name, "", ""))); + + Assert.That(bytes.Length, Is.EqualTo(352)); + var nameSlot = bytes.Skip(32).Take(96).ToArray(); + Assert.That(nameSlot, Is.EqualTo(Concat(Utf16(new string('x', 47)), Zeros(2)))); + Assert.That(LobbyCodecs.Appearance.Read(Reader(bytes)).DeckName, Is.EqualTo(new string('x', 47))); + Assert.That(LobbyCodecs.Appearance.Read(Reader(bytes)).CharacterId, Is.EqualTo("")); + } + + [Test] + public void Appearance_NullFields_WriteZeros_AndReadEmpty() + { + var bytes = Bytes(w => LobbyCodecs.Appearance.Write(w, new AppearanceState(null, null, null, null))); + + Assert.That(bytes.Length, Is.EqualTo(352)); + Assert.That(bytes, Is.All.EqualTo(0)); + + var read = LobbyCodecs.Appearance.Read(Reader(bytes)); + Assert.That(read.Items, Is.All.EqualTo(0)); + Assert.That(read.DeckName, Is.EqualTo("")); + Assert.That(read.CharacterId, Is.EqualTo("")); + Assert.That(read.DeckGroup, Is.EqualTo("")); + } + + [Test] + public void Dialogue_GoldenBytes_MatchTheProbe_AndRoundTrip() + { + var line = new DialogueLine(1, true, 4, 4004, 5004, "corpus-4", "event-4"); + var bytes = Bytes(w => LobbyCodecs.Dialogue.Write(w, line)); + + Assert.That(bytes.Length, Is.EqualTo(204)); + Assert.That(bytes, Is.EqualTo(ProbeDialogue())); + + var read = LobbyCodecs.Dialogue.Read(Reader(bytes)); + Assert.That(read.Version, Is.EqualTo(1)); + Assert.That(read.TargetFaceDown, Is.True); + Assert.That(read.Index, Is.EqualTo(4)); + Assert.That(read.CardCode, Is.EqualTo(4004)); + Assert.That(read.TargetCode, Is.EqualTo(5004)); + Assert.That(read.CorpusKey, Is.EqualTo("corpus-4")); + Assert.That(read.EventKey, Is.EqualTo("event-4")); + } + + [Test] + public void Dialogue_Stamped_Is206Bytes_AndAHelloLineRoundTrips() + { + var hello = new DialogueLine(DialogueLine.CurrentVersion, false, -1, 0, 0, null, null); + var bytes = Bytes(w => StocCodecs.Dialogue.Write(w, new Stamped(0, hello))); + + Assert.That(bytes.Length, Is.EqualTo(206)); + Assert.That(bytes.Skip(2).Take(2), Is.EqualTo(new byte[] { 1, 0 })); + Assert.That(bytes.Skip(4).Take(2), Is.EqualTo(Le16(unchecked((short)-1)))); + + var read = StocCodecs.Dialogue.Read(Reader(bytes)); + Assert.That(read.Seat, Is.EqualTo(0)); + Assert.That(read.Payload.Index, Is.EqualTo(-1)); + Assert.That(read.Payload.TargetFaceDown, Is.False); + Assert.That(read.Payload.CorpusKey, Is.EqualTo("")); + Assert.That(read.Payload.EventKey, Is.EqualTo("")); + + Assert.Throws(() => StocCodecs.Dialogue.Read(Reader(bytes.Take(205).ToArray()))); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/FrameCodecTests.cs b/binding/YGOLegacy.Engine.Tests/FrameCodecTests.cs new file mode 100644 index 0000000..7a102de --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/FrameCodecTests.cs @@ -0,0 +1,312 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using NUnit.Framework; +using YGOLegacy.Protocol.Codecs; +using YGOLegacy.Protocol.Contracts; +using YGOLegacy.Protocol.Framing; + +namespace YGOLegacy.Protocol.Tests +{ + public class FrameCodecTests + { + private static byte[] Bytes(Action write) + { + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + write(writer); + writer.Flush(); + return stream.ToArray(); + } + } + + private static byte[] Concat(params byte[][] parts) + { + return parts.SelectMany(p => p).ToArray(); + } + + private static byte[] LegacyUnityFrame(int function, byte[] data) + { + return Bytes(b => + { + b.Write(BitConverter.GetBytes((short)(data.Length + 1)), 0, 2); + b.Write(BitConverter.GetBytes((short)function), 0, 1); + b.Write(data, 0, data.Length); + }); + } + + private static byte[] LegacyWindBotFrame(byte[] packet) + { + var header = BitConverter.GetBytes((ushort)packet.Length); + var data = new byte[packet.Length + 2]; + Array.Copy(header, 0, data, 0, header.Length); + Array.Copy(packet, 0, data, header.Length, packet.Length); + return data; + } + + private static byte[] PlayerInfoPayload() + { + return Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice"))); + } + + private static byte[] PlayerInfoPacket() + { + var packet = CtosPacket.Begin(LobbyCodecs.PlayerInfo.Id); + LobbyCodecs.PlayerInfo.Write(packet, new PlayerInfo("Alice")); + return ((MemoryStream)packet.BaseStream).ToArray(); + } + + private static byte[] Frame(byte[] packet) + { + return Bytes(w => FrameCodec.Write(w, packet)); + } + + private static List Drain(FrameExtractor extractor) + { + var taken = new List(); + byte[] packet; + while (extractor.TryTake(out packet)) + taken.Add(packet); + return taken; + } + + [Test] + public void PlayerInfo_FramedFromIdAndPayload_MatchesUnitySender() + { + var payload = PlayerInfoPayload(); + var ours = Bytes(w => FrameCodec.Write(w, (byte)LobbyCodecs.PlayerInfo.Id, payload)); + + Assert.That(ours.Length, Is.EqualTo(43)); + Assert.That(ours.Take(3), Is.EqualTo(new byte[] { 0x29, 0x00, 0x10 })); + Assert.That(ours, Is.EqualTo(LegacyUnityFrame((int)LobbyCodecs.PlayerInfo.Id, payload))); + } + + [Test] + public void PlayerInfo_FramedFromPacket_MatchesWindBotSend() + { + var packet = PlayerInfoPacket(); + var ours = Frame(packet); + + Assert.That(ours.Length, Is.EqualTo(43)); + Assert.That(ours, Is.EqualTo(LegacyWindBotFrame(packet))); + Assert.That(ours, Is.EqualTo(Bytes(w => FrameCodec.Write(w, (byte)LobbyCodecs.PlayerInfo.Id, PlayerInfoPayload())))); + } + + [Test] + public void HsReady_FramesAsThreeBytes() + { + var fromId = Bytes(w => FrameCodec.Write(w, (byte)CtosMessage.HsReady, new byte[0])); + var fromNull = Bytes(w => FrameCodec.Write(w, (byte)CtosMessage.HsReady, null)); + var fromPacket = Frame(new[] { (byte)CtosMessage.HsReady }); + + Assert.That(fromId, Is.EqualTo(new byte[] { 0x01, 0x00, 0x22 })); + Assert.That(fromNull, Is.EqualTo(fromId)); + Assert.That(fromPacket, Is.EqualTo(fromId)); + } + + [Test] + public void FortyThousandBytePayload_HeaderEqualsTheOldShortCast() + { + var payload = new byte[40000]; + var ours = Bytes(w => FrameCodec.Write(w, 0x01, payload)); + + Assert.That(ours.Take(2), Is.EqualTo(new byte[] { 0x41, 0x9C })); + Assert.That(ours.Take(2), Is.EqualTo(BitConverter.GetBytes((short)(payload.Length + 1)))); + Assert.That(FrameCodec.ReadLength(ours), Is.EqualTo(40001)); + } + + [Test] + public void Write_OverTheCeiling_Throws() + { + Assert.Throws(() => Bytes(w => FrameCodec.Write(w, 0x01, new byte[FrameCodec.MaxFrame]))); + Assert.Throws(() => Bytes(w => FrameCodec.Write(w, new byte[FrameCodec.MaxFrame + 1]))); + } + + [Test] + public void Write_EmptyPacket_Throws() + { + Assert.Throws(() => Bytes(w => FrameCodec.Write(w, new byte[0]))); + Assert.Throws(() => Bytes(w => FrameCodec.Write(w, null))); + } + + [Test] + public void MaxFramePacket_RoundTrips() + { + var packet = new byte[FrameCodec.MaxFrame]; + for (var i = 0; i < packet.Length; i++) + packet[i] = (byte)i; + var frame = Frame(packet); + var extractor = new FrameExtractor(); + extractor.Feed(frame, frame.Length); + var taken = Drain(extractor); + + Assert.That(frame.Take(2), Is.EqualTo(new byte[] { 0xFE, 0xFF })); + Assert.That(taken.Count, Is.EqualTo(1)); + Assert.That(taken[0], Is.EqualTo(packet)); + Assert.That(extractor.Faulted, Is.False); + Assert.That(extractor.Buffered, Is.EqualTo(0)); + } + + [Test] + public void Extractor_FrameSplitAtEveryByte_ComesOutWhole() + { + var packet = PlayerInfoPacket(); + var frame = Frame(packet); + for (var split = 1; split < frame.Length; split++) + { + var extractor = new FrameExtractor(); + extractor.Feed(frame, split); + Assert.That(Drain(extractor), Is.Empty, "split " + split); + extractor.Feed(frame.Skip(split).ToArray(), frame.Length - split); + var taken = Drain(extractor); + Assert.That(taken.Count, Is.EqualTo(1), "split " + split); + Assert.That(taken[0], Is.EqualTo(packet), "split " + split); + } + } + + [Test] + public void Extractor_OneByteAtATime_ComesOutWhole() + { + var packet = PlayerInfoPacket(); + var frame = Frame(packet); + var extractor = new FrameExtractor(); + var taken = new List(); + foreach (var b in frame) + { + extractor.Feed(new[] { b }, 1); + taken.AddRange(Drain(extractor)); + } + + Assert.That(taken.Count, Is.EqualTo(1)); + Assert.That(taken[0], Is.EqualTo(packet)); + } + + [Test] + public void Extractor_ThreeFramesInOneChunk_AllComeOut() + { + var a = new[] { (byte)CtosMessage.HsReady }; + var b = PlayerInfoPacket(); + var c = new byte[] { (byte)CtosMessage.HsKick, 0x01 }; + var chunk = Concat(Frame(a), Frame(b), Frame(c)); + var extractor = new FrameExtractor(); + extractor.Feed(chunk, chunk.Length); + var taken = Drain(extractor); + + Assert.That(taken.Count, Is.EqualTo(3)); + Assert.That(taken[0], Is.EqualTo(a)); + Assert.That(taken[1], Is.EqualTo(b)); + Assert.That(taken[2], Is.EqualTo(c)); + Assert.That(extractor.Buffered, Is.EqualTo(0)); + } + + [Test] + public void Extractor_HeaderSplitAcrossChunks_ComesOutWhole() + { + var packet = PlayerInfoPacket(); + var frame = Frame(packet); + var extractor = new FrameExtractor(); + extractor.Feed(frame, 1); + Assert.That(Drain(extractor), Is.Empty); + extractor.Feed(frame.Skip(1).ToArray(), frame.Length - 1); + var taken = Drain(extractor); + + Assert.That(taken.Count, Is.EqualTo(1)); + Assert.That(taken[0], Is.EqualTo(packet)); + } + + [Test] + public void Extractor_ZeroLengthFrameBetweenTwoRealOnes_IsDroppedAndCounted() + { + var a = PlayerInfoPacket(); + var c = new[] { (byte)CtosMessage.HsStart }; + var chunk = Concat(Frame(a), new byte[] { 0x00, 0x00 }, Frame(c)); + var extractor = new FrameExtractor(); + extractor.Feed(chunk, chunk.Length); + var taken = Drain(extractor); + + Assert.That(taken.Count, Is.EqualTo(2)); + Assert.That(taken[0], Is.EqualTo(a)); + Assert.That(taken[1], Is.EqualTo(c)); + Assert.That(extractor.DroppedEmpty, Is.EqualTo(1)); + Assert.That(extractor.Faulted, Is.False); + } + + [Test] + public void Extractor_LengthOverTheCeiling_FaultsAndTakesNothing() + { + var chunk = Concat(new byte[] { 0xFF, 0xFF }, new byte[100]); + var extractor = new FrameExtractor(); + extractor.Feed(chunk, chunk.Length); + byte[] packet; + + Assert.That(extractor.TryTake(out packet), Is.False); + Assert.That(packet, Is.Null); + Assert.That(extractor.Faulted, Is.True); + + extractor.Feed(Frame(PlayerInfoPacket()), 43); + Assert.That(extractor.TryTake(out packet), Is.False); + } + + [Test] + public void Extractor_RealFrameBeforeTheFault_IsStillTaken() + { + var a = PlayerInfoPacket(); + var chunk = Concat(Frame(a), new byte[] { 0xFF, 0xFF }); + var extractor = new FrameExtractor(); + extractor.Feed(chunk, chunk.Length); + var taken = Drain(extractor); + + Assert.That(taken.Count, Is.EqualTo(1)); + Assert.That(taken[0], Is.EqualTo(a)); + Assert.That(extractor.Faulted, Is.True); + } + + [Test] + public void Extractor_ManyFramesAcrossManyChunks_KeepsOrder() + { + var packets = Enumerable.Range(0, 300).Select(i => Enumerable.Range(0, 1 + i % 97).Select(j => (byte)(i + j)).ToArray()).ToList(); + var stream = Concat(packets.Select(Frame).ToArray()); + var extractor = new FrameExtractor(); + var taken = new List(); + var offset = 0; + var chunkSize = 7; + while (offset < stream.Length) + { + var n = Math.Min(chunkSize, stream.Length - offset); + extractor.Feed(stream.Skip(offset).Take(n).ToArray(), n); + taken.AddRange(Drain(extractor)); + offset += n; + chunkSize = chunkSize * 3 % 251 + 1; + } + + Assert.That(taken.Count, Is.EqualTo(packets.Count)); + for (var i = 0; i < packets.Count; i++) + Assert.That(taken[i], Is.EqualTo(packets[i]), "packet " + i); + Assert.That(extractor.Buffered, Is.EqualTo(0)); + } + + [Test] + public void Extractor_FeedCountBeyondChunk_IsClamped() + { + var frame = Frame(new[] { (byte)CtosMessage.HsReady }); + var extractor = new FrameExtractor(); + extractor.Feed(frame, 999); + var taken = Drain(extractor); + + Assert.That(taken.Count, Is.EqualTo(1)); + Assert.That(taken[0], Is.EqualTo(new[] { (byte)CtosMessage.HsReady })); + } + + [Test] + public void ReadLength_IsLittleEndian() + { + Assert.That(FrameCodec.ReadLength(new byte[] { 0x29, 0x00 }), Is.EqualTo(41)); + Assert.That(FrameCodec.ReadLength(new byte[] { 0x41, 0x9C }), Is.EqualTo(40001)); + Assert.That(FrameCodec.ReadLength(new byte[] { 0xFF, 0xFF }), Is.EqualTo(0xFFFF)); + Assert.That(FrameCodec.ReadLength(new byte[] { 0x29, 0x00 }), Is.EqualTo(BitConverter.ToUInt16(new byte[] { 0x29, 0x00 }, 0))); + Assert.Throws(() => FrameCodec.ReadLength(new byte[] { 0x01 })); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/LegacyReaders.cs b/binding/YGOLegacy.Engine.Tests/LegacyReaders.cs new file mode 100644 index 0000000..ffd3429 --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/LegacyReaders.cs @@ -0,0 +1,156 @@ +// Frozen copies of the legacy Unity (MDPro3) and WindBot (YGOSharp) readers the parity tests +// compare the shared codec against. Copied verbatim from the Unity repo on 2026-10-15 +// (Assets/Scripts/MDPro3/Duel/TcpHelper.cs, Assets/Scripts/YGOSharp/YGOSharp.Network/); +// only MDPro3's Debug.Log in its catch is dropped. Test-only; never shipped. +using System; +using System.IO; +using System.Text; + +namespace MDPro3 +{ + public static class BinaryExtensions + { + public static void WriteUnicode(this BinaryWriter writer, string text, int len) + { + try + { + var unicode = Encoding.Unicode.GetBytes(text); + var result = new byte[len * 2]; + for (var i = 0; i < result.Length; i++) result[i] = 204; + var max = len * 2 - 2; + Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length); + result[unicode.Length] = 0; + result[unicode.Length + 1] = 0; + writer.Write(result); + } + catch (Exception) + { + } + } + + public static string ReadUnicode(this BinaryReader reader, int len) + { + var unicode = reader.ReadBytes(len * 2); + var text = Encoding.Unicode.GetString(unicode); + text = text[..text.IndexOf('\0')]; + return text; + } + + public static string ReadALLUnicode(this BinaryReader reader) + { + var unicode = reader.ReadToEnd(); + var text = Encoding.Unicode.GetString(unicode); + text = text.Substring(0, text.IndexOf('\0')); + return text; + } + + public static byte[] ReadToEnd(this BinaryReader reader) + { + return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); + } + } +} + +namespace YGOSharp.Network.Utils +{ + public static class BinaryExtensions + { + // fixed length strings + public static void WriteUnicode(this BinaryWriter writer, string text, int len) + { + byte[] unicode = Encoding.Unicode.GetBytes(text); + byte[] result = new byte[len * 2]; + int copy = unicode.Length; + if (unicode.Length > len * 2 - 2) + { + copy = len * 2 - 2; +#if DEBUG + throw new ArgumentException("String '" + text + "' is too long for fixed length " + len + "."); +#endif + } + Array.Copy(unicode, result, copy); + writer.Write(result); + } + + // variable length strings + public static void WriteUnicodeAutoLength(this BinaryWriter writer, string text, int maxlen) + { + byte[] result = Encoding.Unicode.GetBytes(text + "\0"); + int len = result.Length / 2; + if (len > maxlen) + { + len = maxlen; + result[len * 2 - 2] = 0; + result[len * 2 - 1] = 0; +#if DEBUG + throw new ArgumentException("String '" + text + "' is too long for max length " + maxlen + "."); +#endif + } + writer.Write(result, 0, len * 2); + } + + public static string ReadUnicode(this BinaryReader reader, int len) + { + byte[] unicode = reader.ReadBytes(len * 2); + string text = Encoding.Unicode.GetString(unicode); + int index = text.IndexOf('\0'); + if (index > 0) text = text.Substring(0, index); + return text; + } + + public static byte[] ReadToEnd(this BinaryReader reader) + { + return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); + } + } +} + +namespace YGOSharp.Network.Enums +{ + public enum CtosMessage + { + Response = 0x1, + UpdateDeck = 0x2, + HandResult = 0x3, + TpResult = 0x4, + PlayerInfo = 0x10, + CreateGame = 0x11, + JoinGame = 0x12, + LeaveGame = 0x13, + Surrender = 0x14, + TimeConfirm = 0x15, + Chat = 0x16, + ExternalAddress = 0x17, + HsToDuelist = 0x20, + HsToObserver = 0x21, + HsReady = 0x22, + HsNotReady = 0x23, + HsKick = 0x24, + HsStart = 0x25 + } + + public enum StocMessage + { + GameMsg = 0x1, + ErrorMsg = 0x2, + SelectHand = 0x3, + SelectTp = 0x4, + HandResult = 0x5, + TpResult = 0x6, + ChangeSide = 0x7, + WaitingSide = 0x8, + CreateGame = 0x11, + JoinGame = 0x12, + TypeChange = 0x13, + LeaveGame = 0x14, + DuelStart = 0x15, + DuelEnd = 0x16, + Replay = 0x17, + TimeLimit = 0x18, + Chat = 0x19, + HsPlayerEnter = 0x20, + HsPlayerChange = 0x21, + HsWatchChange = 0x22, + TeammateSurrender = 0x23 + } +} diff --git a/binding/YGOLegacy.Engine.Tests/ProtocolCodecTests.cs b/binding/YGOLegacy.Engine.Tests/ProtocolCodecTests.cs new file mode 100644 index 0000000..b64b4c8 --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/ProtocolCodecTests.cs @@ -0,0 +1,304 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using NUnit.Framework; +using YGOLegacy.Protocol.Codecs; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Tests +{ + public class ProtocolCodecTests + { + private const ushort Version = 0x1362; + + private static byte[] Bytes(Action write) + { + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + write(writer); + writer.Flush(); + return stream.ToArray(); + } + } + + private static BinaryReader Reader(byte[] bytes) + { + return new BinaryReader(new MemoryStream(bytes)); + } + + private static byte[] Utf16(string text) + { + return Encoding.Unicode.GetBytes(text); + } + + private static byte[] Concat(params byte[][] parts) + { + return parts.SelectMany(p => p).ToArray(); + } + + private static void AssertEqualExceptPadding(byte[] ours, byte[] legacy, int paddingFrom, byte legacyPad) + { + Assert.That(ours.Length, Is.EqualTo(legacy.Length)); + Assert.That(ours.Take(paddingFrom), Is.EqualTo(legacy.Take(paddingFrom))); + Assert.That(ours.Skip(paddingFrom), Is.All.EqualTo(0)); + Assert.That(legacy.Skip(paddingFrom), Is.All.EqualTo(legacyPad)); + } + + [Test] + public void PlayerInfo_WritesFortyZeroPaddedBytes() + { + var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice"))); + + Assert.That(ours, Is.EqualTo(Concat(Utf16("Alice\0"), new byte[28]))); + } + + [Test] + public void PlayerInfo_MatchesWindBotExactly_AndUnityExceptPadding() + { + var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice"))); + var windbot = Bytes(w => YGOSharp.Network.Utils.BinaryExtensions.WriteUnicode(w, "Alice", 20)); + var unity = Bytes(w => MDPro3.BinaryExtensions.WriteUnicode(w, "Alice", 20)); + + Assert.That(ours, Is.EqualTo(windbot)); + AssertEqualExceptPadding(ours, unity, 12, 0xCC); + } + + [Test] + public void PlayerInfo_OverlongName_KeepsNineteenUnitsAndTerminator() + { + var name = new string('n', 25); + byte[] ours = null; + + Assert.DoesNotThrow(() => ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo(name)))); + Assert.That(ours.Length, Is.EqualTo(40)); + Assert.That(ours.Skip(38), Is.All.EqualTo(0)); + Assert.That(LobbyCodecs.PlayerInfo.Read(Reader(ours)).Name, Is.EqualTo(name.Substring(0, 19))); + } + + [Test] + public void PlayerInfo_EmojiAtTheBoundary_IsNotSplit() + { + var name = new string('a', 18) + "\U0001F600"; + var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo(name))); + + Assert.That(ours.Length, Is.EqualTo(40)); + Assert.That(ours.Skip(36), Is.All.EqualTo(0)); + Assert.That(LobbyCodecs.PlayerInfo.Read(Reader(ours)).Name, Is.EqualTo(new string('a', 18))); + } + + [Test] + public void PlayerInfo_EmojiThatFits_RoundTrips() + { + var name = new string('a', 17) + "\U0001F600"; + var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo(name))); + + Assert.That(ours.Length, Is.EqualTo(40)); + Assert.That(LobbyCodecs.PlayerInfo.Read(Reader(ours)).Name, Is.EqualTo(name)); + } + + [Test] + public void PlayerInfo_NullName_WritesZeros() + { + var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, default(PlayerInfo))); + + Assert.That(ours, Is.EqualTo(new byte[40])); + } + + [Test] + public void ReadFixed_TerminatorAtZero_ReadsEmpty() + { + Assert.That(UnicodeCodec.ReadFixed(Reader(new byte[40]), 20), Is.EqualTo(string.Empty)); + } + + [Test] + public void ReadFixed_NoTerminator_ReadsWholeBuffer() + { + var full = new string('x', 20); + + Assert.That(UnicodeCodec.ReadFixed(Reader(Utf16(full)), 20), Is.EqualTo(full)); + } + + [Test] + public void WriteTerminated_CapsAtMaxCharsIncludingTerminator() + { + var ours = Bytes(w => UnicodeCodec.WriteTerminated(w, "abcdef", 4)); + + Assert.That(ours, Is.EqualTo(Utf16("abc\0"))); + } + + [Test] + public void WriteTerminated_EmojiAtTheCap_IsNotSplit() + { + var ours = Bytes(w => UnicodeCodec.WriteTerminated(w, "a\U0001F600", 3)); + + Assert.That(ours, Is.EqualTo(Utf16("a\0"))); + } + + [Test] + public void JoinGame_WritesFortyEightBytes() + { + var ours = Bytes(w => LobbyCodecs.JoinGame.Write(w, new JoinGame(Version, "abc"))); + var head = new byte[] { 0x62, 0x13, 0xCC, 0xCC, 0x00, 0x00, 0x00, 0x00 }; + + Assert.That(ours, Is.EqualTo(Concat(head, Utf16("abc\0"), new byte[32]))); + } + + [Test] + public void JoinGame_MatchesWindBotExactly_AndUnityExceptPadding() + { + var ours = Bytes(w => LobbyCodecs.JoinGame.Write(w, new JoinGame(Version, "abc"))); + var windbot = Bytes(w => + { + w.Write((short)Version); + w.Write(new byte[] { 0xCC, 0xCC, 0x00, 0x00, 0x00, 0x00 }); + YGOSharp.Network.Utils.BinaryExtensions.WriteUnicode(w, "abc", 20); + }); + var unity = Bytes(w => + { + w.Write((short)Version); + w.Write((byte)204); + w.Write((byte)204); + w.Write(0); + MDPro3.BinaryExtensions.WriteUnicode(w, "abc", 20); + }); + + Assert.That(ours, Is.EqualTo(windbot)); + AssertEqualExceptPadding(ours, unity, 16, 0xCC); + } + + [Test] + public void JoinGame_RoundTrips() + { + var ours = Bytes(w => LobbyCodecs.JoinGame.Write(w, new JoinGame(Version, "secret"))); + var read = LobbyCodecs.JoinGame.Read(Reader(ours)); + + Assert.That(read.Version, Is.EqualTo(Version)); + Assert.That(read.Password, Is.EqualTo("secret")); + } + + [Test] + public void ExternalAddress_WritesZeroIpThenTerminatedHost() + { + var ours = Bytes(w => LobbyCodecs.ExternalAddress.Write(w, new ExternalAddress("127.0.0.1"))); + + Assert.That(ours, Is.EqualTo(Concat(new byte[4], Utf16("127.0.0.1\0")))); + } + + [Test] + public void ExternalAddress_MatchesBothClientsExactly() + { + const string host = "127.0.0.1"; + var ours = Bytes(w => LobbyCodecs.ExternalAddress.Write(w, new ExternalAddress(host))); + var windbot = Bytes(w => + { + w.Write((uint)0); + YGOSharp.Network.Utils.BinaryExtensions.WriteUnicodeAutoLength(w, host, 255); + }); + var unity = Bytes(w => + { + w.Write((uint)0); + MDPro3.BinaryExtensions.WriteUnicode(w, host, host.Length + 1); + }); + + Assert.That(ours, Is.EqualTo(windbot)); + Assert.That(ours, Is.EqualTo(unity)); + } + + [Test] + public void ExternalAddress_RoundTrips() + { + var ours = Bytes(w => LobbyCodecs.ExternalAddress.Write(w, new ExternalAddress("gitea.dev.blueoceanswim.com"))); + + Assert.That(LobbyCodecs.ExternalAddress.Read(Reader(ours)).Host, Is.EqualTo("gitea.dev.blueoceanswim.com")); + } + + [Test] + public void UpdateDeck_WritesCountsThenIds() + { + var deck = new UpdateDeck(new[] { 1, 2 }, new[] { 3 }, new[] { 4 }); + var ours = Bytes(w => LobbyCodecs.UpdateDeck.Write(w, deck)); + var legacy = Bytes(w => + { + w.Write(2 + 1); + w.Write(1); + w.Write(1); + w.Write(2); + w.Write(3); + w.Write(4); + }); + + Assert.That(ours, Is.EqualTo(legacy)); + Assert.That(ours.Length, Is.EqualTo(24)); + } + + [Test] + public void UpdateDeck_ReadsMainAndExtraAsOneList() + { + var deck = new UpdateDeck(new[] { 1, 2 }, new[] { 3 }, new[] { 4 }); + var read = LobbyCodecs.UpdateDeck.Read(Reader(Bytes(w => LobbyCodecs.UpdateDeck.Write(w, deck)))); + + Assert.That(read.Main, Is.EqualTo(new[] { 1, 2, 3 })); + Assert.That(read.Extra, Is.Empty); + Assert.That(read.Side, Is.EqualTo(new[] { 4 })); + } + + [Test] + public void CtosPacket_PutsTheIdByteBeforeThePayload() + { + var packet = CtosPacket.Begin(LobbyCodecs.PlayerInfo.Id); + LobbyCodecs.PlayerInfo.Write(packet, new PlayerInfo("Alice")); + var bytes = ((MemoryStream)packet.BaseStream).ToArray(); + + Assert.That(bytes.Length, Is.EqualTo(41)); + Assert.That(bytes[0], Is.EqualTo(0x10)); + Assert.That(bytes.Skip(1), Is.EqualTo(Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice"))))); + } + + [Test] + public void CodecIds_MatchTheCatalog() + { + Assert.That((int)LobbyCodecs.ExternalAddress.Id, Is.EqualTo(0x17)); + Assert.That((int)LobbyCodecs.PlayerInfo.Id, Is.EqualTo(0x10)); + Assert.That((int)LobbyCodecs.JoinGame.Id, Is.EqualTo(0x12)); + Assert.That((int)LobbyCodecs.UpdateDeck.Id, Is.EqualTo(0x02)); + Assert.That((int)LobbyCodecs.Profile.Id, Is.EqualTo(0x5D)); + Assert.That((int)StocCodecs.Profile.Id, Is.EqualTo(0x5D)); + } + + [Test] + public void CtosCatalog_AgreesWithWindBotEnum() + { + AssertCatalogParity(typeof(CtosMessage), + new[] { typeof(YGOSharp.Network.Enums.CtosMessage) }, + new[] { "RequestField", "Capability", "Appearance", "Dialogue", "SeatPlan", "SeatRequest", "SeatSwap", "SeatMove", + "RestartPrepare", "RestartAck", "RestartControl", "SeatResume", "RestartOpen", "SeatState", "Profile", "AttackPreview" }); + } + + [Test] + public void StocCatalog_AgreesWithWindBotEnum() + { + Assert.That((int)StocMessage.DeckCount, Is.EqualTo(0x09)); + AssertCatalogParity(typeof(StocMessage), + new[] { typeof(YGOSharp.Network.Enums.StocMessage) }, + new[] { "DeckCount", "FieldFinish", "SrvproRoomList", "Capability", "Appearance", "Dialogue", "SetupPairs", "SeatPlan", + "RoomRestarting", "RestartStatus", "SeatResumeResult", "RestartOpen", "SeatState", "MatchOver", "CoinToss", "DeckList", "Profile", "AttackPreview" }); + } + + private static void AssertCatalogParity(Type catalog, Type[] legacyEnums, string[] expectedExtras) + { + var legacyNames = legacyEnums.SelectMany(Enum.GetNames).Distinct().ToArray(); + foreach (var legacy in legacyEnums) + { + foreach (var name in Enum.GetNames(legacy)) + { + Assert.That(Enum.IsDefined(catalog, name), Is.True, legacy.FullName + "." + name + " is missing from the catalog"); + Assert.That(Convert.ToInt32(Enum.Parse(catalog, name)), Is.EqualTo(Convert.ToInt32(Enum.Parse(legacy, name))), name); + } + } + var extras = Enum.GetNames(catalog).Except(legacyNames).OrderBy(n => n).ToArray(); + Assert.That(extras, Is.EqualTo(expectedExtras.OrderBy(n => n).ToArray())); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/StocCodecTests.cs b/binding/YGOLegacy.Engine.Tests/StocCodecTests.cs new file mode 100644 index 0000000..4278f17 --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/StocCodecTests.cs @@ -0,0 +1,406 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using NUnit.Framework; +using YGOLegacy.Protocol.Codecs; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Tests +{ + public class StocCodecTests + { + private static byte[] Bytes(Action write) + { + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + write(writer); + writer.Flush(); + return stream.ToArray(); + } + } + + private static BinaryReader Reader(byte[] bytes) + { + return new BinaryReader(new MemoryStream(bytes)); + } + + private static byte[] Utf16(string text) + { + return Encoding.Unicode.GetBytes(text); + } + + private static byte[] Concat(params byte[][] parts) + { + return parts.SelectMany(p => p).ToArray(); + } + + private static byte[] Le16(int value) + { + return new[] { (byte)value, (byte)(value >> 8) }; + } + + private static byte[] Le32(int value) + { + return new[] { (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24) }; + } + + private static byte[] Zeros(int count) + { + return new byte[count]; + } + + [Test] + public void Ids_MatchTheStocCatalog() + { + Assert.That(StocCodecs.ErrorMsg.Id, Is.EqualTo(StocMessage.ErrorMsg)); + Assert.That(StocCodecs.HandResult.Id, Is.EqualTo(StocMessage.HandResult)); + Assert.That(StocCodecs.JoinGame.Id, Is.EqualTo(StocMessage.JoinGame)); + Assert.That(StocCodecs.TypeChange.Id, Is.EqualTo(StocMessage.TypeChange)); + Assert.That(StocCodecs.TimeLimit.Id, Is.EqualTo(StocMessage.TimeLimit)); + Assert.That(StocCodecs.Chat.Id, Is.EqualTo(StocMessage.Chat)); + Assert.That(StocCodecs.HsPlayerEnter.Id, Is.EqualTo(StocMessage.HsPlayerEnter)); + Assert.That(StocCodecs.HsPlayerChange.Id, Is.EqualTo(StocMessage.HsPlayerChange)); + Assert.That(StocCodecs.HsWatchChange.Id, Is.EqualTo(StocMessage.HsWatchChange)); + Assert.That(StocCodecs.DeckCount.Id, Is.EqualTo(StocMessage.DeckCount)); + } + + [Test] + public void ErrorMsg_GoldenBytes_MatchTheNativeStruct() + { + var code = (4 << 28) | 12345; + var bytes = Bytes(w => StocCodecs.ErrorMsg.Write(w, new ErrorMsg(2, code))); + + Assert.That(bytes.Length, Is.EqualTo(8)); + Assert.That(bytes, Is.EqualTo(Concat(new byte[] { 2 }, Zeros(3), Le32(code)))); + + var read = StocCodecs.ErrorMsg.Read(Reader(bytes)); + Assert.That(read.Msg, Is.EqualTo(2)); + Assert.That(read.Code, Is.EqualTo(code)); + Assert.That(read.Code >> 28, Is.EqualTo(4)); + Assert.That(read.Code & 0xFFFFFFF, Is.EqualTo(12345)); + } + + [Test] + public void ErrorMsg_ReadsWhatBothLegacyHandlersRead() + { + var bytes = Concat(new byte[] { 1 }, new byte[] { 0xAA, 0xBB, 0xCC }, Le32(2)); + var legacy = Reader(bytes); + int legacyMsg = legacy.ReadByte(); + legacy.ReadByte(); + legacy.ReadByte(); + legacy.ReadByte(); + var legacyCode = legacy.ReadInt32(); + + var read = StocCodecs.ErrorMsg.Read(Reader(bytes)); + Assert.That(read.Msg, Is.EqualTo(legacyMsg)); + Assert.That(read.Code, Is.EqualTo(legacyCode)); + } + + [Test] + public void HandResult_GoldenBytes_AndShortPacket() + { + var bytes = Bytes(w => StocCodecs.HandResult.Write(w, new HandResultAnnounce(1, 3))); + Assert.That(bytes, Is.EqualTo(new byte[] { 1, 3 })); + + var read = StocCodecs.HandResult.Read(Reader(bytes)); + Assert.That(read.First, Is.EqualTo(1)); + Assert.That(read.Second, Is.EqualTo(3)); + + var shortRead = StocCodecs.HandResult.Read(Reader(new byte[] { 2 })); + Assert.That(shortRead.First, Is.EqualTo(2)); + Assert.That(shortRead.Second, Is.EqualTo(0)); + } + + [Test] + public void HostInfo_GoldenBytes_MatchTheNative20ByteStruct() + { + var info = new HostInfo(0xDEADBEEF, 5, 2, 5, true, false, 8000, 5, 1, 180); + var bytes = Bytes(w => StocCodecs.JoinGame.Write(w, info)); + + Assert.That(bytes.Length, Is.EqualTo(20)); + Assert.That(bytes, Is.EqualTo(Concat( + Le32(unchecked((int)0xDEADBEEF)), + new byte[] { 5, 2, 5, 1, 0 }, + Zeros(3), + Le32(8000), + new byte[] { 5, 1 }, + Le16(180)))); + Assert.That(bytes.Skip(9).Take(3), Is.All.EqualTo(0)); + + var read = StocCodecs.JoinGame.Read(Reader(bytes)); + Assert.That(read.Lflist, Is.EqualTo(0xDEADBEEF)); + Assert.That(read.Rule, Is.EqualTo(5)); + Assert.That(read.Mode, Is.EqualTo(2)); + Assert.That(read.DuelRule, Is.EqualTo(5)); + Assert.That(read.NoCheckDeck, Is.True); + Assert.That(read.NoShuffleDeck, Is.False); + Assert.That(read.StartLp, Is.EqualTo(8000)); + Assert.That(read.StartHand, Is.EqualTo(5)); + Assert.That(read.DrawCount, Is.EqualTo(1)); + Assert.That(read.TimeLimit, Is.EqualTo(180)); + } + + [Test] + public void HostInfo_ReadsWhatUnitysLegacyFieldSequenceRead() + { + var bytes = Bytes(w => StocCodecs.JoinGame.Write(w, new HostInfo(7, 0, 1, 4, false, true, 16000, 4, 2, 240))); + + var legacy = Reader(bytes); + var lflist = legacy.ReadUInt32(); + var rule = legacy.ReadByte(); + var mode = legacy.ReadByte(); + int masterRule = legacy.ReadChar(); + var noCheck = legacy.ReadBoolean(); + var noShuffle = legacy.ReadBoolean(); + legacy.ReadByte(); + legacy.ReadByte(); + legacy.ReadByte(); + var startLp = legacy.ReadInt32(); + var startHand = legacy.ReadByte(); + var drawCount = legacy.ReadByte(); + var timeLimit = legacy.ReadInt16(); + + var read = StocCodecs.JoinGame.Read(Reader(bytes)); + Assert.That(read.Lflist, Is.EqualTo(lflist)); + Assert.That(read.Rule, Is.EqualTo(rule)); + Assert.That(read.Mode, Is.EqualTo(mode)); + Assert.That((int)read.DuelRule, Is.EqualTo(masterRule)); + Assert.That(read.NoCheckDeck, Is.EqualTo(noCheck)); + Assert.That(read.NoShuffleDeck, Is.EqualTo(noShuffle)); + Assert.That(read.StartLp, Is.EqualTo(startLp)); + Assert.That(read.StartHand, Is.EqualTo(startHand)); + Assert.That(read.DrawCount, Is.EqualTo(drawCount)); + Assert.That((short)read.TimeLimit, Is.EqualTo(timeLimit)); + } + + [Test] + public void TypeChange_NibblesRoundTrip() + { + for (byte position = 0; position < 4; position++) + { + foreach (var isHost in new[] { false, true }) + { + var bytes = Bytes(w => StocCodecs.TypeChange.Write(w, new TypeChange(position, isHost))); + Assert.That(bytes, Is.EqualTo(new[] { (byte)(position | (isHost ? 0x10 : 0)) })); + + var read = StocCodecs.TypeChange.Read(Reader(bytes)); + Assert.That(read.Position, Is.EqualTo(position)); + Assert.That(read.IsHost, Is.EqualTo(isHost)); + } + } + + var observer = StocCodecs.TypeChange.Read(Reader(new byte[] { 0x07 })); + Assert.That(observer.Position, Is.EqualTo(7)); + Assert.That(observer.IsHost, Is.False); + + var hostByOtherBit = StocCodecs.TypeChange.Read(Reader(new byte[] { 0x21 })); + Assert.That(hostByOtherBit.Position, Is.EqualTo(1)); + Assert.That(hostByOtherBit.IsHost, Is.True); + } + + [Test] + public void TimeLimit_GoldenBytes_AndShortPackets() + { + var bytes = Bytes(w => StocCodecs.TimeLimit.Write(w, new TimeLimit(1, 300))); + Assert.That(bytes, Is.EqualTo(Concat(new byte[] { 1, 0 }, Le16(300)))); + + var read = StocCodecs.TimeLimit.Read(Reader(bytes)); + Assert.That(read.Player, Is.EqualTo(1)); + Assert.That(read.LeftTime, Is.EqualTo(300)); + + var twoBytes = StocCodecs.TimeLimit.Read(Reader(new byte[] { 0, 0 })); + Assert.That(twoBytes.Player, Is.EqualTo(0)); + Assert.That(twoBytes.LeftTime, Is.EqualTo(0)); + + var oneByte = StocCodecs.TimeLimit.Read(Reader(new byte[] { 1 })); + Assert.That(oneByte.Player, Is.EqualTo(1)); + Assert.That(oneByte.LeftTime, Is.EqualTo(0)); + } + + [Test] + public void ServerChat_GoldenBytes_PlayerThenTextThenTerminator() + { + var bytes = Bytes(w => StocCodecs.Chat.Write(w, new ServerChat(1, "hi"))); + Assert.That(bytes, Is.EqualTo(Concat(Le16(1), Utf16("hi"), Zeros(2)))); + + var read = StocCodecs.Chat.Read(Reader(bytes)); + Assert.That(read.Player, Is.EqualTo(1)); + Assert.That(read.Text, Is.EqualTo("hi")); + + var system = StocCodecs.Chat.Read(Reader(Concat(Le16(8), Utf16("watch"), Zeros(2)))); + Assert.That(system.Player, Is.EqualTo(8)); + Assert.That(system.Text, Is.EqualTo("watch")); + } + + [Test] + public void ServerChat_ReadsWhatBothLegacyHandlersRead() + { + var bytes = Concat(Le16(2), Utf16("twenty byte chat msg"), Zeros(2)); + + var unity = Reader(bytes); + int unityPlayer = unity.ReadInt16(); + var unityText = MDPro3.BinaryExtensions.ReadUnicode(unity, (int)((unity.BaseStream.Length - unity.BaseStream.Position) / 2)); + + var windbot = Reader(bytes); + int windbotPlayer = windbot.ReadInt16(); + var windbotText = YGOSharp.Network.Utils.BinaryExtensions.ReadUnicode(windbot, 256); + + var read = StocCodecs.Chat.Read(Reader(bytes)); + Assert.That(read.Player, Is.EqualTo(unityPlayer)); + Assert.That(read.Player, Is.EqualTo(windbotPlayer)); + Assert.That(read.Text, Is.EqualTo(unityText)); + Assert.That(read.Text, Is.EqualTo(windbotText)); + } + + [Test] + public void ServerChat_WithoutTerminator_ReadsTheWholeTail() + { + var bytes = Concat(Le16(0), Utf16("no terminator")); + + var read = StocCodecs.Chat.Read(Reader(bytes)); + Assert.That(read.Text, Is.EqualTo("no terminator")); + + var unity = Reader(bytes); + unity.ReadInt16(); + Assert.Throws(() => + MDPro3.BinaryExtensions.ReadUnicode(unity, (int)((unity.BaseStream.Length - unity.BaseStream.Position) / 2))); + } + + [Test] + public void ServerChat_EmptyText_ReadsEmpty() + { + var bytes = Bytes(w => StocCodecs.Chat.Write(w, new ServerChat(0, ""))); + Assert.That(bytes, Is.EqualTo(Concat(Le16(0), Zeros(2)))); + Assert.That(StocCodecs.Chat.Read(Reader(bytes)).Text, Is.EqualTo("")); + } + + [Test] + public void PlayerEnter_GoldenBytes_MatchThePacked41ByteStruct() + { + var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter("Joey", 1))); + + Assert.That(bytes.Length, Is.EqualTo(41)); + Assert.That(bytes, Is.EqualTo(Concat(Utf16("Joey"), Zeros(32), new byte[] { 1 }))); + + var read = StocCodecs.HsPlayerEnter.Read(Reader(bytes)); + Assert.That(read.Name, Is.EqualTo("Joey")); + Assert.That(read.Position, Is.EqualTo(1)); + } + + [Test] + public void PlayerEnter_ReadsWhatBothLegacyHandlersRead() + { + var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter("Mai Valentine B", 0))); + + var unity = Reader(bytes); + var unityName = MDPro3.BinaryExtensions.ReadUnicode(unity, 20); + var unityPos = unity.ReadByte() & 3; + + var windbot = Reader(bytes); + var windbotName = YGOSharp.Network.Utils.BinaryExtensions.ReadUnicode(windbot, 20); + int windbotPos = windbot.ReadByte(); + + var read = StocCodecs.HsPlayerEnter.Read(Reader(bytes)); + Assert.That(read.Name, Is.EqualTo(unityName)); + Assert.That(read.Name, Is.EqualTo(windbotName)); + Assert.That(read.Position & 3, Is.EqualTo(unityPos)); + Assert.That((int)read.Position, Is.EqualTo(windbotPos)); + } + + [Test] + public void PlayerEnter_EmptyName_ReadsEmpty_WhereYgoSharpReadTwentyNuls() + { + var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter("", 2))); + Assert.That(bytes, Is.EqualTo(Concat(Zeros(40), new byte[] { 2 }))); + + var read = StocCodecs.HsPlayerEnter.Read(Reader(bytes)); + Assert.That(read.Name, Is.EqualTo("")); + Assert.That(read.Position, Is.EqualTo(2)); + + var legacy = YGOSharp.Network.Utils.BinaryExtensions.ReadUnicode(Reader(bytes), 20); + Assert.That(legacy.Length, Is.EqualTo(20)); + Assert.That(legacy, Is.All.EqualTo('\0')); + } + + [Test] + public void PlayerEnter_NameClipsToNineteenAndAFullNameDoesNotThrow() + { + var longName = new string('x', 25); + var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter(longName, 3))); + Assert.That(bytes.Length, Is.EqualTo(41)); + Assert.That(bytes.Skip(38).Take(2), Is.All.EqualTo(0)); + Assert.That(StocCodecs.HsPlayerEnter.Read(Reader(bytes)).Name, Is.EqualTo(new string('x', 19))); + + var unterminated = Concat(Utf16(new string('y', 20)), new byte[] { 0 }); + var read = StocCodecs.HsPlayerEnter.Read(Reader(unterminated)); + Assert.That(read.Name, Is.EqualTo(new string('y', 20))); + Assert.That(read.Position, Is.EqualTo(0)); + Assert.Throws(() => MDPro3.BinaryExtensions.ReadUnicode(Reader(unterminated), 20)); + } + + [Test] + public void PlayerChange_NibblesRoundTrip() + { + var ready = Bytes(w => StocCodecs.HsPlayerChange.Write(w, new PlayerChange(2, 0x9))); + Assert.That(ready, Is.EqualTo(new byte[] { 0x29 })); + + var read = StocCodecs.HsPlayerChange.Read(Reader(ready)); + Assert.That(read.Position, Is.EqualTo(2)); + Assert.That(read.State, Is.EqualTo(0x9)); + + var observe = StocCodecs.HsPlayerChange.Read(Reader(new byte[] { 0x38 })); + Assert.That(observe.Position, Is.EqualTo(3)); + Assert.That(observe.State, Is.EqualTo(0x8)); + + var move = StocCodecs.HsPlayerChange.Read(Reader(new byte[] { 0x01 })); + Assert.That(move.Position, Is.EqualTo(0)); + Assert.That(move.State, Is.EqualTo(1)); + + var leave = Bytes(w => StocCodecs.HsPlayerChange.Write(w, new PlayerChange(1, 0xB))); + Assert.That(leave, Is.EqualTo(new byte[] { 0x1B })); + } + + [TestCase(0x29, 2, PlayerChangeKind.Ready, 0)] + [TestCase(0x38, 3, PlayerChangeKind.Observe, 0)] + [TestCase(0x1B, 1, PlayerChangeKind.Leave, 0)] + [TestCase(0x1A, 1, PlayerChangeKind.NotReady, 0)] + [TestCase(0x10, 1, PlayerChangeKind.MoveTo, 0)] + [TestCase(0x03, 0, PlayerChangeKind.MoveTo, 3)] + [TestCase(0x2F, 2, PlayerChangeKind.Unknown, 0)] + public void PlayerChange_Kind_IsDerivedFromTheStateNibble_AsTheLobbyHandlerDid(int status, int seat, PlayerChangeKind kind, int target) + { + var read = StocCodecs.HsPlayerChange.Read(Reader(new byte[] { (byte)status })); + + Assert.That(read.Position, Is.EqualTo(seat)); + Assert.That(read.Kind, Is.EqualTo(kind)); + Assert.That(read.TargetSeat, Is.EqualTo(target)); + } + + [Test] + public void WatchChange_GoldenBytes_LittleEndianUInt16() + { + var bytes = Bytes(w => StocCodecs.HsWatchChange.Write(w, new WatchChange(258))); + Assert.That(bytes, Is.EqualTo(new byte[] { 0x02, 0x01 })); + Assert.That(StocCodecs.HsWatchChange.Read(Reader(bytes)).Count, Is.EqualTo(258)); + } + + [Test] + public void DeckCount_GoldenBytes_InTheServersOrder() + { + var bytes = Bytes(w => StocCodecs.DeckCount.Write(w, new DeckCount(40, 15, 10, 41, 14, 9))); + + Assert.That(bytes.Length, Is.EqualTo(12)); + Assert.That(bytes, Is.EqualTo(Concat(Le16(40), Le16(15), Le16(10), Le16(41), Le16(14), Le16(9)))); + + var read = StocCodecs.DeckCount.Read(Reader(bytes)); + Assert.That(read.Main0, Is.EqualTo(40)); + Assert.That(read.Extra0, Is.EqualTo(15)); + Assert.That(read.Side0, Is.EqualTo(10)); + Assert.That(read.Main1, Is.EqualTo(41)); + Assert.That(read.Extra1, Is.EqualTo(14)); + Assert.That(read.Side1, Is.EqualTo(9)); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/StocRouterTests.cs b/binding/YGOLegacy.Engine.Tests/StocRouterTests.cs new file mode 100644 index 0000000..ff528fc --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/StocRouterTests.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.IO; +using NUnit.Framework; +using YGOLegacy.Protocol.Codecs; +using YGOLegacy.Protocol.Contracts; +using YGOLegacy.Protocol.Routing; + +namespace YGOLegacy.Protocol.Tests +{ + public class StocRouterTests + { + private static BinaryReader Packet(StocMessage id, params byte[] payload) + { + var bytes = new byte[payload.Length + 1]; + bytes[0] = (byte)id; + Array.Copy(payload, 0, bytes, 1, payload.Length); + return new BinaryReader(new MemoryStream(bytes)); + } + + [Test] + public void MixedBatch_DispatchesInArrivalOrder_WhateverTheRegistrationOrder() + { + var router = new StocRouter(); + var seen = new List(); + router.Register(StocMessage.Chat, r => seen.Add(StocMessage.Chat)); + router.Register(StocMessage.GameMsg, r => seen.Add(StocMessage.GameMsg)); + router.Register(StocMessage.HandResult, r => seen.Add(StocMessage.HandResult)); + + var arrivals = new[] { StocMessage.HandResult, StocMessage.GameMsg, StocMessage.Chat, StocMessage.GameMsg }; + foreach (var id in arrivals) + { + StocMessage read; + Assert.That(router.Dispatch(Packet(id), out read), Is.EqualTo(RouteOutcome.Handled)); + Assert.That(read, Is.EqualTo(id)); + } + + Assert.That(seen, Is.EqualTo(arrivals)); + } + + [Test] + public void Handler_GetsTheReaderPositionedAfterTheId() + { + var router = new StocRouter(); + var result = default(HandResultAnnounce); + router.Register(StocMessage.HandResult, r => result = StocCodecs.HandResult.Read(r)); + + StocMessage id; + var outcome = router.Dispatch(Packet(StocMessage.HandResult, 2, 3), out id); + + Assert.That(outcome, Is.EqualTo(RouteOutcome.Handled)); + Assert.That(id, Is.EqualTo(StocMessage.HandResult)); + Assert.That(result.First, Is.EqualTo(2)); + Assert.That(result.Second, Is.EqualTo(3)); + } + + [Test] + public void GameMsg_ReachesItsHandler_WithTheReaderAtTheInnerId() + { + var router = new StocRouter(); + var inner = -1; + var tail = -1L; + router.Register(StocMessage.GameMsg, r => + { + inner = r.ReadByte(); + tail = r.BaseStream.Length - r.BaseStream.Position; + }); + + StocMessage id; + var outcome = router.Dispatch(Packet(StocMessage.GameMsg, 0x5A, 1, 2, 3), out id); + + Assert.That(outcome, Is.EqualTo(RouteOutcome.Handled)); + Assert.That(inner, Is.EqualTo(0x5A)); + Assert.That(tail, Is.EqualTo(3)); + } + + [Test] + public void IgnoredId_ReturnsIgnored_AndCallsNothing() + { + var router = new StocRouter(); + var unknownCalls = 0; + router.OnUnknown = (id, bytes) => unknownCalls++; + router.Ignore(StocMessage.FieldFinish); + + StocMessage read; + var outcome = router.Dispatch(Packet(StocMessage.FieldFinish, 9, 9), out read); + + Assert.That(outcome, Is.EqualTo(RouteOutcome.Ignored)); + Assert.That(read, Is.EqualTo(StocMessage.FieldFinish)); + Assert.That(unknownCalls, Is.EqualTo(0)); + Assert.That(router.IsRegistered(StocMessage.FieldFinish), Is.True); + } + + [Test] + public void UnknownId_ReturnsUnknown_ReportsOncePerId_WithThePayloadLength() + { + var router = new StocRouter(); + var reports = new List>(); + router.OnUnknown = (id, bytes) => reports.Add(new KeyValuePair(id, bytes)); + + StocMessage read; + Assert.That(router.Dispatch(Packet(StocMessage.SrvproRoomList, 1, 2, 3), out read), Is.EqualTo(RouteOutcome.Unknown)); + Assert.That(read, Is.EqualTo(StocMessage.SrvproRoomList)); + Assert.That(router.Dispatch(Packet(StocMessage.SrvproRoomList, 1), out read), Is.EqualTo(RouteOutcome.Unknown)); + Assert.That(router.Dispatch(Packet(StocMessage.FieldFinish), out read), Is.EqualTo(RouteOutcome.Unknown)); + + Assert.That(reports.Count, Is.EqualTo(2)); + Assert.That(reports[0].Key, Is.EqualTo(StocMessage.SrvproRoomList)); + Assert.That(reports[0].Value, Is.EqualTo(3)); + Assert.That(reports[1].Key, Is.EqualTo(StocMessage.FieldFinish)); + Assert.That(reports[1].Value, Is.EqualTo(0)); + Assert.That(router.IsRegistered(StocMessage.SrvproRoomList), Is.False); + } + + [Test] + public void UnknownId_WithoutAHook_DoesNotThrow() + { + var router = new StocRouter(); + StocMessage read; + Assert.That(router.Dispatch(Packet(StocMessage.SrvproRoomList, 1), out read), Is.EqualTo(RouteOutcome.Unknown)); + } + + [Test] + public void DuplicateRegistration_Throws() + { + var router = new StocRouter(); + router.Register(StocMessage.Chat, r => { }); + router.Ignore(StocMessage.DeckCount); + + Assert.Throws(() => router.Register(StocMessage.Chat, r => { })); + Assert.Throws(() => router.Ignore(StocMessage.Chat)); + Assert.Throws(() => router.Register(StocMessage.DeckCount, r => { })); + Assert.Throws(() => router.Ignore(StocMessage.DeckCount)); + } + + [Test] + public void NullHandler_Throws() + { + var router = new StocRouter(); + Assert.Throws(() => router.Register(StocMessage.Chat, null)); + Assert.That(router.IsRegistered(StocMessage.Chat), Is.False); + } + + [Test] + public void EmptyPacket_ReturnsEmpty_WithoutReading() + { + var router = new StocRouter(); + var calls = 0; + router.OnUnknown = (id, bytes) => calls++; + router.Register(StocMessage.GameMsg, r => calls++); + + StocMessage read; + var outcome = router.Dispatch(new BinaryReader(new MemoryStream(new byte[0])), out read); + + Assert.That(outcome, Is.EqualTo(RouteOutcome.Empty)); + Assert.That(calls, Is.EqualTo(0)); + } + + [Test] + public void HandlerException_PropagatesUnchanged() + { + var router = new StocRouter(); + var thrown = new InvalidDataException("bad chat"); + router.Register(StocMessage.Chat, r => { throw thrown; }); + + var read = default(StocMessage); + var caught = Assert.Throws(() => router.Dispatch(Packet(StocMessage.Chat, 1), out read)); + + Assert.That(caught, Is.SameAs(thrown)); + } + + [Test] + public void NullReader_Throws() + { + var router = new StocRouter(); + StocMessage read; + Assert.Throws(() => router.Dispatch(null, out read)); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/YGOLegacy.Engine.Tests.csproj b/binding/YGOLegacy.Engine.Tests/YGOLegacy.Engine.Tests.csproj new file mode 100644 index 0000000..b32cad7 --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/YGOLegacy.Engine.Tests.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + 9 + disable + false + true + + + + + + + + + + + + + diff --git a/binding/YGOLegacy.Engine/Protocol/Codecs/DuelCodecs.cs b/binding/YGOLegacy.Engine/Protocol/Codecs/DuelCodecs.cs new file mode 100644 index 0000000..bbecf4b --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Codecs/DuelCodecs.cs @@ -0,0 +1,67 @@ +using System.IO; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Codecs +{ + public static class DuelCodecs + { + public static readonly ResponseCodec Response = new ResponseCodec(); + public static readonly HandResultCodec HandResult = new HandResultCodec(); + public static readonly TpResultCodec TpResult = new TpResultCodec(); + public static readonly EmptyPayloadCodec Surrender = new EmptyPayloadCodec(CtosMessage.Surrender); + public static readonly EmptyPayloadCodec TimeConfirm = new EmptyPayloadCodec(CtosMessage.TimeConfirm); + } + + public sealed class ResponseCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.Response; + + public void Write(BinaryWriter writer, Response payload) + { + var bytes = payload.Bytes; + if (bytes != null && bytes.Length > 0) + writer.Write(bytes, 0, bytes.Length); + } + + public void Write(BinaryWriter writer, int value) + { + writer.Write(value); + } + + public Response Read(BinaryReader reader) + { + var remaining = (int)(reader.BaseStream.Length - reader.BaseStream.Position); + return new Response(reader.ReadBytes(remaining)); + } + } + + public sealed class HandResultCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.HandResult; + + public void Write(BinaryWriter writer, HandResult payload) + { + writer.Write(payload.Result); + } + + public HandResult Read(BinaryReader reader) + { + return new HandResult(reader.ReadByte()); + } + } + + public sealed class TpResultCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.TpResult; + + public void Write(BinaryWriter writer, TpResult payload) + { + writer.Write((byte)(payload.GoFirst ? 1 : 0)); + } + + public TpResult Read(BinaryReader reader) + { + return new TpResult(reader.ReadByte() != 0); + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Codecs/FeatureCodecs.cs b/binding/YGOLegacy.Engine/Protocol/Codecs/FeatureCodecs.cs new file mode 100644 index 0000000..a1cae41 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Codecs/FeatureCodecs.cs @@ -0,0 +1,600 @@ +using System.IO; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Codecs +{ + public sealed class CapabilityCodec : ICtosCodec + { + public const int Size = 6; + public const int StampedSize = Size + StampedCodec.SeatBytes; + + public CtosMessage Id => CtosMessage.Capability; + + public void Write(BinaryWriter writer, Capability payload) + { + writer.Write(payload.Protocol); + writer.Write(payload.Flags); + } + + public Capability Read(BinaryReader reader) + { + var protocol = reader.ReadUInt16(); + var flags = reader.ReadUInt32(); + return new Capability(protocol, flags); + } + } + + public sealed class AppearanceCodec : ICtosCodec + { + public const int Size = AppearanceState.ItemCount * 4 + + (AppearanceState.DeckNameChars + AppearanceState.CharacterIdChars + AppearanceState.DeckGroupChars) * 2; + public const int StampedSize = Size + StampedCodec.SeatBytes; + + public CtosMessage Id => CtosMessage.Appearance; + + public void Write(BinaryWriter writer, AppearanceState payload) + { + for (var i = 0; i < AppearanceState.ItemCount; i++) + writer.Write(payload.Items != null && i < payload.Items.Length ? payload.Items[i] : 0); + UnicodeCodec.WriteFixed(writer, payload.DeckName, AppearanceState.DeckNameChars); + UnicodeCodec.WriteFixed(writer, payload.CharacterId, AppearanceState.CharacterIdChars); + UnicodeCodec.WriteFixed(writer, payload.DeckGroup, AppearanceState.DeckGroupChars); + } + + public AppearanceState Read(BinaryReader reader) + { + var items = new int[AppearanceState.ItemCount]; + for (var i = 0; i < items.Length; i++) + items[i] = reader.ReadInt32(); + var deckName = UnicodeCodec.ReadFixed(reader, AppearanceState.DeckNameChars); + var characterId = UnicodeCodec.ReadFixed(reader, AppearanceState.CharacterIdChars); + var deckGroup = UnicodeCodec.ReadFixed(reader, AppearanceState.DeckGroupChars); + return new AppearanceState(items, deckName, characterId, deckGroup); + } + } + + public sealed class DialogueCodec : ICtosCodec + { + public const int Size = 1 + 1 + 2 + 4 + 4 + DialogueLine.KeyChars * 2 * 2; + public const int StampedSize = Size + StampedCodec.SeatBytes; + private const byte TargetFaceDownFlag = 0x1; + + public CtosMessage Id => CtosMessage.Dialogue; + + public void Write(BinaryWriter writer, DialogueLine payload) + { + writer.Write(payload.Version); + writer.Write((byte)(payload.TargetFaceDown ? TargetFaceDownFlag : 0)); + writer.Write(payload.Index); + writer.Write(payload.CardCode); + writer.Write(payload.TargetCode); + UnicodeCodec.WriteFixed(writer, payload.CorpusKey, DialogueLine.KeyChars); + UnicodeCodec.WriteFixed(writer, payload.EventKey, DialogueLine.KeyChars); + } + + public DialogueLine Read(BinaryReader reader) + { + var version = reader.ReadByte(); + var flags = reader.ReadByte(); + var index = reader.ReadInt16(); + var cardCode = reader.ReadUInt32(); + var targetCode = reader.ReadUInt32(); + var corpusKey = UnicodeCodec.ReadFixed(reader, DialogueLine.KeyChars); + var eventKey = UnicodeCodec.ReadFixed(reader, DialogueLine.KeyChars); + return new DialogueLine(version, (flags & TargetFaceDownFlag) != 0, index, cardCode, targetCode, corpusKey, eventKey); + } + } + + public sealed class SeatPlanCodec : ICtosCodec + { + public const int Size = SeatPlan.IdBytes + 4 + 2 + 1 + SeatPlan.MaxSeats + SeatPlan.MaxSeats * SeatPlan.IdBytes; + + public CtosMessage Id => CtosMessage.SeatPlan; + + public void Write(BinaryWriter writer, SeatPlan payload) + { + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write(payload.DeadlineMs); + writer.Write(payload.Revision); + writer.Write(payload.SeatCount); + for (var i = 0; i < SeatPlan.MaxSeats; i++) + writer.Write((byte)payload.Kind(i)); + for (var i = 0; i < SeatPlan.MaxSeats; i++) + writer.Write(SeatIds.Fixed(payload.Tokens?[i])); + } + + public SeatPlan Read(BinaryReader reader) + { + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var deadline = reader.ReadUInt32(); + var revision = reader.ReadUInt16(); + var count = reader.ReadByte(); + var kinds = new SeatPlanKind[SeatPlan.MaxSeats]; + for (var i = 0; i < kinds.Length; i++) + kinds[i] = (SeatPlanKind)reader.ReadByte(); + var tokens = new byte[SeatPlan.MaxSeats][]; + for (var i = 0; i < tokens.Length; i++) + tokens[i] = reader.ReadBytes(SeatPlan.IdBytes); + return new SeatPlan(restartId, deadline, revision, count, kinds, tokens); + } + } + + public sealed class SeatRequestCodec : ICtosCodec + { + public const int Size = 2 + SeatPlan.IdBytes + 1 + SeatPlan.IdBytes; + + public CtosMessage Id => CtosMessage.SeatRequest; + + public void Write(BinaryWriter writer, SeatRequest payload) + { + writer.Write(payload.Protocol); + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write(payload.Seat); + writer.Write(SeatIds.Fixed(payload.Token)); + } + + public SeatRequest Read(BinaryReader reader) + { + var protocol = reader.ReadUInt16(); + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var seat = reader.ReadByte(); + return new SeatRequest(protocol, restartId, seat, reader.ReadBytes(SeatPlan.IdBytes)); + } + } + + public sealed class SeatSwapCodec : ICtosCodec + { + public const int Size = 2; + + public CtosMessage Id => CtosMessage.SeatSwap; + + public void Write(BinaryWriter writer, SeatSwap payload) + { + writer.Write(payload.First); + writer.Write(payload.Second); + } + + public SeatSwap Read(BinaryReader reader) => new SeatSwap(reader.ReadByte(), reader.ReadByte()); + } + + public sealed class SeatMoveCodec : ICtosCodec + { + public const int Size = 2; + + public CtosMessage Id => CtosMessage.SeatMove; + + public void Write(BinaryWriter writer, SeatMove payload) + { + writer.Write(payload.From); + writer.Write(payload.To); + } + + public SeatMove Read(BinaryReader reader) => new SeatMove(reader.ReadByte(), reader.ReadByte()); + } + + public sealed class SeatStateCodec : ICtosCodec + { + public const int Size = 4; + public const int StampedSize = Size + StampedCodec.SeatBytes; + + public CtosMessage Id => CtosMessage.SeatState; + + public void Write(BinaryWriter writer, SeatState payload) + { + writer.Write(payload.Version); + writer.Write((byte)payload.Kind); + writer.Write(payload.Value); + } + + public SeatState Read(BinaryReader reader) + { + var version = reader.ReadByte(); + var kind = (SeatStateKind)reader.ReadByte(); + return new SeatState(version, kind, reader.ReadUInt16()); + } + } + + public sealed class ProfileCodec : ICtosCodec + { + public const int Size = 1 + 1 + (ProfileState.AvatarIdChars + ProfileState.FrameIdChars) * 2; + public const int StampedSize = Size + StampedCodec.SeatBytes; + + public CtosMessage Id => CtosMessage.Profile; + + public void Write(BinaryWriter writer, ProfileState payload) + { + writer.Write(payload.Version); + writer.Write((byte)0); + UnicodeCodec.WriteFixed(writer, payload.AvatarId, ProfileState.AvatarIdChars); + UnicodeCodec.WriteFixed(writer, payload.FrameId, ProfileState.FrameIdChars); + } + + public ProfileState Read(BinaryReader reader) + { + var version = reader.ReadByte(); + reader.ReadByte(); + var avatarId = UnicodeCodec.ReadFixed(reader, ProfileState.AvatarIdChars); + var frameId = UnicodeCodec.ReadFixed(reader, ProfileState.FrameIdChars); + return new ProfileState(version, avatarId, frameId); + } + } + + // Version, count, then count x 4 bytes (patch 0023). + public sealed class AttackPreviewQueryCodec : ICtosCodec + { + public const int HeaderSize = 2; + + public CtosMessage Id => CtosMessage.AttackPreview; + + public void Write(BinaryWriter writer, AttackPreviewQuery payload) + { + var count = payload.Pairs.Length > AttackPreviewQuery.MaxPairs ? AttackPreviewQuery.MaxPairs : payload.Pairs.Length; + writer.Write(payload.Version); + writer.Write((byte)count); + for (var i = 0; i < count; i++) + WritePair(writer, payload.Pairs[i]); + } + + public AttackPreviewQuery Read(BinaryReader reader) + { + var version = reader.ReadByte(); + int count = reader.ReadByte(); + var pairs = new AttackPreviewPair[count]; + for (var i = 0; i < count; i++) + pairs[i] = ReadPair(reader); + return new AttackPreviewQuery(version, pairs); + } + + public static void WritePair(BinaryWriter writer, AttackPreviewPair pair) + { + writer.Write(pair.AttackerLocation); + writer.Write(pair.AttackerSequence); + writer.Write(pair.TargetLocation); + writer.Write(pair.TargetSequence); + } + + public static AttackPreviewPair ReadPair(BinaryReader reader) + { + return new AttackPreviewPair(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte()); + } + } + + public sealed class RestartPrepareCodec : ICtosCodec + { + public const int Size = SeatPlan.IdBytes + 4 + 1 + SeatPlan.MaxSeats * SeatPlan.IdBytes + SeatPlan.IdBytes; + + public CtosMessage Id => CtosMessage.RestartPrepare; + + public void Write(BinaryWriter writer, RestartPrepare payload) + { + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write(payload.TimeoutMs); + writer.Write(payload.SeatCount); + for (var i = 0; i < SeatPlan.MaxSeats; i++) + writer.Write(SeatIds.Fixed(payload.SeatTokens?[i])); + writer.Write(SeatIds.Fixed(payload.ObserverToken)); + } + + public RestartPrepare Read(BinaryReader reader) + { + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var timeout = reader.ReadUInt32(); + var count = reader.ReadByte(); + var tokens = new byte[SeatPlan.MaxSeats][]; + for (var i = 0; i < tokens.Length; i++) + tokens[i] = reader.ReadBytes(SeatPlan.IdBytes); + return new RestartPrepare(restartId, timeout, count, tokens, reader.ReadBytes(SeatPlan.IdBytes)); + } + } + + public sealed class RestartAckCodec : ICtosCodec + { + public const int Size = SeatPlan.IdBytes + 1; + + public CtosMessage Id => CtosMessage.RestartAck; + + public void Write(BinaryWriter writer, RestartAck payload) + { + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write((byte)payload.Phase); + } + + public RestartAck Read(BinaryReader reader) => new RestartAck(reader.ReadBytes(SeatPlan.IdBytes), (RestartPhase)reader.ReadByte()); + } + + public sealed class RestartControlCodec : ICtosCodec + { + public const int Size = SeatPlan.IdBytes + 1; + + public CtosMessage Id => CtosMessage.RestartControl; + + public void Write(BinaryWriter writer, RestartControl payload) + { + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write((byte)payload.Action); + } + + public RestartControl Read(BinaryReader reader) => new RestartControl(reader.ReadBytes(SeatPlan.IdBytes), (RestartPhase)reader.ReadByte()); + } + + public sealed class SeatResumeCodec : ICtosCodec + { + public const int Size = SeatPlan.IdBytes + 2; + + public CtosMessage Id => CtosMessage.SeatResume; + + public void Write(BinaryWriter writer, SeatResume payload) + { + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write((byte)payload.Action); + writer.Write(payload.Reason); + } + + public SeatResume Read(BinaryReader reader) + => new SeatResume(reader.ReadBytes(SeatPlan.IdBytes), (SeatResumeAction)reader.ReadByte(), reader.ReadByte()); + } + + public sealed class RestartOpenCodec : ICtosCodec + { + public const int Size = SeatPlan.IdBytes * 2; + + public CtosMessage Id => CtosMessage.RestartOpen; + + public void Write(BinaryWriter writer, RestartOpen payload) + { + writer.Write(SeatIds.Fixed(payload.RestartId)); + writer.Write(SeatIds.Fixed(payload.ObserverToken)); + } + + public RestartOpen Read(BinaryReader reader) => new RestartOpen(reader.ReadBytes(SeatPlan.IdBytes), reader.ReadBytes(SeatPlan.IdBytes)); + } + + // STOC 0x54: uint16 sender (0xFF) + phase, restart id, the receiver's own seat, its token (Prepare only), timeout. + public sealed class RoomRestartingCodec : IStocCodec> + { + public const int PayloadSize = 1 + SeatPlan.IdBytes + 1 + SeatPlan.IdBytes + 4; + public const int Size = StampedCodec.SeatBytes + PayloadSize; + + public StocMessage Id => StocMessage.RoomRestarting; + + public Stamped Read(BinaryReader reader) + { + StocCodecs.Require(reader, Size, Id); + var seat = reader.ReadUInt16(); + var phase = (RestartPhase)reader.ReadByte(); + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var own = reader.ReadByte(); + var token = reader.ReadBytes(SeatPlan.IdBytes); + return new Stamped(seat, new RoomRestarting(phase, restartId, own, token, reader.ReadUInt32())); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + writer.Write((byte)payload.Payload.Phase); + writer.Write(SeatIds.Fixed(payload.Payload.RestartId)); + writer.Write(payload.Payload.Seat); + writer.Write(SeatIds.Fixed(payload.Payload.Token)); + writer.Write(payload.Payload.TimeoutMs); + } + } + + // STOC 0x56, host only: uint16 sender (0xFF) + phase, restart id, acked / expected counts, complete flag, reason. + public sealed class RestartStatusCodec : IStocCodec> + { + public const int PayloadSize = 1 + SeatPlan.IdBytes + 4; + public const int Size = StampedCodec.SeatBytes + PayloadSize; + + public StocMessage Id => StocMessage.RestartStatus; + + public Stamped Read(BinaryReader reader) + { + StocCodecs.Require(reader, Size, Id); + var seat = reader.ReadUInt16(); + var phase = (RestartPhase)reader.ReadByte(); + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var acked = reader.ReadByte(); + var expected = reader.ReadByte(); + var complete = reader.ReadByte() != 0; + return new Stamped(seat, new RestartStatus(phase, restartId, acked, expected, complete, (RestartReason)reader.ReadByte())); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + writer.Write((byte)payload.Payload.Phase); + writer.Write(SeatIds.Fixed(payload.Payload.RestartId)); + writer.Write(payload.Payload.Acked); + writer.Write(payload.Payload.Expected); + writer.Write((byte)(payload.Payload.Complete ? 1 : 0)); + writer.Write((byte)payload.Payload.Reason); + } + } + + // STOC 0x57, to the claimant: uint16 sender (0xFF) + restart id, accepted, seat, reason. + public sealed class SeatResumeResultCodec : IStocCodec> + { + public const int PayloadSize = SeatPlan.IdBytes + 3; + public const int Size = StampedCodec.SeatBytes + PayloadSize; + + public StocMessage Id => StocMessage.SeatResumeResult; + + public Stamped Read(BinaryReader reader) + { + StocCodecs.Require(reader, Size, Id); + var seat = reader.ReadUInt16(); + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var accepted = reader.ReadByte() != 0; + var own = reader.ReadByte(); + return new Stamped(seat, new SeatResumeResult(restartId, accepted, own, reader.ReadByte())); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + writer.Write(SeatIds.Fixed(payload.Payload.RestartId)); + writer.Write((byte)(payload.Payload.Accepted ? 1 : 0)); + writer.Write(payload.Payload.Seat); + writer.Write(payload.Payload.Reason); + } + } + + // STOC 0x58, to the bootstrap host: uint16 sender (0xFF) + restart id, opened. + public sealed class RestartOpenedCodec : IStocCodec> + { + public const int PayloadSize = SeatPlan.IdBytes + 1; + public const int Size = StampedCodec.SeatBytes + PayloadSize; + + public StocMessage Id => StocMessage.RestartOpen; + + public Stamped Read(BinaryReader reader) + { + StocCodecs.Require(reader, Size, Id); + var seat = reader.ReadUInt16(); + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + return new Stamped(seat, new RestartOpened(restartId, reader.ReadByte() != 0)); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + writer.Write(SeatIds.Fixed(payload.Payload.RestartId)); + writer.Write((byte)(payload.Payload.Opened ? 1 : 0)); + } + } + + // uint16 sender (0xFF) + version, seat count, occupied per seat (patch 0014). + public sealed class MatchOverCodec : IStocCodec> + { + public const int PayloadSize = 2 + MatchOver.MaxSeats; + public const int Size = StampedCodec.SeatBytes + PayloadSize; + + public StocMessage Id => StocMessage.MatchOver; + + public Stamped Read(BinaryReader reader) + { + StocCodecs.Require(reader, Size, Id); + var seat = reader.ReadUInt16(); + var version = reader.ReadByte(); + var seatCount = reader.ReadByte(); + var occupied = new bool[MatchOver.MaxSeats]; + for (var i = 0; i < MatchOver.MaxSeats; i++) + occupied[i] = reader.ReadByte() != 0; + return new Stamped(seat, new MatchOver(version, seatCount, occupied)); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + writer.Write(payload.Payload.Version); + writer.Write(payload.Payload.SeatCount); + for (var i = 0; i < MatchOver.MaxSeats; i++) + writer.Write((byte)(payload.Payload.Occupied(i) ? 1 : 0)); + } + } + + // The server's echo: uint16 sender (0xFF) + restart id, revision, seat count and kinds; never tokens. + public sealed class SeatPlanStateCodec : IStocCodec> + { + public const int PayloadSize = SeatPlan.IdBytes + 2 + 1 + SeatPlan.MaxSeats; + public const int Size = StampedCodec.SeatBytes + PayloadSize; + + public StocMessage Id => StocMessage.SeatPlan; + + public Stamped Read(BinaryReader reader) + { + var remaining = StocCodecs.Remaining(reader); + if (remaining < Size) + throw new EndOfStreamException("STOC " + Id + ": " + remaining + " bytes, expected " + Size); + var seat = reader.ReadUInt16(); + var restartId = reader.ReadBytes(SeatPlan.IdBytes); + var revision = reader.ReadUInt16(); + var count = reader.ReadByte(); + var kinds = new SeatPlanKind[SeatPlan.MaxSeats]; + for (var i = 0; i < kinds.Length; i++) + kinds[i] = (SeatPlanKind)reader.ReadByte(); + return new Stamped(seat, new SeatPlan(restartId, 0, revision, count, kinds, null)); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + writer.Write(SeatIds.Fixed(payload.Payload.RestartId)); + writer.Write(payload.Payload.Revision); + writer.Write(payload.Payload.SeatCount); + for (var i = 0; i < SeatPlan.MaxSeats; i++) + writer.Write((byte)payload.Payload.Kind(i)); + } + } + + // Version, count, then count x (the 4 request bytes echoed + 24 answer bytes); no sender stamp (patch 0023). + public sealed class AttackPreviewResultCodec : IStocCodec + { + public const int HeaderSize = 2; + + public StocMessage Id => StocMessage.AttackPreview; + + public AttackPreviewResult Read(BinaryReader reader) + { + StocCodecs.Require(reader, HeaderSize, Id); + var version = reader.ReadByte(); + int count = reader.ReadByte(); + StocCodecs.Require(reader, count * AttackPreviewEntry.Size, Id); + var entries = new AttackPreviewEntry[count]; + for (var i = 0; i < count; i++) + { + var pair = AttackPreviewQueryCodec.ReadPair(reader); + entries[i] = new AttackPreviewEntry(pair, reader.ReadBytes(AttackPreviewEntry.AnswerBytes)); + } + return new AttackPreviewResult(version, entries); + } + + public void Write(BinaryWriter writer, AttackPreviewResult payload) + { + var count = payload.Entries.Length > AttackPreviewQuery.MaxPairs ? AttackPreviewQuery.MaxPairs : payload.Entries.Length; + writer.Write(payload.Version); + writer.Write((byte)count); + for (var i = 0; i < count; i++) + { + AttackPreviewQueryCodec.WritePair(writer, payload.Entries[i].Pair); + writer.Write(payload.Entries[i].Answer, 0, AttackPreviewEntry.AnswerBytes); + } + } + } + + public static class StampedCodec + { + public const int SeatBytes = 2; + } + + // The server prefixes a relayed feature message with the sender's seat (uint16); the payload is the CTOS bytes. + public sealed class StampedCodec : IStocCodec> + { + private readonly ICtosCodec _payload; + + public StocMessage Id { get; } + public int Size { get; } + + public StampedCodec(StocMessage id, ICtosCodec payload, int payloadSize) + { + Id = id; + _payload = payload; + Size = StampedCodec.SeatBytes + payloadSize; + } + + public Stamped Read(BinaryReader reader) + { + var remaining = StocCodecs.Remaining(reader); + if (remaining < Size) + throw new EndOfStreamException("STOC " + Id + ": " + remaining + " bytes, expected " + Size); + var seat = reader.ReadUInt16(); + return new Stamped(seat, _payload.Read(reader)); + } + + public void Write(BinaryWriter writer, Stamped payload) + { + writer.Write((ushort)payload.Seat); + _payload.Write(writer, payload.Payload); + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Codecs/LobbyCodecs.cs b/binding/YGOLegacy.Engine/Protocol/Codecs/LobbyCodecs.cs new file mode 100644 index 0000000..6c55197 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Codecs/LobbyCodecs.cs @@ -0,0 +1,205 @@ +using System.Collections.Generic; +using System.IO; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Codecs +{ + public interface ICtosCodec + { + CtosMessage Id { get; } + void Write(BinaryWriter writer, T payload); + T Read(BinaryReader reader); + } + + public static class CtosPacket + { + public static BinaryWriter Begin(CtosMessage id) + { + var writer = new BinaryWriter(new MemoryStream()); + writer.Write((byte)id); + return writer; + } + } + + public sealed class EmptyPayloadCodec : ICtosCodec + { + public CtosMessage Id { get; } + + public EmptyPayloadCodec(CtosMessage id) + { + Id = id; + } + + public void Write(BinaryWriter writer) + { + } + + public void Write(BinaryWriter writer, NoPayload payload) + { + } + + public NoPayload Read(BinaryReader reader) + { + return default(NoPayload); + } + } + + public static class LobbyCodecs + { + public const int NameChars = 20; + public const int PasswordChars = 20; + public const int HostChars = 256; + public const int ChatChars = 256; + + public static readonly ExternalAddressCodec ExternalAddress = new ExternalAddressCodec(); + public static readonly PlayerInfoCodec PlayerInfo = new PlayerInfoCodec(); + public static readonly JoinGameCodec JoinGame = new JoinGameCodec(); + public static readonly UpdateDeckCodec UpdateDeck = new UpdateDeckCodec(); + public static readonly ChatCodec Chat = new ChatCodec(); + public static readonly KickCodec HsKick = new KickCodec(); + public static readonly EmptyPayloadCodec LeaveGame = new EmptyPayloadCodec(CtosMessage.LeaveGame); + public static readonly EmptyPayloadCodec HsToDuelist = new EmptyPayloadCodec(CtosMessage.HsToDuelist); + public static readonly EmptyPayloadCodec HsToObserver = new EmptyPayloadCodec(CtosMessage.HsToObserver); + public static readonly EmptyPayloadCodec HsReady = new EmptyPayloadCodec(CtosMessage.HsReady); + public static readonly EmptyPayloadCodec HsNotReady = new EmptyPayloadCodec(CtosMessage.HsNotReady); + public static readonly EmptyPayloadCodec HsStart = new EmptyPayloadCodec(CtosMessage.HsStart); + public static readonly CapabilityCodec Capability = new CapabilityCodec(); + public static readonly AppearanceCodec Appearance = new AppearanceCodec(); + public static readonly DialogueCodec Dialogue = new DialogueCodec(); + public static readonly SeatPlanCodec SeatPlan = new SeatPlanCodec(); + public static readonly SeatRequestCodec SeatRequest = new SeatRequestCodec(); + public static readonly SeatSwapCodec SeatSwap = new SeatSwapCodec(); + public static readonly SeatMoveCodec SeatMove = new SeatMoveCodec(); + public static readonly RestartPrepareCodec RestartPrepare = new RestartPrepareCodec(); + public static readonly RestartAckCodec RestartAck = new RestartAckCodec(); + public static readonly RestartControlCodec RestartControl = new RestartControlCodec(); + public static readonly SeatResumeCodec SeatResume = new SeatResumeCodec(); + public static readonly RestartOpenCodec RestartOpen = new RestartOpenCodec(); + public static readonly SeatStateCodec SeatState = new SeatStateCodec(); + public static readonly ProfileCodec Profile = new ProfileCodec(); + public static readonly AttackPreviewQueryCodec AttackPreview = new AttackPreviewQueryCodec(); + } + + public sealed class ChatCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.Chat; + + public void Write(BinaryWriter writer, Chat payload) + { + UnicodeCodec.WriteTerminated(writer, payload.Text, LobbyCodecs.ChatChars); + } + + public Chat Read(BinaryReader reader) + { + return new Chat(UnicodeCodec.ReadTerminated(reader, LobbyCodecs.ChatChars)); + } + } + + public sealed class KickCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.HsKick; + + public void Write(BinaryWriter writer, Kick payload) + { + writer.Write(payload.Position); + } + + public Kick Read(BinaryReader reader) + { + return new Kick(reader.ReadByte()); + } + } + + public sealed class ExternalAddressCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.ExternalAddress; + + public void Write(BinaryWriter writer, ExternalAddress payload) + { + writer.Write(0u); + UnicodeCodec.WriteTerminated(writer, payload.Host, LobbyCodecs.HostChars); + } + + public ExternalAddress Read(BinaryReader reader) + { + reader.ReadUInt32(); + return new ExternalAddress(UnicodeCodec.ReadTerminated(reader, LobbyCodecs.HostChars)); + } + } + + public sealed class PlayerInfoCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.PlayerInfo; + + public void Write(BinaryWriter writer, PlayerInfo payload) + { + UnicodeCodec.WriteFixed(writer, payload.Name, LobbyCodecs.NameChars); + } + + public PlayerInfo Read(BinaryReader reader) + { + return new PlayerInfo(UnicodeCodec.ReadFixed(reader, LobbyCodecs.NameChars)); + } + } + + public sealed class JoinGameCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.JoinGame; + + public void Write(BinaryWriter writer, JoinGame payload) + { + writer.Write(payload.Version); + // Struct padding after the uint16 version: both clients have always sent CC CC here. + writer.Write((byte)0xCC); + writer.Write((byte)0xCC); + writer.Write(0u); + UnicodeCodec.WriteFixed(writer, payload.Password, LobbyCodecs.PasswordChars); + } + + public JoinGame Read(BinaryReader reader) + { + var version = reader.ReadUInt16(); + reader.ReadUInt16(); + reader.ReadUInt32(); + return new JoinGame(version, UnicodeCodec.ReadFixed(reader, LobbyCodecs.PasswordChars)); + } + } + + public sealed class UpdateDeckCodec : ICtosCodec + { + public CtosMessage Id => CtosMessage.UpdateDeck; + + public void Write(BinaryWriter writer, UpdateDeck payload) + { + writer.Write(payload.Main.Count + payload.Extra.Count); + writer.Write(payload.Side.Count); + WriteIds(writer, payload.Main); + WriteIds(writer, payload.Extra); + WriteIds(writer, payload.Side); + } + + // The wire carries one main+extra count, so a read cannot split them again. + public UpdateDeck Read(BinaryReader reader) + { + var mainCount = reader.ReadInt32(); + var sideCount = reader.ReadInt32(); + var main = ReadIds(reader, mainCount); + var side = ReadIds(reader, sideCount); + return new UpdateDeck(main, null, side); + } + + private static void WriteIds(BinaryWriter writer, IReadOnlyList ids) + { + for (var i = 0; i < ids.Count; i++) + writer.Write(ids[i]); + } + + private static int[] ReadIds(BinaryReader reader, int count) + { + var ids = new int[count]; + for (var i = 0; i < count; i++) + ids[i] = reader.ReadInt32(); + return ids; + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Codecs/StocCodecs.cs b/binding/YGOLegacy.Engine/Protocol/Codecs/StocCodecs.cs new file mode 100644 index 0000000..48b2de2 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Codecs/StocCodecs.cs @@ -0,0 +1,393 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Codecs +{ + public interface IStocCodec + { + StocMessage Id { get; } + T Read(BinaryReader reader); + void Write(BinaryWriter writer, T payload); + } + + public static class StocCodecs + { + public const int NameChars = 20; + public const int ChatChars = 256; + + public static readonly ErrorMsgCodec ErrorMsg = new ErrorMsgCodec(); + public static readonly HandResultAnnounceCodec HandResult = new HandResultAnnounceCodec(); + public static readonly HostInfoCodec JoinGame = new HostInfoCodec(); + public static readonly TypeChangeCodec TypeChange = new TypeChangeCodec(); + public static readonly TimeLimitCodec TimeLimit = new TimeLimitCodec(); + public static readonly ServerChatCodec Chat = new ServerChatCodec(); + public static readonly PlayerEnterCodec HsPlayerEnter = new PlayerEnterCodec(); + public static readonly PlayerChangeCodec HsPlayerChange = new PlayerChangeCodec(); + public static readonly WatchChangeCodec HsWatchChange = new WatchChangeCodec(); + public static readonly DeckCountCodec DeckCount = new DeckCountCodec(); + public static readonly StampedCodec Capability = new StampedCodec(StocMessage.Capability, LobbyCodecs.Capability, CapabilityCodec.Size); + public static readonly StampedCodec Appearance = new StampedCodec(StocMessage.Appearance, LobbyCodecs.Appearance, AppearanceCodec.Size); + public static readonly StampedCodec Dialogue = new StampedCodec(StocMessage.Dialogue, LobbyCodecs.Dialogue, DialogueCodec.Size); + public static readonly SetupPairsCodec SetupPairs = new SetupPairsCodec(); + public static readonly SeatPlanStateCodec SeatPlan = new SeatPlanStateCodec(); + public static readonly RoomRestartingCodec RoomRestarting = new RoomRestartingCodec(); + public static readonly RestartStatusCodec RestartStatus = new RestartStatusCodec(); + public static readonly SeatResumeResultCodec SeatResumeResult = new SeatResumeResultCodec(); + public static readonly RestartOpenedCodec RestartOpened = new RestartOpenedCodec(); + public static readonly StampedCodec SeatState = new StampedCodec(StocMessage.SeatState, LobbyCodecs.SeatState, SeatStateCodec.Size); + public static readonly MatchOverCodec MatchOver = new MatchOverCodec(); + public static readonly CoinTossCodec CoinToss = new CoinTossCodec(); + public static readonly DeckListCodec DeckList = new DeckListCodec(); + public static readonly StampedCodec Profile = new StampedCodec(StocMessage.Profile, LobbyCodecs.Profile, ProfileCodec.Size); + public static readonly AttackPreviewResultCodec AttackPreview = new AttackPreviewResultCodec(); + + internal static long Remaining(BinaryReader reader) + { + return reader.BaseStream.Length - reader.BaseStream.Position; + } + + internal static void Require(BinaryReader reader, int size, StocMessage id) + { + var remaining = Remaining(reader); + if (remaining < size) + throw new EndOfStreamException("STOC " + id + ": " + remaining + " bytes, expected " + size); + } + + internal static void SkipPadding(BinaryReader reader, int count) + { + var available = Remaining(reader); + if (available <= 0) + return; + reader.ReadBytes(count < available ? count : (int)available); + } + + internal static void WritePadding(BinaryWriter writer, int count) + { + for (var i = 0; i < count; i++) + writer.Write((byte)0); + } + } + + public sealed class ErrorMsgCodec : IStocCodec + { + public StocMessage Id => StocMessage.ErrorMsg; + + public ErrorMsg Read(BinaryReader reader) + { + var msg = reader.ReadByte(); + StocCodecs.SkipPadding(reader, 3); + var code = StocCodecs.Remaining(reader) >= 4 ? reader.ReadInt32() : 0; + return new ErrorMsg(msg, code); + } + + public void Write(BinaryWriter writer, ErrorMsg payload) + { + writer.Write(payload.Msg); + StocCodecs.WritePadding(writer, 3); + writer.Write(payload.Code); + } + } + + public sealed class HandResultAnnounceCodec : IStocCodec + { + public StocMessage Id => StocMessage.HandResult; + + public HandResultAnnounce Read(BinaryReader reader) + { + var first = reader.ReadByte(); + var second = StocCodecs.Remaining(reader) >= 1 ? reader.ReadByte() : (byte)0; + return new HandResultAnnounce(first, second); + } + + public void Write(BinaryWriter writer, HandResultAnnounce payload) + { + writer.Write(payload.First); + writer.Write(payload.Second); + } + } + + // Version, chooser seat, face, choose seconds; no sender stamp (patch 0017). + public sealed class CoinTossCodec : IStocCodec + { + public const int Size = 4; + + public StocMessage Id => StocMessage.CoinToss; + + public CoinTossAnnounce Read(BinaryReader reader) + { + StocCodecs.Require(reader, Size, Id); + return new CoinTossAnnounce(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte()); + } + + public void Write(BinaryWriter writer, CoinTossAnnounce payload) + { + writer.Write(payload.Version); + writer.Write(payload.ChooserSeat); + writer.Write(payload.Face); + writer.Write(payload.ChooseSeconds); + } + } + + // Version, side, kind, uint16 count, then count uint32 codes; no sender stamp (patch 0019). + public sealed class DeckListCodec : IStocCodec + { + public const int HeaderSize = 5; + + public StocMessage Id => StocMessage.DeckList; + + public DeckList Read(BinaryReader reader) + { + StocCodecs.Require(reader, HeaderSize, Id); + var version = reader.ReadByte(); + var side = reader.ReadByte(); + var kind = (DeckListKind)reader.ReadByte(); + int count = reader.ReadUInt16(); + if (count > DeckList.MaxCards) + throw new InvalidDataException("STOC " + Id + ": " + count + " cards, at most " + DeckList.MaxCards); + StocCodecs.Require(reader, count * 4, Id); + var codes = new int[count]; + for (var i = 0; i < count; i++) + codes[i] = (int)reader.ReadUInt32(); + return new DeckList(version, side, kind, codes); + } + + public void Write(BinaryWriter writer, DeckList payload) + { + writer.Write(payload.Version); + writer.Write(payload.Side); + writer.Write((byte)payload.Kind); + writer.Write((ushort)payload.Codes.Length); + foreach (var code in payload.Codes) + writer.Write((uint)code); + } + } + + public sealed class HostInfoCodec : IStocCodec + { + public StocMessage Id => StocMessage.JoinGame; + + public HostInfo Read(BinaryReader reader) + { + var lflist = reader.ReadUInt32(); + var rule = reader.ReadByte(); + var mode = reader.ReadByte(); + var duelRule = reader.ReadByte(); + var noCheckDeck = reader.ReadByte() != 0; + var noShuffleDeck = reader.ReadByte() != 0; + StocCodecs.SkipPadding(reader, 3); + var startLp = reader.ReadInt32(); + var startHand = reader.ReadByte(); + var drawCount = reader.ReadByte(); + var timeLimit = reader.ReadUInt16(); + return new HostInfo(lflist, rule, mode, duelRule, noCheckDeck, noShuffleDeck, startLp, startHand, drawCount, timeLimit); + } + + public void Write(BinaryWriter writer, HostInfo payload) + { + writer.Write(payload.Lflist); + writer.Write(payload.Rule); + writer.Write(payload.Mode); + writer.Write(payload.DuelRule); + writer.Write((byte)(payload.NoCheckDeck ? 1 : 0)); + writer.Write((byte)(payload.NoShuffleDeck ? 1 : 0)); + StocCodecs.WritePadding(writer, 3); + writer.Write(payload.StartLp); + writer.Write(payload.StartHand); + writer.Write(payload.DrawCount); + writer.Write(payload.TimeLimit); + } + } + + public sealed class TypeChangeCodec : IStocCodec + { + public StocMessage Id => StocMessage.TypeChange; + + public TypeChange Read(BinaryReader reader) + { + var type = reader.ReadByte(); + return new TypeChange((byte)(type & 0xF), ((type >> 4) & 0xF) != 0); + } + + public void Write(BinaryWriter writer, TypeChange payload) + { + writer.Write((byte)((payload.Position & 0xF) | (payload.IsHost ? 0x10 : 0))); + } + } + + public sealed class TimeLimitCodec : IStocCodec + { + public StocMessage Id => StocMessage.TimeLimit; + + public TimeLimit Read(BinaryReader reader) + { + var player = reader.ReadByte(); + StocCodecs.SkipPadding(reader, 1); + var leftTime = StocCodecs.Remaining(reader) >= 2 ? reader.ReadUInt16() : (ushort)0; + return new TimeLimit(player, leftTime); + } + + public void Write(BinaryWriter writer, TimeLimit payload) + { + writer.Write(payload.Player); + StocCodecs.WritePadding(writer, 1); + writer.Write(payload.LeftTime); + } + } + + public sealed class ServerChatCodec : IStocCodec + { + public StocMessage Id => StocMessage.Chat; + + public ServerChat Read(BinaryReader reader) + { + var player = reader.ReadUInt16(); + return new ServerChat(player, UnicodeCodec.ReadTerminated(reader, StocCodecs.ChatChars)); + } + + public void Write(BinaryWriter writer, ServerChat payload) + { + writer.Write(payload.Player); + UnicodeCodec.WriteTerminated(writer, payload.Text, StocCodecs.ChatChars); + } + } + + public sealed class PlayerEnterCodec : IStocCodec + { + public StocMessage Id => StocMessage.HsPlayerEnter; + + public PlayerEnter Read(BinaryReader reader) + { + var name = UnicodeCodec.ReadFixed(reader, StocCodecs.NameChars); + var position = StocCodecs.Remaining(reader) >= 1 ? reader.ReadByte() : (byte)0; + return new PlayerEnter(name, position); + } + + public void Write(BinaryWriter writer, PlayerEnter payload) + { + UnicodeCodec.WriteFixed(writer, payload.Name, StocCodecs.NameChars); + writer.Write(payload.Position); + } + } + + public sealed class PlayerChangeCodec : IStocCodec + { + public StocMessage Id => StocMessage.HsPlayerChange; + + public PlayerChange Read(BinaryReader reader) + { + var status = reader.ReadByte(); + return new PlayerChange((byte)((status >> 4) & 0xF), (byte)(status & 0xF)); + } + + public void Write(BinaryWriter writer, PlayerChange payload) + { + writer.Write((byte)((payload.Position << 4) | (payload.State & 0xF))); + } + } + + public sealed class WatchChangeCodec : IStocCodec + { + public StocMessage Id => StocMessage.HsWatchChange; + + public WatchChange Read(BinaryReader reader) + { + return new WatchChange(reader.ReadUInt16()); + } + + public void Write(BinaryWriter writer, WatchChange payload) + { + writer.Write(payload.Count); + } + } + + public sealed class DeckCountCodec : IStocCodec + { + public StocMessage Id => StocMessage.DeckCount; + + public DeckCount Read(BinaryReader reader) + { + return new DeckCount( + reader.ReadInt16(), reader.ReadInt16(), reader.ReadInt16(), + reader.ReadInt16(), reader.ReadInt16(), reader.ReadInt16()); + } + + public void Write(BinaryWriter writer, DeckCount payload) + { + writer.Write(payload.Main0); + writer.Write(payload.Extra0); + writer.Write(payload.Side0); + writer.Write(payload.Main1); + writer.Write(payload.Extra1); + writer.Write(payload.Side1); + } + } + + // Patch 0009: uint16 count, then per pair uint16 length + the ASCII token "key=value", value verbatim. + public sealed class SetupPairsCodec : IStocCodec>> + { + public const int ReplayFlag = 0x40000000; + + public StocMessage Id => StocMessage.SetupPairs; + + public Stamped> Read(BinaryReader reader) + { + var seat = reader.ReadUInt16(); + return new Stamped>(seat, ReadBlock(reader)); + } + + public void Write(BinaryWriter writer, Stamped> payload) + { + writer.Write((ushort)payload.Seat); + WriteBlock(writer, payload.Payload); + } + + public static IReadOnlyList ReadBlock(BinaryReader reader) + { + var count = reader.ReadUInt16(); + var pairs = new List(count); + for (var i = 0; i < count; i++) + { + var length = reader.ReadUInt16(); + var bytes = reader.ReadBytes(length); + if (bytes.Length < length) + throw new EndOfStreamException("setup pair " + i + ": " + bytes.Length + " bytes, expected " + length); + pairs.Add(SetupPair.FromToken(Encoding.ASCII.GetString(bytes))); + } + return pairs; + } + + public static void WriteBlock(BinaryWriter writer, IReadOnlyList pairs) + { + var count = pairs?.Count ?? 0; + writer.Write((ushort)count); + for (var i = 0; i < count; i++) + { + var bytes = Encoding.ASCII.GetBytes(pairs[i].Token); + writer.Write((ushort)bytes.Length); + writer.Write(bytes); + } + } + + // In a replay the block follows a uint32 byte length, at the start of the (decompressed) data. + public static IReadOnlyList ReadReplayBlock(BinaryReader reader) + { + var length = reader.ReadUInt32(); + var bytes = reader.ReadBytes(checked((int)length)); + if (bytes.Length < length) + throw new EndOfStreamException("replay setup pairs: " + bytes.Length + " bytes, expected " + length); + using var block = new BinaryReader(new MemoryStream(bytes)); + return ReadBlock(block); + } + + public static void WriteReplayBlock(BinaryWriter writer, IReadOnlyList pairs) + { + using var stream = new MemoryStream(); + using (var block = new BinaryWriter(stream, Encoding.ASCII, true)) + WriteBlock(block, pairs); + writer.Write((uint)stream.Length); + writer.Write(stream.ToArray()); + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Codecs/UnicodeCodec.cs b/binding/YGOLegacy.Engine/Protocol/Codecs/UnicodeCodec.cs new file mode 100644 index 0000000..60cca3e --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Codecs/UnicodeCodec.cs @@ -0,0 +1,81 @@ +using System.IO; +using System.Text; + +namespace YGOLegacy.Protocol.Codecs +{ + public static class UnicodeCodec + { + public static void WriteFixed(BinaryWriter writer, string text, int chars) + { + if (chars <= 0) + return; + var buffer = new byte[chars * 2]; + Encode(Clip(text, chars - 1), buffer); + writer.Write(buffer); + } + + public static void WriteTerminated(BinaryWriter writer, string text, int maxChars) + { + if (maxChars <= 0) + return; + var kept = Clip(text, maxChars - 1); + var buffer = new byte[(kept.Length + 1) * 2]; + Encode(kept, buffer); + writer.Write(buffer); + } + + public static string ReadFixed(BinaryReader reader, int chars) + { + if (chars <= 0) + return string.Empty; + var buffer = reader.ReadBytes(chars * 2); + var units = buffer.Length / 2; + var text = new char[units]; + for (var i = 0; i < units; i++) + { + var c = (char)(buffer[2 * i] | (buffer[2 * i + 1] << 8)); + if (c == '\0') + return new string(text, 0, i); + text[i] = c; + } + return new string(text); + } + + public static string ReadTerminated(BinaryReader reader, int maxChars) + { + var text = new StringBuilder(); + while (text.Length < maxChars) + { + var pair = reader.ReadBytes(2); + if (pair.Length < 2) + break; + var c = (char)(pair[0] | (pair[1] << 8)); + if (c == '\0') + break; + text.Append(c); + } + return text.ToString(); + } + + private static string Clip(string text, int maxUnits) + { + if (string.IsNullOrEmpty(text) || maxUnits <= 0) + return string.Empty; + if (text.Length <= maxUnits) + return text; + var end = maxUnits; + if (char.IsHighSurrogate(text[end - 1])) + end--; + return text.Substring(0, end); + } + + private static void Encode(string text, byte[] buffer) + { + for (var i = 0; i < text.Length; i++) + { + buffer[2 * i] = (byte)text[i]; + buffer[2 * i + 1] = (byte)(text[i] >> 8); + } + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Contracts/DuelPayloads.cs b/binding/YGOLegacy.Engine/Protocol/Contracts/DuelPayloads.cs new file mode 100644 index 0000000..1c26262 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Contracts/DuelPayloads.cs @@ -0,0 +1,34 @@ +namespace YGOLegacy.Protocol.Contracts +{ + public readonly struct Response + { + private static readonly byte[] None = new byte[0]; + + public byte[] Bytes { get; } + + public Response(byte[] bytes) + { + Bytes = bytes ?? None; + } + } + + public readonly struct HandResult + { + public byte Result { get; } + + public HandResult(byte result) + { + Result = result; + } + } + + public readonly struct TpResult + { + public bool GoFirst { get; } + + public TpResult(bool goFirst) + { + GoFirst = goFirst; + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Contracts/FeaturePayloads.cs b/binding/YGOLegacy.Engine/Protocol/Contracts/FeaturePayloads.cs new file mode 100644 index 0000000..830d589 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Contracts/FeaturePayloads.cs @@ -0,0 +1,615 @@ +using System; + +namespace YGOLegacy.Protocol.Contracts +{ + public static class FeatureFlags + { + public const uint Appearance = 0x1; + public const uint Dialogue = 0x2; + public const uint All = Appearance | Dialogue | SeatPlan | RulesRestart | SeatState | LobbyAfterMatch | CoinToss | DeckList | Profile | AttackPreview; + // Server-only: the host relays setup pairs (0x43); a client never advertises it. + public const uint SetupPairs = 0x4; + // Server: chosen seats (0x50-0x53). Client: it renders the seat plan. + public const uint SeatPlan = 0x8; + // Server: the rules restart (0x54-0x58). Client: it saves its seat on Prepare and rejoins after Commit. + public const uint RulesRestart = 0x10; + // Server: seat state (0x59) stored per seat and replayed to joiners. Client: it shows what a seat is doing. + public const uint SeatState = 0x20; + // Server: a match end returns the room to the lobby and sends MatchOver (0x5A). Client: it hands the connection back to the Room. + public const uint LobbyAfterMatch = 0x40; + // Server: the duel opens with a coin toss (0x5B) and never asks for rock-paper-scissors. Client: it shows the toss. + public const uint CoinToss = 0x80; + // Server: deck lists (0x5C): the owner's remaining cards sorted, observers' real order and submitted Main Deck when Show all is on. Client: the Deck zone panel shows them. + public const uint DeckList = 0x100; + // Server: profile (0x5D) stored per seat and replayed to joiners. Client: it shows a human's avatar. + public const uint Profile = 0x200; + // Server: attack preview (0x5E): the seat whose battle prompt is open asks for its pairs, the host's core answers. Client: it shows the badge. + public const uint AttackPreview = 0x400; + // Client role, not a feature: set only on the room host's own line, so every peer can badge the host's seat. + public const uint RoomHost = 0x80000000; + } + + public readonly struct SetupPair + { + public const int MaxPairs = 64; + public const int MaxTokenBytes = 512; + + public string Key { get; } + public string Value { get; } + + public SetupPair(string key, string value) + { + Key = key ?? string.Empty; + Value = value ?? string.Empty; + } + + public string Token => Key + "=" + Value; + + public static SetupPair FromToken(string token) + { + var cut = token.IndexOf('='); + return cut < 0 ? new SetupPair(token, string.Empty) : new SetupPair(token.Substring(0, cut), token.Substring(cut + 1)); + } + } + + public readonly struct Capability + { + public const ushort ProtocolVersion = 8; + public const int ServerSender = 0xFF; + + public ushort Protocol { get; } + public uint Flags { get; } + + public Capability(ushort protocol, uint flags) + { + Protocol = protocol; + Flags = flags; + } + + public bool Has(uint flag) + { + return (Flags & flag) == flag; + } + } + + public readonly struct AppearanceState + { + public const int ItemCount = 8; + public const int DeckNameChars = 48; + public const int CharacterIdChars = 64; + public const int DeckGroupChars = 48; + + // Case, Protector, Field, Grave, Stand, Mate, Face, Frame: OnlineAppearanceSync's order. + public int[] Items { get; } + public string DeckName { get; } + public string CharacterId { get; } + public string DeckGroup { get; } + + public AppearanceState(int[] items, string deckName, string characterId, string deckGroup) + { + var copy = new int[ItemCount]; + if (items != null) + Array.Copy(items, copy, Math.Min(items.Length, ItemCount)); + Items = copy; + DeckName = deckName ?? string.Empty; + CharacterId = characterId ?? string.Empty; + DeckGroup = deckGroup ?? string.Empty; + } + } + + // CTOS/STOC 0x5D (patch 0020): a seated human's avatar id and frame id, as the sender wrote them; a receiver sanitizes both. + public readonly struct ProfileState + { + public const byte CurrentVersion = 1; + public const int AvatarIdChars = 32; + public const int FrameIdChars = 16; + + public byte Version { get; } + public string AvatarId { get; } + public string FrameId { get; } + + public ProfileState(string avatarId, string frameId) : this(CurrentVersion, avatarId, frameId) { } + + public ProfileState(byte version, string avatarId, string frameId) + { + Version = version; + AvatarId = avatarId ?? string.Empty; + FrameId = frameId ?? string.Empty; + } + } + + // One attacker x target pair of CTOS/STOC 0x5E (patch 0023), in the asking seat's own zones; target location 0xFF = direct. + public readonly struct AttackPreviewPair + { + public const byte DirectTarget = 0xFF; + public const int Size = 4; + + public byte AttackerLocation { get; } + public byte AttackerSequence { get; } + public byte TargetLocation { get; } + public byte TargetSequence { get; } + + public AttackPreviewPair(byte attackerLocation, byte attackerSequence, byte targetLocation, byte targetSequence) + { + AttackerLocation = attackerLocation; + AttackerSequence = attackerSequence; + TargetLocation = targetLocation; + TargetSequence = targetSequence; + } + + public static AttackPreviewPair Direct(byte attackerLocation, byte attackerSequence) + => new AttackPreviewPair(attackerLocation, attackerSequence, DirectTarget, 0); + + public bool IsDirect => TargetLocation == DirectTarget; + } + + // CTOS 0x5E: every pair of one battle prompt, asked once when the prompt opens. + public readonly struct AttackPreviewQuery + { + public const byte CurrentVersion = 1; + public const int MaxPairs = 255; + + public byte Version { get; } + public AttackPreviewPair[] Pairs { get; } + + public AttackPreviewQuery(AttackPreviewPair[] pairs) : this(CurrentVersion, pairs) { } + + public AttackPreviewQuery(byte version, AttackPreviewPair[] pairs) + { + Version = version; + Pairs = pairs ?? Array.Empty(); + } + } + + // One answered pair: the request echoed and the 24 bytes ygol_preview_attack wrote, undecoded (the duel's service decodes them). + public readonly struct AttackPreviewEntry + { + public const int AnswerBytes = 24; + public const int Size = AttackPreviewPair.Size + AnswerBytes; + + public AttackPreviewPair Pair { get; } + public byte[] Answer { get; } + + public AttackPreviewEntry(AttackPreviewPair pair, byte[] answer) + { + Pair = pair; + var copy = new byte[AnswerBytes]; + if (answer != null) + Array.Copy(answer, copy, Math.Min(answer.Length, AnswerBytes)); + Answer = copy; + } + } + + // STOC 0x5E, to the asking seat only, no sender stamp: a refused pair is left out, never answered with zeros. + public readonly struct AttackPreviewResult + { + public const byte CurrentVersion = 1; + + public byte Version { get; } + public AttackPreviewEntry[] Entries { get; } + + public AttackPreviewResult(AttackPreviewEntry[] entries) : this(CurrentVersion, entries) { } + + public AttackPreviewResult(byte version, AttackPreviewEntry[] entries) + { + Version = version; + Entries = entries ?? Array.Empty(); + } + } + + public readonly struct DialogueLine + { + public const byte CurrentVersion = 1; + public const int KeyChars = 48; + + public byte Version { get; } + public bool TargetFaceDown { get; } + public short Index { get; } + public uint CardCode { get; } + public uint TargetCode { get; } + public string CorpusKey { get; } + public string EventKey { get; } + + public DialogueLine(byte version, bool targetFaceDown, short index, uint cardCode, uint targetCode, + string corpusKey, string eventKey) + { + Version = version; + TargetFaceDown = targetFaceDown; + Index = index; + CardCode = cardCode; + TargetCode = targetCode; + CorpusKey = corpusKey ?? string.Empty; + EventKey = eventKey ?? string.Empty; + } + } + + public enum SeatPlanKind : byte + { + Open = 0, + Cpu = 1, + Reserved = 2, + } + + public enum SeatStateKind : byte + { + None = 0, + PickingDeck = 1, + } + + // What a seated duelist is doing right now; the server keeps one per seat and replays it to joiners after the seat's appearance. + public readonly struct SeatState + { + public const byte CurrentVersion = 1; + + public byte Version { get; } + public SeatStateKind Kind { get; } + // State-specific; 0 for every state today. + public ushort Value { get; } + + public SeatState(SeatStateKind kind, ushort value = 0) : this(CurrentVersion, kind, value) { } + + public SeatState(byte version, SeatStateKind kind, ushort value) + { + Version = version; + Kind = kind; + Value = value; + } + } + + // CTOS from the host carries the claim tokens; the server's STOC echo carries neither tokens nor the deadline. + public readonly struct SeatPlan + { + public const int MaxSeats = 4; + public const int IdBytes = 16; + + public byte[] RestartId { get; } + public uint DeadlineMs { get; } + public ushort Revision { get; } + public byte SeatCount { get; } + public SeatPlanKind[] Kinds { get; } + public byte[][] Tokens { get; } + + public SeatPlan(byte[] restartId, uint deadlineMs, ushort revision, byte seatCount, SeatPlanKind[] kinds, byte[][] tokens) + { + RestartId = SeatIds.Fixed(restartId); + DeadlineMs = deadlineMs; + Revision = revision; + SeatCount = seatCount; + Kinds = new SeatPlanKind[MaxSeats]; + if (kinds != null) + Array.Copy(kinds, Kinds, Math.Min(kinds.Length, MaxSeats)); + Tokens = new byte[MaxSeats][]; + for (var i = 0; i < MaxSeats; i++) + Tokens[i] = SeatIds.Fixed(tokens != null && i < tokens.Length ? tokens[i] : null); + } + + public SeatPlanKind Kind(int seat) => Kinds != null && seat >= 0 && seat < MaxSeats && seat < SeatCount ? Kinds[seat] : SeatPlanKind.Open; + } + + public readonly struct SeatRequest + { + public const byte Observer = 0xFF; + + public ushort Protocol { get; } + public byte[] RestartId { get; } + public byte Seat { get; } + public byte[] Token { get; } + + public SeatRequest(ushort protocol, byte[] restartId, byte seat, byte[] token) + { + Protocol = protocol; + RestartId = SeatIds.Fixed(restartId); + Seat = seat; + Token = SeatIds.Fixed(token); + } + } + + public readonly struct SeatSwap + { + public byte First { get; } + public byte Second { get; } + + public SeatSwap(byte first, byte second) + { + First = first; + Second = second; + } + } + + // From = 0xFF: the sender, as a watcher. To = 0xFF: the watchers. + public readonly struct SeatMove + { + public const byte Watchers = 0xFF; + + public byte From { get; } + public byte To { get; } + + public SeatMove(byte from, byte to) + { + From = from; + To = to; + } + } + + public enum RestartPhase : byte + { + None = 0, + Prepare = 1, + Commit = 2, + Abort = 3, + } + + public enum RestartReason : byte + { + None = 0, + IncompatiblePeer = 1, + AckTimeout = 2, + NotInLobby = 3, + NotHost = 4, + Busy = 5, + } + + public enum SeatResumeAction : byte + { + Complete = 1, + Release = 2, + } + + // Host -> server: one claim token per seat and one for every observer; the server hands each connection only its own. + public readonly struct RestartPrepare + { + public byte[] RestartId { get; } + public uint TimeoutMs { get; } + public byte SeatCount { get; } + public byte[][] SeatTokens { get; } + public byte[] ObserverToken { get; } + + public RestartPrepare(byte[] restartId, uint timeoutMs, byte seatCount, byte[][] seatTokens, byte[] observerToken) + { + RestartId = SeatIds.Fixed(restartId); + TimeoutMs = timeoutMs; + SeatCount = seatCount; + SeatTokens = new byte[SeatPlan.MaxSeats][]; + for (var i = 0; i < SeatPlan.MaxSeats; i++) + SeatTokens[i] = SeatIds.Fixed(seatTokens != null && i < seatTokens.Length ? seatTokens[i] : null); + ObserverToken = SeatIds.Fixed(observerToken); + } + } + + // Server -> one connection: its own seat (0xFF = observer) and, in Prepare only, its own token. + public readonly struct RoomRestarting + { + public RestartPhase Phase { get; } + public byte[] RestartId { get; } + public byte Seat { get; } + public byte[] Token { get; } + public uint TimeoutMs { get; } + + public RoomRestarting(RestartPhase phase, byte[] restartId, byte seat, byte[] token, uint timeoutMs) + { + Phase = phase; + RestartId = SeatIds.Fixed(restartId); + Seat = seat; + Token = SeatIds.Fixed(token); + TimeoutMs = timeoutMs; + } + } + + public readonly struct RestartAck + { + public byte[] RestartId { get; } + public RestartPhase Phase { get; } + + public RestartAck(byte[] restartId, RestartPhase phase) + { + RestartId = SeatIds.Fixed(restartId); + Phase = phase; + } + } + + public readonly struct RestartControl + { + public byte[] RestartId { get; } + public RestartPhase Action { get; } + + public RestartControl(byte[] restartId, RestartPhase action) + { + RestartId = SeatIds.Fixed(restartId); + Action = action; + } + } + + public readonly struct RestartStatus + { + public RestartPhase Phase { get; } + public byte[] RestartId { get; } + public byte Acked { get; } + public byte Expected { get; } + public bool Complete { get; } + public RestartReason Reason { get; } + + public RestartStatus(RestartPhase phase, byte[] restartId, byte acked, byte expected, bool complete, RestartReason reason) + { + Phase = phase; + RestartId = SeatIds.Fixed(restartId); + Acked = acked; + Expected = expected; + Complete = complete; + Reason = reason; + } + } + + public readonly struct SeatResume + { + public byte[] RestartId { get; } + public SeatResumeAction Action { get; } + public byte Reason { get; } + + public SeatResume(byte[] restartId, SeatResumeAction action, byte reason) + { + RestartId = SeatIds.Fixed(restartId); + Action = action; + Reason = reason; + } + } + + public readonly struct SeatResumeResult + { + public byte[] RestartId { get; } + public bool Accepted { get; } + public byte Seat { get; } + public byte Reason { get; } + + public SeatResumeResult(byte[] restartId, bool accepted, byte seat, byte reason) + { + RestartId = SeatIds.Fixed(restartId); + Accepted = accepted; + Seat = seat; + Reason = reason; + } + } + + // Host -> replacement server: the observers' shared claim token, then admission opens. + public readonly struct RestartOpen + { + public byte[] RestartId { get; } + public byte[] ObserverToken { get; } + + public RestartOpen(byte[] restartId, byte[] observerToken) + { + RestartId = SeatIds.Fixed(restartId); + ObserverToken = SeatIds.Fixed(observerToken); + } + } + + public readonly struct RestartOpened + { + public byte[] RestartId { get; } + public bool Opened { get; } + + public RestartOpened(byte[] restartId, bool opened) + { + RestartId = SeatIds.Fixed(restartId); + Opened = opened; + } + } + + // STOC 0x5A, server-stamped: the match ended and the room stayed; the lobby every connection is back in (READY false on every seat). + public readonly struct MatchOver + { + public const byte CurrentVersion = 1; + public const int MaxSeats = 4; + + public byte Version { get; } + public byte SeatCount { get; } + private readonly byte occupied0, occupied1, occupied2, occupied3; + + public MatchOver(byte seatCount, bool[] occupied) : this(CurrentVersion, seatCount, occupied) { } + + public MatchOver(byte version, byte seatCount, bool[] occupied) + { + Version = version; + SeatCount = seatCount; + occupied0 = (byte)(occupied != null && occupied.Length > 0 && occupied[0] ? 1 : 0); + occupied1 = (byte)(occupied != null && occupied.Length > 1 && occupied[1] ? 1 : 0); + occupied2 = (byte)(occupied != null && occupied.Length > 2 && occupied[2] ? 1 : 0); + occupied3 = (byte)(occupied != null && occupied.Length > 3 && occupied[3] ? 1 : 0); + } + + public bool Occupied(int seat) => seat switch { 0 => occupied0 != 0, 1 => occupied1 != 0, 2 => occupied2 != 0, 3 => occupied3 != 0, _ => false }; + } + + // Sorted: the owner's remaining cards by code. Ordered: the real order, top first. Submitted: the Main Deck in the zone, sorted. 1 and 2 reach observers only. + public enum DeckListKind : byte + { + Sorted = 0, + Ordered = 1, + Submitted = 2, + } + + // STOC 0x5C (patch 0019): one deck's contents for the side that owns it; no sender stamp. + public readonly struct DeckList + { + public const byte CurrentVersion = 1; + public const int MaxCards = 250; + + public byte Version { get; } + public byte Side { get; } + public DeckListKind Kind { get; } + public int[] Codes { get; } + + public DeckList(byte side, DeckListKind kind, int[] codes) : this(CurrentVersion, side, kind, codes) { } + + public DeckList(byte version, byte side, DeckListKind kind, int[] codes) + { + Version = version; + Side = side; + Kind = kind; + Codes = codes ?? Array.Empty(); + } + } + + public static class SeatIds + { + public static bool IsZero(byte[] value) + { + if (value == null) + return true; + foreach (var b in value) + if (b != 0) + return false; + return true; + } + + public static bool Same(byte[] a, byte[] b) + { + var x = Fixed(a); + var y = Fixed(b); + for (var i = 0; i < x.Length; i++) + if (x[i] != y[i]) + return false; + return true; + } + + public static byte[] Fixed(byte[] value) + { + var copy = new byte[SeatPlan.IdBytes]; + if (value != null) + Array.Copy(value, copy, Math.Min(value.Length, SeatPlan.IdBytes)); + return copy; + } + + public static byte[] NewToken() + { + var token = new byte[SeatPlan.IdBytes]; + using (var random = System.Security.Cryptography.RandomNumberGenerator.Create()) + random.GetBytes(token); + return token; + } + + public static string ToHex(byte[] value) => BitConverter.ToString(Fixed(value)).Replace("-", string.Empty); + + public static byte[] FromHex(string hex) + { + if (string.IsNullOrEmpty(hex) || hex.Length != SeatPlan.IdBytes * 2) + return null; + var bytes = new byte[SeatPlan.IdBytes]; + for (var i = 0; i < bytes.Length; i++) + if (!byte.TryParse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber, null, out bytes[i])) + return null; + return bytes; + } + } + + public readonly struct Stamped + { + public int Seat { get; } + public T Payload { get; } + + public Stamped(int seat, T payload) + { + Seat = seat; + Payload = payload; + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Contracts/LobbyPayloads.cs b/binding/YGOLegacy.Engine/Protocol/Contracts/LobbyPayloads.cs new file mode 100644 index 0000000..0d46e02 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Contracts/LobbyPayloads.cs @@ -0,0 +1,76 @@ +using System.Collections.Generic; + +namespace YGOLegacy.Protocol.Contracts +{ + public readonly struct ExternalAddress + { + public string Host { get; } + + public ExternalAddress(string host) + { + Host = host ?? string.Empty; + } + } + + public readonly struct PlayerInfo + { + public string Name { get; } + + public PlayerInfo(string name) + { + Name = name ?? string.Empty; + } + } + + public readonly struct JoinGame + { + public ushort Version { get; } + public string Password { get; } + + public JoinGame(ushort version, string password) + { + Version = version; + Password = password ?? string.Empty; + } + } + + public readonly struct Chat + { + public string Text { get; } + + public Chat(string text) + { + Text = text ?? string.Empty; + } + } + + public readonly struct Kick + { + public byte Position { get; } + + public Kick(byte position) + { + Position = position; + } + } + + public readonly struct NoPayload + { + } + + public readonly struct UpdateDeck + { + private static readonly int[] None = new int[0]; + + public IReadOnlyList Main { get; } + public IReadOnlyList Extra { get; } + public IReadOnlyList Side { get; } + + public UpdateDeck(IReadOnlyList main, IReadOnlyList extra, IReadOnlyList side) + { + Main = main ?? None; + Extra = extra ?? None; + Side = side ?? None; + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Contracts/MessageIds.cs b/binding/YGOLegacy.Engine/Protocol/Contracts/MessageIds.cs new file mode 100644 index 0000000..3a39313 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Contracts/MessageIds.cs @@ -0,0 +1,83 @@ +namespace YGOLegacy.Protocol.Contracts +{ + public enum CtosMessage + { + Response = 0x1, + UpdateDeck = 0x2, + HandResult = 0x3, + TpResult = 0x4, + PlayerInfo = 0x10, + CreateGame = 0x11, + JoinGame = 0x12, + LeaveGame = 0x13, + Surrender = 0x14, + TimeConfirm = 0x15, + Chat = 0x16, + ExternalAddress = 0x17, + HsToDuelist = 0x20, + HsToObserver = 0x21, + HsReady = 0x22, + HsNotReady = 0x23, + HsKick = 0x24, + HsStart = 0x25, + RequestField = 0x30, + Capability = 0x40, + Appearance = 0x41, + Dialogue = 0x42, + SeatPlan = 0x50, + SeatRequest = 0x51, + SeatSwap = 0x52, + SeatMove = 0x53, + RestartPrepare = 0x54, + RestartAck = 0x55, + RestartControl = 0x56, + SeatResume = 0x57, + RestartOpen = 0x58, + SeatState = 0x59, + Profile = 0x5D, + AttackPreview = 0x5E + } + + public enum StocMessage + { + GameMsg = 0x1, + ErrorMsg = 0x2, + SelectHand = 0x3, + SelectTp = 0x4, + HandResult = 0x5, + TpResult = 0x6, + ChangeSide = 0x7, + WaitingSide = 0x8, + DeckCount = 0x9, + CreateGame = 0x11, + JoinGame = 0x12, + TypeChange = 0x13, + LeaveGame = 0x14, + DuelStart = 0x15, + DuelEnd = 0x16, + Replay = 0x17, + TimeLimit = 0x18, + Chat = 0x19, + HsPlayerEnter = 0x20, + HsPlayerChange = 0x21, + HsWatchChange = 0x22, + TeammateSurrender = 0x23, + FieldFinish = 0x30, + SrvproRoomList = 0x31, + Capability = 0x40, + Appearance = 0x41, + Dialogue = 0x42, + SetupPairs = 0x43, + SeatPlan = 0x50, + RoomRestarting = 0x54, + RestartStatus = 0x56, + SeatResumeResult = 0x57, + RestartOpen = 0x58, + SeatState = 0x59, + MatchOver = 0x5A, + CoinToss = 0x5B, + DeckList = 0x5C, + Profile = 0x5D, + AttackPreview = 0x5E + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Contracts/StocPayloads.cs b/binding/YGOLegacy.Engine/Protocol/Contracts/StocPayloads.cs new file mode 100644 index 0000000..dc83b3b --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Contracts/StocPayloads.cs @@ -0,0 +1,205 @@ +namespace YGOLegacy.Protocol.Contracts +{ + public readonly struct ErrorMsg + { + public byte Msg { get; } + public int Code { get; } + + public ErrorMsg(byte msg, int code) + { + Msg = msg; + Code = code; + } + } + + public readonly struct HandResultAnnounce + { + public byte First { get; } + public byte Second { get; } + + public HandResultAnnounce(byte first, byte second) + { + First = first; + Second = second; + } + } + + // STOC 0x5B (patch 0017), to every seat and spectator before SELECT_TP: who chooses the turn order and how the coin landed. + public readonly struct CoinTossAnnounce + { + public const byte CurrentVersion = 1; + public const byte Heads = 0; + public const byte Tails = 1; + // No toss: game 2+ of a match, the loser chooses. + public const byte NoFace = 0xFF; + + public byte Version { get; } + public byte ChooserSeat { get; } + public byte Face { get; } + public byte ChooseSeconds { get; } + + public CoinTossAnnounce(byte chooserSeat, byte face, byte chooseSeconds) : this(CurrentVersion, chooserSeat, face, chooseSeconds) { } + + public CoinTossAnnounce(byte version, byte chooserSeat, byte face, byte chooseSeconds) + { + Version = version; + ChooserSeat = chooserSeat; + Face = face; + ChooseSeconds = chooseSeconds; + } + + public bool Tossed => Face != NoFace; + } + + public readonly struct HostInfo + { + public uint Lflist { get; } + public byte Rule { get; } + public byte Mode { get; } + public byte DuelRule { get; } + public bool NoCheckDeck { get; } + public bool NoShuffleDeck { get; } + public int StartLp { get; } + public byte StartHand { get; } + public byte DrawCount { get; } + public ushort TimeLimit { get; } + + public HostInfo(uint lflist, byte rule, byte mode, byte duelRule, bool noCheckDeck, bool noShuffleDeck, + int startLp, byte startHand, byte drawCount, ushort timeLimit) + { + Lflist = lflist; + Rule = rule; + Mode = mode; + DuelRule = duelRule; + NoCheckDeck = noCheckDeck; + NoShuffleDeck = noShuffleDeck; + StartLp = startLp; + StartHand = startHand; + DrawCount = drawCount; + TimeLimit = timeLimit; + } + } + + public readonly struct TypeChange + { + public byte Position { get; } + public bool IsHost { get; } + + public TypeChange(byte position, bool isHost) + { + Position = (byte)(position & 0xF); + IsHost = isHost; + } + } + + public readonly struct TimeLimit + { + public byte Player { get; } + public ushort LeftTime { get; } + + public TimeLimit(byte player, ushort leftTime) + { + Player = player; + LeftTime = leftTime; + } + } + + public readonly struct ServerChat + { + public ushort Player { get; } + public string Text { get; } + + public ServerChat(ushort player, string text) + { + Player = player; + Text = text ?? string.Empty; + } + } + + public readonly struct PlayerEnter + { + public string Name { get; } + public byte Position { get; } + + public PlayerEnter(string name, byte position) + { + Name = name ?? string.Empty; + Position = position; + } + } + + public enum PlayerChangeKind + { + MoveTo, + Observe, + Ready, + NotReady, + Leave, + Unknown + } + + public readonly struct PlayerChange + { + public const byte ObserveState = 0x8; + public const byte ReadyState = 0x9; + public const byte NotReadyState = 0xA; + public const byte LeaveState = 0xB; + + public byte Position { get; } + public byte State { get; } + public PlayerChangeKind Kind { get; } + public byte TargetSeat { get; } + + public PlayerChange(byte position, byte state) + { + Position = (byte)(position & 0xF); + State = (byte)(state & 0xF); + Kind = KindOf(State); + TargetSeat = Kind == PlayerChangeKind.MoveTo ? State : (byte)0; + } + + public static PlayerChangeKind KindOf(byte state) + { + if (state < ObserveState) + return PlayerChangeKind.MoveTo; + switch (state) + { + case ObserveState: return PlayerChangeKind.Observe; + case ReadyState: return PlayerChangeKind.Ready; + case NotReadyState: return PlayerChangeKind.NotReady; + case LeaveState: return PlayerChangeKind.Leave; + default: return PlayerChangeKind.Unknown; + } + } + } + + public readonly struct WatchChange + { + public ushort Count { get; } + + public WatchChange(ushort count) + { + Count = count; + } + } + + public readonly struct DeckCount + { + public short Main0 { get; } + public short Extra0 { get; } + public short Side0 { get; } + public short Main1 { get; } + public short Extra1 { get; } + public short Side1 { get; } + + public DeckCount(short main0, short extra0, short side0, short main1, short extra1, short side1) + { + Main0 = main0; + Extra0 = extra0; + Side0 = side0; + Main1 = main1; + Extra1 = extra1; + Side1 = side1; + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Framing/FrameCodec.cs b/binding/YGOLegacy.Engine/Protocol/Framing/FrameCodec.cs new file mode 100644 index 0000000..ca83469 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Framing/FrameCodec.cs @@ -0,0 +1,116 @@ +using System; +using System.IO; + +namespace YGOLegacy.Protocol.Framing +{ + public static class FrameCodec + { + public const int HeaderSize = 2; + public const int MaxFrame = 0xFFFE; + + public static void Write(BinaryWriter writer, byte id, byte[] payload) + { + var payloadLength = payload == null ? 0 : payload.Length; + WriteHeader(writer, payloadLength + 1); + writer.Write(id); + if (payloadLength > 0) + writer.Write(payload, 0, payloadLength); + } + + public static void Write(BinaryWriter writer, byte[] packet) + { + if (packet == null || packet.Length == 0) + throw new ArgumentException("A frame needs at least the id byte", nameof(packet)); + WriteHeader(writer, packet.Length); + writer.Write(packet, 0, packet.Length); + } + + public static int ReadLength(byte[] header) + { + if (header == null || header.Length < HeaderSize) + throw new ArgumentException("A frame header is two bytes", nameof(header)); + return header[0] | (header[1] << 8); + } + + private static void WriteHeader(BinaryWriter writer, int length) + { + if (length > MaxFrame) + throw new ArgumentException("Frame of " + length + " bytes exceeds the " + MaxFrame + "-byte ceiling"); + writer.Write((byte)length); + writer.Write((byte)(length >> 8)); + } + } + + public sealed class FrameExtractor + { + private byte[] _buffer = new byte[4096]; + private int _start; + private int _count; + + public int DroppedEmpty { get; private set; } + public bool Faulted { get; private set; } + public int Buffered => _count; + + public void Feed(byte[] chunk, int count) + { + if (Faulted || chunk == null || count <= 0) + return; + if (count > chunk.Length) + count = chunk.Length; + Reserve(count); + Array.Copy(chunk, 0, _buffer, _start + _count, count); + _count += count; + } + + public bool TryTake(out byte[] packet) + { + packet = null; + while (!Faulted && _count >= FrameCodec.HeaderSize) + { + var length = _buffer[_start] | (_buffer[_start + 1] << 8); + if (length > FrameCodec.MaxFrame) + { + Faulted = true; + return false; + } + if (length == 0) + { + Consume(FrameCodec.HeaderSize); + DroppedEmpty++; + continue; + } + if (_count < FrameCodec.HeaderSize + length) + return false; + packet = new byte[length]; + Array.Copy(_buffer, _start + FrameCodec.HeaderSize, packet, 0, length); + Consume(FrameCodec.HeaderSize + length); + return true; + } + return false; + } + + private void Consume(int bytes) + { + _start += bytes; + _count -= bytes; + if (_count == 0) + _start = 0; + } + + private void Reserve(int extra) + { + if (_start + _count + extra <= _buffer.Length) + return; + if (_count + extra <= _buffer.Length) + { + Array.Copy(_buffer, _start, _buffer, 0, _count); + _start = 0; + return; + } + var grown = new byte[Math.Max(_buffer.Length * 2, _count + extra)]; + Array.Copy(_buffer, _start, grown, 0, _count); + _buffer = grown; + _start = 0; + } + } +} diff --git a/binding/YGOLegacy.Engine/Protocol/Routing/StocRouter.cs b/binding/YGOLegacy.Engine/Protocol/Routing/StocRouter.cs new file mode 100644 index 0000000..c90be74 --- /dev/null +++ b/binding/YGOLegacy.Engine/Protocol/Routing/StocRouter.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.IO; +using YGOLegacy.Protocol.Contracts; + +namespace YGOLegacy.Protocol.Routing +{ + public enum RouteOutcome + { + Handled, + Ignored, + Unknown, + Empty + } + + public sealed class StocRouter + { + private readonly Dictionary> _handlers = new Dictionary>(); + private readonly HashSet _ignored = new HashSet(); + private readonly HashSet _reported = new HashSet(); + + public Action OnUnknown { get; set; } + + public void Register(StocMessage id, Action handler) + { + if (handler == null) + throw new ArgumentNullException(nameof(handler)); + RequireFree(id); + _handlers.Add(id, handler); + } + + public void Ignore(StocMessage id) + { + RequireFree(id); + _ignored.Add(id); + } + + public bool IsRegistered(StocMessage id) + { + return _handlers.ContainsKey(id) || _ignored.Contains(id); + } + + public RouteOutcome Dispatch(BinaryReader reader, out StocMessage id) + { + if (reader == null) + throw new ArgumentNullException(nameof(reader)); + id = default(StocMessage); + var stream = reader.BaseStream; + if (stream.Position >= stream.Length) + return RouteOutcome.Empty; + id = (StocMessage)reader.ReadByte(); + Action handler; + if (_handlers.TryGetValue(id, out handler)) + { + handler(reader); + return RouteOutcome.Handled; + } + if (_ignored.Contains(id)) + return RouteOutcome.Ignored; + if (_reported.Add(id)) + OnUnknown?.Invoke(id, (int)(stream.Length - stream.Position)); + return RouteOutcome.Unknown; + } + + private void RequireFree(StocMessage id) + { + if (IsRegistered(id)) + throw new ArgumentException("STOC " + id + " already has an owner", nameof(id)); + } + } +} diff --git a/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj b/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj new file mode 100644 index 0000000..9c4bb18 --- /dev/null +++ b/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj @@ -0,0 +1,19 @@ + + + + netstandard2.1 + 9 + true + disable + YGOLegacy.Engine + YGOLegacy.Engine + true + portable + local + 1.0.0.0 + 1.0.0.0 + $(EngineVersion) + false + + + diff --git a/build/Dockerfile b/build/Dockerfile index f30ebeb..01c22b9 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -60,7 +60,7 @@ EOF # defined, no leading underscore: C++ symbols are _Z-mangled; sqlite3_*, lua_*, event_*, ... count, # as they do on Windows), every name declared in contract/ocgapi.h among them, the count exactly # ; then engine.json with protocol and capabilities READ from the server source, never -# typed in. +# typed in, and binding = the version (the C# binding is released with the engine under one tag). COPY <<'EOF' /export-gate #!/usr/bin/env python3 import re, subprocess, sys @@ -86,8 +86,8 @@ capabilities = 0 for n in exprs[0].split('|'): if n not in bits: sys.exit('capability %s has no constexpr uint32_t in gframe/network.h' % n) capabilities |= bits[n] -open(out + '/engine.json', 'w').write('{\n "version": "%s",\n "exports": %d,\n "protocol": %d,\n "capabilities": %d\n}\n' % (version, len(names), protocol, capabilities)) -print('engine.json: version %s, exports %d, protocol %d, capabilities 0x%X' % (version, len(names), protocol, capabilities)) +open(out + '/engine.json', 'w').write('{\n "version": "%s",\n "exports": %d,\n "protocol": %d,\n "capabilities": %d,\n "binding": "%s"\n}\n' % (version, len(names), protocol, capabilities, version)) +print('engine.json: version %s, exports %d, protocol %d, capabilities 0x%X, binding %s' % (version, len(names), protocol, capabilities, version)) EOF # --- sources + gates. obj/ bin/ build/ are wiped so a dirty checkout can never hand the build a stale diff --git a/build/windows.ps1 b/build/windows.ps1 index 08d88a6..cb65097 100644 --- a/build/windows.ps1 +++ b/build/windows.ps1 @@ -16,8 +16,9 @@ verbatim plus the server's YGOSERVER_API lines from gframe\serverapi.h in its marked block; a difference fails the build (the contract is a copy kept honest). After the gate it writes out\win64\engine.json: { version, exports, protocol, - capabilities }, protocol and capabilities READ from gframe\network.h and the - SendServerCapability line of single_duel.cpp / tag_duel.cpp, never typed in. + capabilities, binding }, protocol and capabilities READ from gframe\network.h and + the SendServerCapability line of single_duel.cpp / tag_duel.cpp, never typed in; + binding is the version of the C# binding released with this engine (the same tag). Output: out\win64\ygol-engine.dll (+ .pdb). The export gate is the truth: the script FAILS unless the DLL exports exactly 334 symbols (start_server, @@ -138,6 +139,6 @@ Write-Host "Built: $out" Write-Host "exports: $n (expected $ExpectedExports)" if ($n -ne $ExpectedExports) { throw "export count $n != $ExpectedExports; do NOT ship this build" } -$json = "{`n `"version`": `"$Version`",`n `"exports`": $n,`n `"protocol`": $protocol,`n `"capabilities`": $capabilities`n}`n" +$json = "{`n `"version`": `"$Version`",`n `"exports`": $n,`n `"protocol`": $protocol,`n `"capabilities`": $capabilities,`n `"binding`": `"$Version`"`n}`n" [IO.File]::WriteAllText((Join-Path $outDir "engine.json"), $json, (New-Object Text.UTF8Encoding $false)) -Write-Host "engine.json: version $Version, exports $n, protocol $protocol, capabilities 0x$($capabilities.ToString('X'))" +Write-Host "engine.json: version $Version, exports $n, protocol $protocol, capabilities 0x$($capabilities.ToString('X')), binding $Version"