Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f52eca74ce | ||
|
|
2789a82ef4 | ||
|
|
2344e5dae1 | ||
|
|
c3b5e6e13b | ||
|
|
ffd50fa147 | ||
|
|
7ec61d18e6 | ||
|
|
b8bdb0f20c |
No files matched your search
@@ -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
|
||||
@@ -56,7 +57,7 @@ jobs:
|
||||
git clean -fdx -e out
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
|
||||
- name: Build (contract check, export gate 334, engine.json)
|
||||
- name: Build (contract check, export gate 335, engine.json)
|
||||
id: build
|
||||
run: |
|
||||
$version = "local"
|
||||
@@ -80,11 +81,30 @@ 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:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build (contract check, export gate 855, engine.json)
|
||||
- name: Build (contract check, export gate 856, engine.json)
|
||||
run: |
|
||||
version=local
|
||||
case "$GITHUB_REF" in refs/tags/v*) version="$GITHUB_REF_NAME";; esac
|
||||
@@ -106,7 +126,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build (contract check, export gate 849, engine.json)
|
||||
- name: Build (contract check, export gate 850, engine.json)
|
||||
run: |
|
||||
version=local
|
||||
case "$GITHUB_REF" in refs/tags/v*) version="$GITHUB_REF_NAME";; esac
|
||||
@@ -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)"
|
||||
@@ -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
|
||||
|
||||
+30
-2
@@ -5,9 +5,37 @@ wire protocol, the engine message stream, the setup pairs and the Lua API. A row
|
||||
change first shipped in the Unity repo, the ticket, and the contract part it touched. Rows 0001-0024
|
||||
are the fork patches replayed into this repo as commits (`git log --oneline -- server/gframe core`).
|
||||
|
||||
## Unreleased
|
||||
## v1.2.0 — 2026-10-15
|
||||
|
||||
Nothing yet.
|
||||
Tag partner cards: the waiting teammate's hand, Extra Deck and deck reach that team's two seats. One new
|
||||
export (Windows 335, Linux 856, Android 850), one new message, capability `0x2000`, protocol 9 (capabilities
|
||||
`0x27FF`).
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-15 | `ygol_query_tag_cards(pduel, playerid, out)`: the waiting tag partner's hand, Extra Deck (bit 31 = face-up) and deck codes (sorted) of one side, read only; returns the byte length, 0 when not a tag duel. Core. | TICKET-405 | C API: 1 export |
|
||||
| 2026-10-15 | `STOC_TAG_PARTNER_CARDS` `0x5F` = `u8 side` + the export's bytes, no stamp, to that side's two seats only (never the other team, never an observer): after `start_duel`, after every `MSG_TAG_SWAP`, and in a seated duelist's field resync. `FEATURE_TAG_PARTNER_CARDS` `0x2000` (`0x800` and `0x1000` stay reserved for proposals 44 and 45), protocol 8 -> 9. Server. | TICKET-405 | Wire: STOC `0x5F`, capability bit `0x2000`, protocol 9 |
|
||||
| 2026-10-15 | Binding: `StocMessage.TagPartnerCards`, `FeatureFlags.TagPartnerCards`, the `TagPartnerCards` record + `StocCodecs.TagPartnerCards`, `EngineApi.ygol_query_tag_cards`, `Capability.ProtocolVersion` 9. | TICKET-405 | (e) C# binding |
|
||||
|
||||
## v1.1.1 — 2026-10-15
|
||||
|
||||
A rules fix in the core only. No contract change: same exports, protocol 8, capabilities `0x7FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-15 | Tag duel opening turns: no Battle Phase on turns 1, 2 and 3 (duelists 1A, 2A, 1B); the fourth duelist (2B) is the first who can battle, as the official Tag Duel rules say. Single duels keep turn 1 only. `DUEL_ATTACK_FIRST_TURN` still lifts the block. Core (`field::is_opening_turn_without_bp`, used by the idle command and `Duel.IsAbleToEnterBP`). | - | Rules only; no contract change |
|
||||
|
||||
## v1.1.0 — 2026-10-15
|
||||
|
||||
The C# binding joins the release: `ygol-engine-binding.zip` (`YGOLegacy.Engine.dll` + `.pdb`) beside
|
||||
the five assets of v1.0.0, and `engine.json` names it in `binding`. The native libraries are
|
||||
unchanged in content (same exports, protocol 8, capabilities `0x7FF`); only `ygol_engine_version()`
|
||||
answers the new tag.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-15 | `binding/YGOLegacy.Engine` (`netstandard2.1`) carries the wire protocol, namespaces `YGOLegacy.Protocol.*` unchanged, with its NUnit fixtures; the `windows` job builds and tests it and ships `ygol-engine-binding.zip`; `engine.json` gains `binding`. | TICKET-397 | (e) C# binding: new |
|
||||
| 2026-10-15 | Namespace `YGOLegacy.Engine`: `EngineApi` (all 45 exports of `contract/ocgapi.h`, one typed extern each, header parity test), `MessageScan` (the message-layout scanner, moved from the Unity bot host), `GameMessage` (one enum from the 84 `MSG_*` defines, header parity test), `EngineBinding` (`Version`, `CheckNative()`); contract section (e) written. | TICKET-398 | (e) C# binding: the four types; `engine.json`: `binding` documented |
|
||||
|
||||
## v1.0.0 — 2026-10-15
|
||||
|
||||
|
||||
@@ -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; `EngineApi`, `MessageScan`, `GameMessage`, `EngineBinding`) 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,35 @@ 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, and the namespace `YGOLegacy.Engine`: `EngineApi` (one typed
|
||||
extern per export of `contract/ocgapi.h`, plus the three callback delegates), `MessageScan` (the
|
||||
engine message-layout scanner), `GameMessage` (one enum from the `MSG_*` defines) and
|
||||
`EngineBinding` (`Version` and `CheckNative()`, which throws when the native library's
|
||||
`ygol_engine_version()` is not the binding's version). Unity, the tools and the server repo's
|
||||
card-tester consume this DLL instead of their own copies of the sources and call `CheckNative()`
|
||||
once at start. `binding/YGOLegacy.Engine.Tests/` (`net8.0`, NUnit) holds the fixtures, including the
|
||||
two parity tests that parse the headers; nothing in the tests touches the native library. Contract
|
||||
section (e) documents the DLL.
|
||||
|
||||
```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 +168,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\<tag>\` for the last job to attach. The release token is
|
||||
the run's own `GITHUB_TOKEN`.
|
||||
@@ -154,10 +186,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 }`; `exports` is the Windows count, the rest is identical in every bundle |
|
||||
| `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
|
||||
|
||||
|
||||
@@ -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<BinaryWriter> 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<BinaryWriter> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Engine;
|
||||
|
||||
namespace YGOLegacy.Engine.Tests
|
||||
{
|
||||
internal static class ContractFiles
|
||||
{
|
||||
private const string RepoRoot = "../../../../..";
|
||||
|
||||
public static string OcgApiHeader => Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, RepoRoot, "contract", "ocgapi.h"));
|
||||
public static string CommonHeader => Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, RepoRoot, "core", "common.h"));
|
||||
}
|
||||
|
||||
public class EngineApiParityTests
|
||||
{
|
||||
private static readonly Regex Export = new Regex(@"^\s*(?:OCGCORE_API|YGOSERVER_API)\s+.*?\b(\w+)\s*\(", RegexOptions.Compiled);
|
||||
|
||||
private static List<string> HeaderNames()
|
||||
{
|
||||
return File.ReadLines(ContractFiles.OcgApiHeader)
|
||||
.Select(line => Export.Match(line))
|
||||
.Where(m => m.Success)
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static List<string> ExternNames()
|
||||
{
|
||||
return typeof(EngineApi)
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly)
|
||||
.Where(m => m.GetCustomAttribute<DllImportAttribute>() != null)
|
||||
.Select(m => m.Name)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeaderHas46Exports()
|
||||
{
|
||||
Assert.That(HeaderNames().Count, Is.EqualTo(46));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryHeaderExportHasAnExtern()
|
||||
{
|
||||
var missing = HeaderNames().Except(ExternNames()).ToList();
|
||||
Assert.That(missing, Is.Empty, "header exports without an EngineApi extern");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryExternIsAHeaderExport()
|
||||
{
|
||||
var extra = ExternNames().Except(HeaderNames()).ToList();
|
||||
Assert.That(extra, Is.Empty, "EngineApi externs that are not in contract/ocgapi.h");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryExternIsPublicCdeclOnYgolEngine()
|
||||
{
|
||||
var methods = typeof(EngineApi)
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly)
|
||||
.Where(m => m.GetCustomAttribute<DllImportAttribute>() != null)
|
||||
.ToList();
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var import = method.GetCustomAttribute<DllImportAttribute>();
|
||||
Assert.That(method.IsPublic, method.Name + " is not public");
|
||||
Assert.That(import.Value, Is.EqualTo("ygol-engine"), method.Name);
|
||||
Assert.That(import.CallingConvention, Is.EqualTo(CallingConvention.Cdecl), method.Name);
|
||||
Assert.That(import.EntryPoint, Is.Null.Or.EqualTo(method.Name), method.Name + " renames its entry point");
|
||||
Assert.That(import.CharSet, Is.Not.EqualTo(CharSet.Unicode), method.Name + " uses CharSet.Unicode");
|
||||
}
|
||||
Assert.That(methods.Select(m => m.Name).Distinct().Count(), Is.EqualTo(methods.Count), "an export has an overload");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
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<BinaryWriter> 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<SeatPlan>(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<EndOfStreamException>(() => 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(0x27FB));
|
||||
|
||||
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<MatchOver>(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<EndOfStreamException>(() => 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<EndOfStreamException>(() => StocCodecs.CoinToss.Read(Reader(toss.Take(3).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Profile_Id_Flag_AndSizes_ArePinned_0x5D_0x200_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(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<ProfileState>(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<EndOfStreamException>(() => StocCodecs.Profile.Read(Reader(stamped.Take(99).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AttackPreview_Id_Flag_AndSizes_ArePinned_0x5E_0x400_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(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<EndOfStreamException>(() => StocCodecs.AttackPreview.Read(Reader(answered.Take(29).ToArray())));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.AttackPreview.Read(Reader(new byte[] { 1 })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TagPartnerCards_Id_Flag_Protocol_AndRoundTrip_ArePinned_0x5F_0x2000_9()
|
||||
{
|
||||
Assert.That((int)StocCodecs.TagPartnerCards.Id, Is.EqualTo(0x5F));
|
||||
Assert.That(FeatureFlags.TagPartnerCards, Is.EqualTo(0x2000));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.TagPartnerCards, Is.EqualTo(FeatureFlags.TagPartnerCards));
|
||||
Assert.That(Capability.ProtocolVersion, Is.EqualTo(9));
|
||||
Assert.That(TagPartnerCardsCodec.HeaderSize, Is.EqualTo(7));
|
||||
|
||||
var faceUpPendulum = 0x80000000u | 16178681u;
|
||||
var payload = new TagPartnerCards(1, new uint[] { 89631139u, 46986414u }, new uint[] { faceUpPendulum, 44508094u }, new[] { 10, 20, 30 });
|
||||
var bytes = Bytes(w => StocCodecs.TagPartnerCards.Write(w, payload));
|
||||
Assert.That(bytes.Length, Is.EqualTo(7 + 4 * 7));
|
||||
Assert.That(bytes.Take(7).ToArray(), Is.EqualTo(new byte[] { 1, 1, 2, 2, 0, 3, 0 }));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 7), Is.EqualTo(89631139u));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 15), Is.EqualTo(faceUpPendulum));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 23), Is.EqualTo(10u));
|
||||
|
||||
var read = StocCodecs.TagPartnerCards.Read(Reader(bytes));
|
||||
Assert.That(read.Version, Is.EqualTo(1));
|
||||
Assert.That(read.Side, Is.EqualTo(1));
|
||||
Assert.That(read.Hand, Is.EqualTo(payload.Hand));
|
||||
Assert.That(read.Extra, Is.EqualTo(payload.Extra));
|
||||
Assert.That(read.Deck, Is.EqualTo(payload.Deck));
|
||||
Assert.That(TagPartnerCards.IsFaceUp(read.Extra[0]), Is.True);
|
||||
Assert.That(TagPartnerCards.CodeOf(read.Extra[0]), Is.EqualTo(16178681));
|
||||
Assert.That(TagPartnerCards.IsFaceUp(read.Extra[1]), Is.False);
|
||||
|
||||
var empty = StocCodecs.TagPartnerCards.Read(Reader(new byte[] { 0, 1, 0, 0, 0, 0, 0 }));
|
||||
Assert.That(empty.Side, Is.EqualTo(0));
|
||||
Assert.That(empty.Hand, Is.Empty);
|
||||
Assert.That(empty.Extra, Is.Empty);
|
||||
Assert.That(empty.Deck, Is.Empty);
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.TagPartnerCards.Read(Reader(bytes.Take(bytes.Length - 1).ToArray())));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.TagPartnerCards.Read(Reader(new byte[] { 0, 1, 0 })));
|
||||
Assert.Throws<InvalidDataException>(() => StocCodecs.TagPartnerCards.Read(Reader(new byte[] { 0, 1, 0, 0, 0, 0xFB, 0 })));
|
||||
}
|
||||
|
||||
[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<SeatState>(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<EndOfStreamException>(() => 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<RoomRestarting>(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<EndOfStreamException>(() => StocCodecs.RoomRestarting.Read(Reader(restarting.Take(39).ToArray())));
|
||||
|
||||
var status = Bytes(w => StocCodecs.RestartStatus.Write(w, new Stamped<RestartStatus>(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<SeatResumeResult>(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<RestartOpened>(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<EndOfStreamException>(() => 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<IReadOnlyList<SetupPair>>(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<IReadOnlyList<SetupPair>>(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<EndOfStreamException>(() => 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(9), Le32(0x27FB))));
|
||||
|
||||
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<Capability>(2, new Capability(1, 1))))));
|
||||
Assert.That(seated.Seat, Is.EqualTo(2));
|
||||
Assert.That(seated.Payload.Flags, Is.EqualTo(1));
|
||||
|
||||
Assert.Throws<EndOfStreamException>(() => 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<AppearanceState>(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<EndOfStreamException>(() => 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<DialogueLine>(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<EndOfStreamException>(() => StocCodecs.Dialogue.Read(Reader(bytes.Take(205).ToArray())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<BinaryWriter> 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<byte[]> Drain(FrameExtractor extractor)
|
||||
{
|
||||
var taken = new List<byte[]>();
|
||||
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<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, 0x01, new byte[FrameCodec.MaxFrame])));
|
||||
Assert.Throws<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, new byte[FrameCodec.MaxFrame + 1])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Write_EmptyPacket_Throws()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, new byte[0])));
|
||||
Assert.Throws<ArgumentException>(() => 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<byte[]>();
|
||||
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<byte[]>();
|
||||
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<ArgumentException>(() => FrameCodec.ReadLength(new byte[] { 0x01 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Engine;
|
||||
|
||||
namespace YGOLegacy.Engine.Tests
|
||||
{
|
||||
public class GameMessageParityTests
|
||||
{
|
||||
private static readonly Regex Define = new Regex(@"^#define\s+MSG_([A-Z0-9_]+)\s+(\d+)\b", RegexOptions.Compiled);
|
||||
|
||||
private static string Pascal(string name)
|
||||
{
|
||||
return string.Concat(name.Split('_').Select(p => p.Substring(0, 1).ToUpperInvariant() + p.Substring(1).ToLowerInvariant()));
|
||||
}
|
||||
|
||||
private static Dictionary<string, int> HeaderMessages()
|
||||
{
|
||||
return File.ReadLines(ContractFiles.CommonHeader)
|
||||
.Select(line => Define.Match(line))
|
||||
.Where(m => m.Success)
|
||||
.ToDictionary(m => Pascal(m.Groups[1].Value), m => int.Parse(m.Groups[2].Value));
|
||||
}
|
||||
|
||||
private static Dictionary<string, int> EnumMessages()
|
||||
{
|
||||
return Enum.GetNames(typeof(GameMessage))
|
||||
.ToDictionary(name => name, name => (int)(byte)Enum.Parse(typeof(GameMessage), name));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeaderHas84Messages()
|
||||
{
|
||||
Assert.That(HeaderMessages().Count, Is.EqualTo(84));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryHeaderMessageIsAMember()
|
||||
{
|
||||
var missing = HeaderMessages().Keys.Except(EnumMessages().Keys).ToList();
|
||||
Assert.That(missing, Is.Empty, "MSG_ defines without a GameMessage member");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryMemberIsAHeaderMessage()
|
||||
{
|
||||
var extra = EnumMessages().Keys.Except(HeaderMessages().Keys).ToList();
|
||||
Assert.That(extra, Is.Empty, "GameMessage members that are not a MSG_ define");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryMemberHasTheHeaderValue()
|
||||
{
|
||||
var header = HeaderMessages();
|
||||
var renumbered = EnumMessages()
|
||||
.Where(kv => header.TryGetValue(kv.Key, out var value) && value != kv.Value)
|
||||
.Select(kv => kv.Key + " = " + kv.Value + ", header says " + header[kv.Key])
|
||||
.ToList();
|
||||
Assert.That(renumbered, Is.Empty, "GameMessage members whose value differs from the header");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<BinaryWriter> 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", "TagPartnerCards" });
|
||||
}
|
||||
|
||||
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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<BinaryWriter> 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<ArgumentOutOfRangeException>(() =>
|
||||
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<ArgumentOutOfRangeException>(() => 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<StocMessage>();
|
||||
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<KeyValuePair<StocMessage, int>>();
|
||||
router.OnUnknown = (id, bytes) => reports.Add(new KeyValuePair<StocMessage, int>(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<ArgumentException>(() => router.Register(StocMessage.Chat, r => { }));
|
||||
Assert.Throws<ArgumentException>(() => router.Ignore(StocMessage.Chat));
|
||||
Assert.Throws<ArgumentException>(() => router.Register(StocMessage.DeckCount, r => { }));
|
||||
Assert.Throws<ArgumentException>(() => router.Ignore(StocMessage.DeckCount));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullHandler_Throws()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
Assert.Throws<ArgumentNullException>(() => 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<InvalidDataException>(() => 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<ArgumentNullException>(() => router.Dispatch(null, out read));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<LangVersion>9</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="NUnit" Version="3.14.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\YGOLegacy.Engine\YGOLegacy.Engine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate IntPtr ScriptReader([MarshalAs(UnmanagedType.LPUTF8Str)] string script_name, int* len);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate uint CardReader(uint code, IntPtr data);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate uint MessageHandler(IntPtr pduel, uint msg_type);
|
||||
|
||||
public static unsafe class EngineApi
|
||||
{
|
||||
private const string Library = "ygol-engine";
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_script_reader(ScriptReader f);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_card_reader(CardReader f);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_message_handler(MessageHandler f);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel(uint seed);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel_v2(uint[] seed_sequence);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel_ex(uint seed, uint create_flags);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel_v2_ex(uint[] seed_sequence, uint create_flags);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void start_duel(IntPtr pduel, uint options);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void end_duel(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_player_info(IntPtr pduel, int playerid, int lp, int startcount, int drawcount);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void get_log_message(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_message(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern uint process(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void new_card(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void new_tag_card(IntPtr pduel, uint code, byte owner, byte location);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_card(IntPtr pduel, byte playerid, byte location, byte sequence, uint query_flag, byte[] buf, int use_cache);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_field_count(IntPtr pduel, byte playerid, byte location);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_field_card(IntPtr pduel, byte playerid, byte location, uint query_flag, byte[] buf, int use_cache);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_field_info(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_responsei(IntPtr pduel, int value);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_responseb(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int preload_script(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string script_name);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr default_script_reader([MarshalAs(UnmanagedType.LPUTF8Str)] string script_name, int* len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_preview_attack(IntPtr pduel, byte playerid, byte location, byte sequence, byte target_location, byte target_sequence, byte[] @out);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_query_tag_cards(IntPtr pduel, byte playerid, byte[] @out);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_registry_value(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string key, byte[] out_buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_registry_value(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string key, [MarshalAs(UnmanagedType.LPUTF8Str)] string value);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_registry_keys(IntPtr pduel, byte[] out_buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void clear_registry(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int dump_registry(IntPtr pduel, byte[] out_buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void load_registry(IntPtr pduel, byte[] in_buf, int in_len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_lua_coverage_dump_size(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string name);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int dump_lua_coverage(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, byte[] out_buf, int out_len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_all_lua_coverages_dump_size(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int dump_all_lua_coverages(IntPtr pduel, byte[] out_buf, int out_len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void clear_lua_coverage(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string name);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void clear_all_lua_coverages(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_add(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_move(IntPtr pduel, byte playerid, byte location, byte sequence, byte dst_playerid, byte dst_location, byte dst_sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_remove(IntPtr pduel, byte playerid, byte location, byte sequence);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_set_position(IntPtr pduel, byte playerid, byte location, byte sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_set_lp(IntPtr pduel, byte playerid, int lp);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_reask(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int start_server([MarshalAs(UnmanagedType.LPUTF8Str)] string args);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void stop_server();
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr ygol_engine_version();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
public static partial class EngineBinding
|
||||
{
|
||||
public static string CheckNative()
|
||||
{
|
||||
var native = Marshal.PtrToStringAnsi(EngineApi.ygol_engine_version());
|
||||
if (native == Version) return native;
|
||||
throw new InvalidOperationException(
|
||||
"ygol-engine reports version '" + native + "' but the YGOLegacy.Engine binding is '" + Version
|
||||
+ "'; fetch the engine release whose tag equals the binding version.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
public enum GameMessage : byte
|
||||
{
|
||||
Retry = 1,
|
||||
Hint = 2,
|
||||
Win = 5,
|
||||
UpdateCard = 7,
|
||||
SelectBattlecmd = 10,
|
||||
SelectIdlecmd = 11,
|
||||
SelectEffectyn = 12,
|
||||
SelectYesno = 13,
|
||||
SelectOption = 14,
|
||||
SelectCard = 15,
|
||||
SelectChain = 16,
|
||||
SelectPlace = 18,
|
||||
SelectPosition = 19,
|
||||
SelectTribute = 20,
|
||||
SelectCounter = 22,
|
||||
SelectSum = 23,
|
||||
SelectDisfield = 24,
|
||||
SortCard = 25,
|
||||
SelectUnselectCard = 26,
|
||||
ConfirmDecktop = 30,
|
||||
ConfirmCards = 31,
|
||||
ShuffleDeck = 32,
|
||||
ShuffleHand = 33,
|
||||
SwapGraveDeck = 35,
|
||||
ShuffleSetCard = 36,
|
||||
ReverseDeck = 37,
|
||||
DeckTop = 38,
|
||||
ShuffleExtra = 39,
|
||||
NewTurn = 40,
|
||||
NewPhase = 41,
|
||||
ConfirmExtratop = 42,
|
||||
Move = 50,
|
||||
PosChange = 53,
|
||||
Set = 54,
|
||||
Swap = 55,
|
||||
FieldDisabled = 56,
|
||||
Summoning = 60,
|
||||
Summoned = 61,
|
||||
Spsummoning = 62,
|
||||
Spsummoned = 63,
|
||||
Flipsummoning = 64,
|
||||
Flipsummoned = 65,
|
||||
Chaining = 70,
|
||||
Chained = 71,
|
||||
ChainSolving = 72,
|
||||
ChainSolved = 73,
|
||||
ChainEnd = 74,
|
||||
ChainNegated = 75,
|
||||
ChainDisabled = 76,
|
||||
RandomSelected = 81,
|
||||
BecomeTarget = 83,
|
||||
Draw = 90,
|
||||
Damage = 91,
|
||||
Recover = 92,
|
||||
Equip = 93,
|
||||
Lpupdate = 94,
|
||||
CardTarget = 96,
|
||||
CancelTarget = 97,
|
||||
PayLpcost = 100,
|
||||
AddCounter = 101,
|
||||
RemoveCounter = 102,
|
||||
Attack = 110,
|
||||
Battle = 111,
|
||||
AttackDisabled = 112,
|
||||
DamageStepStart = 113,
|
||||
DamageStepEnd = 114,
|
||||
MissedEffect = 120,
|
||||
TossCoin = 130,
|
||||
TossDice = 131,
|
||||
RockPaperScissors = 132,
|
||||
HandRes = 133,
|
||||
AnnounceRace = 140,
|
||||
AnnounceAttrib = 141,
|
||||
AnnounceCard = 142,
|
||||
AnnounceNumber = 143,
|
||||
CardHint = 160,
|
||||
TagSwap = 161,
|
||||
ReloadField = 162,
|
||||
AiName = 163,
|
||||
ShowHint = 164,
|
||||
PlayerHint = 165,
|
||||
MatchKill = 170,
|
||||
CustomMsg = 180,
|
||||
ResetTime = 221,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System;
|
||||
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
public static class MessageScan
|
||||
{
|
||||
private const int LOCATION_DECK = 0x01;
|
||||
private const int LOCATION_HAND = 0x02;
|
||||
private const int LOCATION_GRAVE = 0x10;
|
||||
private const int LOCATION_OVERLAY = 0x80;
|
||||
private const int POS_FACEDOWN = 0xA;
|
||||
private const int QUERY_CODE = 0x1;
|
||||
private const int QUERY_IS_PUBLIC = 0x100000;
|
||||
|
||||
public struct MsgInfo
|
||||
{
|
||||
public int Player;
|
||||
public bool Prompt;
|
||||
public bool ToPlayerOnly;
|
||||
public bool NewTurn;
|
||||
}
|
||||
|
||||
public static string PromptName(int id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case 10: return "SELECT_BATTLECMD";
|
||||
case 11: return "SELECT_IDLECMD";
|
||||
case 12: return "SELECT_EFFECTYN";
|
||||
case 13: return "SELECT_YESNO";
|
||||
case 14: return "SELECT_OPTION";
|
||||
case 15: return "SELECT_CARD";
|
||||
case 16: return "SELECT_CHAIN";
|
||||
case 18: return "SELECT_PLACE";
|
||||
case 19: return "SELECT_POSITION";
|
||||
case 20: return "SELECT_TRIBUTE";
|
||||
case 22: return "SELECT_COUNTER";
|
||||
case 23: return "SELECT_SUM";
|
||||
case 24: return "SELECT_DISFIELD";
|
||||
case 25: return "SORT_CARD";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
public static MsgInfo Scan(byte[] b, ref int pos, int id, int len)
|
||||
{
|
||||
var info = new MsgInfo();
|
||||
int count;
|
||||
switch (id)
|
||||
{
|
||||
case 1: /* RETRY */ break;
|
||||
case 2: /* HINT */
|
||||
{
|
||||
var type = b[pos];
|
||||
info.Player = b[pos + 1];
|
||||
pos += 6;
|
||||
// ygopro's SingleDuel: HINT_EVENT/MESSAGE/SELECTMSG/EFFECT go
|
||||
// to the hinted player only, the rest is public.
|
||||
info.ToPlayerOnly = type == 1 || type == 2 || type == 3 || type == 5;
|
||||
break;
|
||||
}
|
||||
case 3: /* WAITING */ break;
|
||||
case 4: /* START */ pos += 18; break;
|
||||
case 5: /* WIN */ pos += 2; break;
|
||||
case 8: /* REQUEST_DECK */ break;
|
||||
|
||||
case 10: /* SELECT_BATTLECMD */
|
||||
info.Player = b[pos]; pos += 1;
|
||||
count = b[pos++]; pos += count * 11;
|
||||
count = b[pos++]; pos += count * 8;
|
||||
pos += 2;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 11: /* SELECT_IDLECMD */
|
||||
info.Player = b[pos]; pos += 1;
|
||||
for (var k = 0; k < 5; k++) { count = b[pos++]; pos += count * 7; }
|
||||
count = b[pos++]; pos += count * 11;
|
||||
pos += 3;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 12: /* SELECT_EFFECTYN */ info.Player = b[pos]; pos += 13; info.Prompt = true; break;
|
||||
case 13: /* SELECT_YESNO */ info.Player = b[pos]; pos += 5; info.Prompt = true; break;
|
||||
case 14: /* SELECT_OPTION */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 4;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 15: /* SELECT_CARD */
|
||||
case 20: /* SELECT_TRIBUTE */
|
||||
info.Player = b[pos]; pos += 4; count = b[pos++]; pos += count * 8;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 26: /* SELECT_UNSELECT_CARD */
|
||||
info.Player = b[pos]; pos += 5;
|
||||
count = b[pos++]; pos += count * 8;
|
||||
count = b[pos++]; pos += count * 8;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 16: /* SELECT_CHAIN */
|
||||
info.Player = b[pos]; count = b[pos + 1]; pos += 11 + count * 14;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 18: /* SELECT_PLACE */
|
||||
case 19: /* SELECT_POSITION */
|
||||
case 24: /* SELECT_DISFIELD */
|
||||
info.Player = b[pos]; pos += 6; info.Prompt = true; break;
|
||||
|
||||
case 22: /* SELECT_COUNTER */
|
||||
info.Player = b[pos]; pos += 5; count = b[pos++]; pos += count * 9;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 23: /* SELECT_SUM */
|
||||
info.Player = b[pos + 1]; pos += 8;
|
||||
count = b[pos++]; pos += count * 11;
|
||||
count = b[pos++]; pos += count * 11;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 21: /* SORT_CHAIN */
|
||||
case 25: /* SORT_CARD */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 7;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 30: /* CONFIRM_DECKTOP */
|
||||
case 42: /* CONFIRM_EXTRATOP */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 7; break;
|
||||
|
||||
case 31: /* CONFIRM_CARDS */
|
||||
info.Player = b[pos]; pos += 2; count = b[pos++]; pos += count * 7; break;
|
||||
|
||||
case 32: /* SHUFFLE_DECK */
|
||||
case 34: /* REFRESH_DECK */
|
||||
case 35: /* SWAP_GRAVE_DECK*/
|
||||
info.Player = b[pos]; pos += 1; break;
|
||||
|
||||
case 33: /* SHUFFLE_HAND */
|
||||
case 39: /* SHUFFLE_EXTRA */
|
||||
case 90: /* DRAW */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 4; break;
|
||||
|
||||
case 36: /* SHUFFLE_SET_CARD */
|
||||
pos += 1; count = b[pos++]; pos += count * 8; break;
|
||||
|
||||
case 37: /* REVERSE_DECK */ break;
|
||||
case 38: /* DECK_TOP */ info.Player = b[pos]; pos += 6; break;
|
||||
case 40: /* NEW_TURN */ info.NewTurn = true; pos += 1; break;
|
||||
case 41: /* NEW_PHASE */ pos += 2; break;
|
||||
|
||||
case 50: /* MOVE */ pos += 16; break;
|
||||
case 53: /* POS_CHANGE */ pos += 9; break;
|
||||
case 54: /* SET */ pos += 8; break;
|
||||
case 55: /* SWAP */ pos += 16; break;
|
||||
case 56: /* FIELD_DISABLED */ pos += 4; break;
|
||||
|
||||
case 60: /* SUMMONING */
|
||||
case 62: /* SPSUMMONING */
|
||||
case 64: /* FLIPSUMMONING */ pos += 8; break;
|
||||
case 61: /* SUMMONED */
|
||||
case 63: /* SPSUMMONED */
|
||||
case 65: /* FLIPSUMMONED */ break;
|
||||
|
||||
case 70: /* CHAINING */ pos += 16; break;
|
||||
case 71: /* CHAINED */
|
||||
case 72: /* CHAIN_SOLVING */
|
||||
case 73: /* CHAIN_SOLVED */
|
||||
case 75: /* CHAIN_NEGATED */
|
||||
case 76: /* CHAIN_DISABLED*/ pos += 1; break;
|
||||
case 74: /* CHAIN_END */ break;
|
||||
|
||||
case 80: /* CARD_SELECTED */
|
||||
case 81: /* RANDOM_SELECTED */
|
||||
pos += 1; count = b[pos++]; pos += count * 4; break;
|
||||
case 83: /* BECOME_TARGET */
|
||||
count = b[pos++]; pos += count * 4; break;
|
||||
|
||||
case 91: /* DAMAGE */
|
||||
case 92: /* RECOVER */
|
||||
case 94: /* LP_UPDATE */
|
||||
case 100: /* PAY_LPCOST */ pos += 5; break;
|
||||
case 93: /* EQUIP */ pos += 8; break;
|
||||
case 95: /* UNEQUIP */ pos += 4; break;
|
||||
case 96: /* CARD_TARGET */
|
||||
case 97: /* CANCEL_TARGET */ pos += 8; break;
|
||||
case 101: /* ADD_COUNTER */
|
||||
case 102: /* REMOVE_COUNTER */ pos += 7; break;
|
||||
|
||||
case 110: /* ATTACK */ pos += 8; break;
|
||||
case 111: /* BATTLE */ pos += 26; break;
|
||||
case 112: /* ATTACK_DISABLED */
|
||||
case 113: /* DAMAGE_STEP_START */
|
||||
case 114: /* DAMAGE_STEP_END */ break;
|
||||
|
||||
case 120: /* MISSED_EFFECT */ pos += 8; break;
|
||||
case 121: /* BE_CHAIN_TARGET */
|
||||
case 122: /* CREATE_RELATION */
|
||||
case 123: /* RELEASE_RELATION */ break;
|
||||
|
||||
case 130: /* TOSS_COIN */
|
||||
case 131: /* TOSS_DICE */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count; break;
|
||||
|
||||
case 132: /* ROCK_PAPER_SCISSORS */ info.Player = b[pos]; pos += 1; info.Prompt = true; break;
|
||||
case 133: /* HAND_RES */ pos += 2; break;
|
||||
|
||||
case 140: /* ANNOUNCE_RACE */
|
||||
case 141: /* ANNOUNCE_ATTRIB */
|
||||
info.Player = b[pos]; pos += 6; info.Prompt = true; break;
|
||||
case 142: /* ANNOUNCE_CARD */
|
||||
case 143: /* ANNOUNCE_NUMBER */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 4;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 160: /* CARD_HINT */ pos += 9; break;
|
||||
case 163: /* AI_NAME */
|
||||
case 164: /* SHOW_HINT */
|
||||
{
|
||||
var slen = b[pos] | (b[pos + 1] << 8);
|
||||
pos += 2 + slen + 1; break;
|
||||
}
|
||||
case 165: /* PLAYER_HINT */ pos += 6; break;
|
||||
case 170: /* MATCH_KILL */ pos += 4; break;
|
||||
case 180: /* CUSTOM_MSG */ break;
|
||||
|
||||
case 162: /* RELOAD_FIELD — Debug.ReloadFieldEnd(), so a scripted
|
||||
board (Tools/CardTests) emits it where a duel never does. */
|
||||
{
|
||||
pos += 1; // duel rule
|
||||
for (var side = 0; side < 2; side++)
|
||||
{
|
||||
pos += 4; // life points
|
||||
for (var i = 0; i < 7; i++) if (b[pos++] > 0) pos += 2; // monster zones
|
||||
for (var i = 0; i < 8; i++) if (b[pos++] > 0) pos += 1; // spell/trap zones
|
||||
pos += 6; // deck, hand, grave, banish, extra, extra pendulum counts
|
||||
}
|
||||
// The chain block is written ONCE, after both players. Reading it per
|
||||
// player takes player 1's low LP byte as a chain count and swallows
|
||||
// every message that follows — see the [YGOL] note in CoreWrapper.Analyse.
|
||||
count = b[pos++]; pos += count * 15;
|
||||
break;
|
||||
}
|
||||
|
||||
case 221: /* RESET_TIME */ pos += 3; break;
|
||||
|
||||
default:
|
||||
throw new Exception("unknown core message " + id + " at offset " + (pos - 1) + " of " + len
|
||||
+ " — the host's layout table needs a case for it");
|
||||
}
|
||||
if (pos > len) throw new Exception("core message " + id + " overran its buffer (" + pos + " > " + len + ")");
|
||||
return info;
|
||||
}
|
||||
|
||||
public static byte[] Blank(int id, byte[] msg, MsgInfo info, int recipient)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case 39: // MSG_SHUFFLE_EXTRA: the opponent may not read an extra
|
||||
// deck (RefreshPile hides its codes the same way), so
|
||||
// the new order goes out blank to them.
|
||||
case 33: // MSG_SHUFFLE_HAND: only the owner sees the new order.
|
||||
{
|
||||
if (recipient == info.Player) return msg;
|
||||
var copy = (byte[])msg.Clone();
|
||||
for (var i = 2; i + 4 <= copy.Length; i += 4)
|
||||
copy[i] = copy[i + 1] = copy[i + 2] = copy[i + 3] = 0;
|
||||
return copy;
|
||||
}
|
||||
case 90: // MSG_DRAW: only the drawing player sees what was drawn.
|
||||
{
|
||||
var copy = (byte[])msg.Clone();
|
||||
for (var i = 2; i + 4 <= copy.Length; i += 4)
|
||||
{
|
||||
if (recipient == info.Player)
|
||||
copy[i + 3] &= 0x7f; // strip the "public" bit like Analyse
|
||||
else
|
||||
copy[i] = copy[i + 1] = copy[i + 2] = copy[i + 3] = 0;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
case 50: // MSG_MOVE: a card that lands in a deck/hand (but not a
|
||||
{ // grave or an xyz pile) or lands face-down is hidden —
|
||||
// from the OTHER player only. Its new controller always
|
||||
// sees it: you know the monster you just set. (This is
|
||||
// the one place where ygoserver is per-recipient and
|
||||
// Percy.Ygopro, having a single client, is not.)
|
||||
if (msg.Length < 16) return msg;
|
||||
int cc = msg[8], cl = msg[9], cp = msg[11];
|
||||
if (recipient == cc) return msg;
|
||||
var hidden = ((cl & (LOCATION_GRAVE | LOCATION_OVERLAY)) == 0 && (cl & (LOCATION_DECK | LOCATION_HAND)) != 0)
|
||||
|| (cp & POS_FACEDOWN) != 0;
|
||||
if (!hidden) return msg;
|
||||
var copy = (byte[])msg.Clone();
|
||||
copy[0] = copy[1] = copy[2] = copy[3] = 0;
|
||||
return copy;
|
||||
}
|
||||
case 54: // MSG_SET: the code is never revealed.
|
||||
{
|
||||
if (msg.Length < 4) return msg;
|
||||
var copy = (byte[])msg.Clone();
|
||||
copy[0] = copy[1] = copy[2] = copy[3] = 0;
|
||||
return copy;
|
||||
}
|
||||
default:
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
|
||||
public static void BlankPileCodes(byte[] buf, bool all)
|
||||
{
|
||||
var o = 0;
|
||||
while (o + 8 <= buf.Length)
|
||||
{
|
||||
var recLen = BitConverter.ToInt32(buf, o);
|
||||
if (recLen <= 4 || o + recLen > buf.Length) { o += Math.Max(recLen, 4); continue; }
|
||||
var flag = BitConverter.ToInt32(buf, o + 4);
|
||||
if ((flag & QUERY_CODE) != 0)
|
||||
{
|
||||
var hide = all;
|
||||
if (!hide)
|
||||
{
|
||||
var publicOffset = FieldOffset(buf, o, recLen, flag, QUERY_IS_PUBLIC);
|
||||
hide = publicOffset < 0 || BitConverter.ToInt32(buf, publicOffset) == 0;
|
||||
}
|
||||
if (hide)
|
||||
buf[o + 8] = buf[o + 9] = buf[o + 10] = buf[o + 11] = 0;
|
||||
}
|
||||
o += recLen;
|
||||
}
|
||||
}
|
||||
|
||||
private static int FieldOffset(byte[] buf, int recordStart, int recordLen, int flag, int wanted)
|
||||
{
|
||||
var o = recordStart + 8; // past len + flag
|
||||
var end = recordStart + recordLen;
|
||||
for (var bit = 0x1; bit != 0 && bit <= 0x800000; bit <<= 1)
|
||||
{
|
||||
if ((flag & bit) == 0) continue;
|
||||
if (bit == wanted) return o <= end - 4 ? o : -1;
|
||||
if (o + 4 > end) return -1;
|
||||
switch (bit)
|
||||
{
|
||||
case 0x8000: // TARGET_CARD
|
||||
case 0x10000: // OVERLAY_CARD
|
||||
case 0x20000: // COUNTERS
|
||||
o += 4 + BitConverter.ToInt32(buf, o) * 4;
|
||||
break;
|
||||
case 0x800000: // LINK (count + marker)
|
||||
o += 8;
|
||||
break;
|
||||
default:
|
||||
o += 4;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Response>
|
||||
{
|
||||
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<HandResult>
|
||||
{
|
||||
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<TpResult>
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,600 @@
|
||||
using System.IO;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public sealed class CapabilityCodec : ICtosCodec<Capability>
|
||||
{
|
||||
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<AppearanceState>
|
||||
{
|
||||
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<DialogueLine>
|
||||
{
|
||||
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<SeatPlan>
|
||||
{
|
||||
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<SeatRequest>
|
||||
{
|
||||
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<SeatSwap>
|
||||
{
|
||||
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<SeatMove>
|
||||
{
|
||||
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<SeatState>
|
||||
{
|
||||
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<ProfileState>
|
||||
{
|
||||
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<AttackPreviewQuery>
|
||||
{
|
||||
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<RestartPrepare>
|
||||
{
|
||||
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<RestartAck>
|
||||
{
|
||||
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<RestartControl>
|
||||
{
|
||||
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<SeatResume>
|
||||
{
|
||||
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<RestartOpen>
|
||||
{
|
||||
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<Stamped<RoomRestarting>>
|
||||
{
|
||||
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<RoomRestarting> 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<RoomRestarting>(seat, new RoomRestarting(phase, restartId, own, token, reader.ReadUInt32()));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<RoomRestarting> 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<Stamped<RestartStatus>>
|
||||
{
|
||||
public const int PayloadSize = 1 + SeatPlan.IdBytes + 4;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.RestartStatus;
|
||||
|
||||
public Stamped<RestartStatus> 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<RestartStatus>(seat, new RestartStatus(phase, restartId, acked, expected, complete, (RestartReason)reader.ReadByte()));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<RestartStatus> 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<Stamped<SeatResumeResult>>
|
||||
{
|
||||
public const int PayloadSize = SeatPlan.IdBytes + 3;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.SeatResumeResult;
|
||||
|
||||
public Stamped<SeatResumeResult> 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<SeatResumeResult>(seat, new SeatResumeResult(restartId, accepted, own, reader.ReadByte()));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<SeatResumeResult> 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<Stamped<RestartOpened>>
|
||||
{
|
||||
public const int PayloadSize = SeatPlan.IdBytes + 1;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.RestartOpen;
|
||||
|
||||
public Stamped<RestartOpened> Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var seat = reader.ReadUInt16();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
return new Stamped<RestartOpened>(seat, new RestartOpened(restartId, reader.ReadByte() != 0));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<RestartOpened> 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<Stamped<MatchOver>>
|
||||
{
|
||||
public const int PayloadSize = 2 + MatchOver.MaxSeats;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.MatchOver;
|
||||
|
||||
public Stamped<MatchOver> 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<MatchOver>(seat, new MatchOver(version, seatCount, occupied));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<MatchOver> 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<Stamped<SeatPlan>>
|
||||
{
|
||||
public const int PayloadSize = SeatPlan.IdBytes + 2 + 1 + SeatPlan.MaxSeats;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.SeatPlan;
|
||||
|
||||
public Stamped<SeatPlan> 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<SeatPlan>(seat, new SeatPlan(restartId, 0, revision, count, kinds, null));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<SeatPlan> 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<AttackPreviewResult>
|
||||
{
|
||||
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<T> : IStocCodec<Stamped<T>>
|
||||
{
|
||||
private readonly ICtosCodec<T> _payload;
|
||||
|
||||
public StocMessage Id { get; }
|
||||
public int Size { get; }
|
||||
|
||||
public StampedCodec(StocMessage id, ICtosCodec<T> payload, int payloadSize)
|
||||
{
|
||||
Id = id;
|
||||
_payload = payload;
|
||||
Size = StampedCodec.SeatBytes + payloadSize;
|
||||
}
|
||||
|
||||
public Stamped<T> 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<T>(seat, _payload.Read(reader));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<T> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
_payload.Write(writer, payload.Payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public interface ICtosCodec<T>
|
||||
{
|
||||
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<NoPayload>
|
||||
{
|
||||
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<Chat>
|
||||
{
|
||||
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<Kick>
|
||||
{
|
||||
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<ExternalAddress>
|
||||
{
|
||||
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<PlayerInfo>
|
||||
{
|
||||
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<JoinGame>
|
||||
{
|
||||
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<UpdateDeck>
|
||||
{
|
||||
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<int> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public interface IStocCodec<T>
|
||||
{
|
||||
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<Contracts.Capability> Capability = new StampedCodec<Contracts.Capability>(StocMessage.Capability, LobbyCodecs.Capability, CapabilityCodec.Size);
|
||||
public static readonly StampedCodec<AppearanceState> Appearance = new StampedCodec<AppearanceState>(StocMessage.Appearance, LobbyCodecs.Appearance, AppearanceCodec.Size);
|
||||
public static readonly StampedCodec<DialogueLine> Dialogue = new StampedCodec<DialogueLine>(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> SeatState = new StampedCodec<SeatState>(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<ProfileState> Profile = new StampedCodec<ProfileState>(StocMessage.Profile, LobbyCodecs.Profile, ProfileCodec.Size);
|
||||
public static readonly AttackPreviewResultCodec AttackPreview = new AttackPreviewResultCodec();
|
||||
public static readonly TagPartnerCardsCodec TagPartnerCards = new TagPartnerCardsCodec();
|
||||
|
||||
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<ErrorMsg>
|
||||
{
|
||||
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<HandResultAnnounce>
|
||||
{
|
||||
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<CoinTossAnnounce>
|
||||
{
|
||||
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<DeckList>
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Side, version, hand count, extra count, pad, uint16 deck count, then the hand, extra and deck codes as uint32; no sender stamp (v1.2.0, TICKET-405).
|
||||
public sealed class TagPartnerCardsCodec : IStocCodec<TagPartnerCards>
|
||||
{
|
||||
public const int HeaderSize = 7;
|
||||
|
||||
public StocMessage Id => StocMessage.TagPartnerCards;
|
||||
|
||||
public TagPartnerCards Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, HeaderSize, Id);
|
||||
var side = reader.ReadByte();
|
||||
var version = reader.ReadByte();
|
||||
int handCount = reader.ReadByte();
|
||||
int extraCount = reader.ReadByte();
|
||||
reader.ReadByte();
|
||||
int deckCount = reader.ReadUInt16();
|
||||
if (deckCount > TagPartnerCards.MaxDeckCards)
|
||||
throw new InvalidDataException("STOC " + Id + ": " + deckCount + " deck cards, at most " + TagPartnerCards.MaxDeckCards);
|
||||
StocCodecs.Require(reader, (handCount + extraCount + deckCount) * 4, Id);
|
||||
var hand = new uint[handCount];
|
||||
for (var i = 0; i < handCount; i++)
|
||||
hand[i] = reader.ReadUInt32();
|
||||
var extra = new uint[extraCount];
|
||||
for (var i = 0; i < extraCount; i++)
|
||||
extra[i] = reader.ReadUInt32();
|
||||
var deck = new int[deckCount];
|
||||
for (var i = 0; i < deckCount; i++)
|
||||
deck[i] = (int)reader.ReadUInt32();
|
||||
return new TagPartnerCards(version, side, hand, extra, deck);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, TagPartnerCards payload)
|
||||
{
|
||||
writer.Write(payload.Side);
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)payload.Hand.Length);
|
||||
writer.Write((byte)payload.Extra.Length);
|
||||
writer.Write((byte)0);
|
||||
writer.Write((ushort)payload.Deck.Length);
|
||||
foreach (var raw in payload.Hand)
|
||||
writer.Write(raw);
|
||||
foreach (var raw in payload.Extra)
|
||||
writer.Write(raw);
|
||||
foreach (var code in payload.Deck)
|
||||
writer.Write((uint)code);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class HostInfoCodec : IStocCodec<HostInfo>
|
||||
{
|
||||
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<TypeChange>
|
||||
{
|
||||
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<TimeLimit>
|
||||
{
|
||||
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<ServerChat>
|
||||
{
|
||||
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<PlayerEnter>
|
||||
{
|
||||
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<PlayerChange>
|
||||
{
|
||||
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<WatchChange>
|
||||
{
|
||||
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<DeckCount>
|
||||
{
|
||||
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<Stamped<IReadOnlyList<SetupPair>>>
|
||||
{
|
||||
public const int ReplayFlag = 0x40000000;
|
||||
|
||||
public StocMessage Id => StocMessage.SetupPairs;
|
||||
|
||||
public Stamped<IReadOnlyList<SetupPair>> Read(BinaryReader reader)
|
||||
{
|
||||
var seat = reader.ReadUInt16();
|
||||
return new Stamped<IReadOnlyList<SetupPair>>(seat, ReadBlock(reader));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<IReadOnlyList<SetupPair>> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
WriteBlock(writer, payload.Payload);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<SetupPair> ReadBlock(BinaryReader reader)
|
||||
{
|
||||
var count = reader.ReadUInt16();
|
||||
var pairs = new List<SetupPair>(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<SetupPair> 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<SetupPair> 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<SetupPair> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
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 | TagPartnerCards;
|
||||
// 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;
|
||||
// Server: tag partner cards (0x5F): the waiting teammate's hand, Extra Deck and deck go to that side's two seats. Client: the partner view shows them. 0x800 and 0x1000 are reserved by proposals 44 and 45.
|
||||
public const uint TagPartnerCards = 0x2000;
|
||||
// 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 = 9;
|
||||
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<AttackPreviewPair>();
|
||||
}
|
||||
}
|
||||
|
||||
// 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<AttackPreviewEntry>();
|
||||
}
|
||||
}
|
||||
|
||||
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<int>();
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x5F (v1.2.0, TICKET-405): the waiting tag partner's hand, Extra Deck and deck of one side; to that side's two seats only, no sender stamp.
|
||||
public readonly struct TagPartnerCards
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int MaxDeckCards = 250;
|
||||
public const uint FaceUpBit = 0x80000000;
|
||||
|
||||
public byte Version { get; }
|
||||
public byte Side { get; }
|
||||
// Raw codes: bit 31 set = face-up (a Pendulum in the Extra Deck), like MSG_TAG_SWAP.
|
||||
public uint[] Hand { get; }
|
||||
public uint[] Extra { get; }
|
||||
// Sorted ascending; the real order never leaves the engine.
|
||||
public int[] Deck { get; }
|
||||
|
||||
public TagPartnerCards(byte side, uint[] hand, uint[] extra, int[] deck) : this(CurrentVersion, side, hand, extra, deck) { }
|
||||
|
||||
public TagPartnerCards(byte version, byte side, uint[] hand, uint[] extra, int[] deck)
|
||||
{
|
||||
Version = version;
|
||||
Side = side;
|
||||
Hand = hand ?? Array.Empty<uint>();
|
||||
Extra = extra ?? Array.Empty<uint>();
|
||||
Deck = deck ?? Array.Empty<int>();
|
||||
}
|
||||
|
||||
public static int CodeOf(uint raw) => (int)(raw & ~FaceUpBit);
|
||||
|
||||
public static bool IsFaceUp(uint raw) => (raw & FaceUpBit) != 0;
|
||||
}
|
||||
|
||||
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<T>
|
||||
{
|
||||
public int Seat { get; }
|
||||
public T Payload { get; }
|
||||
|
||||
public Stamped(int seat, T payload)
|
||||
{
|
||||
Seat = seat;
|
||||
Payload = payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<int> Main { get; }
|
||||
public IReadOnlyList<int> Extra { get; }
|
||||
public IReadOnlyList<int> Side { get; }
|
||||
|
||||
public UpdateDeck(IReadOnlyList<int> main, IReadOnlyList<int> extra, IReadOnlyList<int> side)
|
||||
{
|
||||
Main = main ?? None;
|
||||
Extra = extra ?? None;
|
||||
Side = side ?? None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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,
|
||||
TagPartnerCards = 0x5F
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<StocMessage, Action<BinaryReader>> _handlers = new Dictionary<StocMessage, Action<BinaryReader>>();
|
||||
private readonly HashSet<StocMessage> _ignored = new HashSet<StocMessage>();
|
||||
private readonly HashSet<StocMessage> _reported = new HashSet<StocMessage>();
|
||||
|
||||
public Action<StocMessage, int> OnUnknown { get; set; }
|
||||
|
||||
public void Register(StocMessage id, Action<BinaryReader> 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<BinaryReader> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<LangVersion>9</LangVersion>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>YGOLegacy.Engine</AssemblyName>
|
||||
<RootNamespace>YGOLegacy.Engine</RootNamespace>
|
||||
<Deterministic>true</Deterministic>
|
||||
<DebugType>portable</DebugType>
|
||||
<EngineVersion Condition="'$(EngineVersion)' == ''">local</EngineVersion>
|
||||
<AssemblyVersion>1.0.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0.0</FileVersion>
|
||||
<InformationalVersion>$(EngineVersion)</InformationalVersion>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<Target Name="GenerateEngineBindingVersion" BeforeTargets="CoreCompile">
|
||||
<PropertyGroup>
|
||||
<EngineBindingVersionFile>$(IntermediateOutputPath)EngineBindingVersion.cs</EngineBindingVersionFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<EngineBindingVersionLine Include="namespace YGOLegacy.Engine" />
|
||||
<EngineBindingVersionLine Include="{" />
|
||||
<EngineBindingVersionLine Include=" public static partial class EngineBinding" />
|
||||
<EngineBindingVersionLine Include=" {" />
|
||||
<EngineBindingVersionLine Include=" public const string Version = "$(EngineVersion)"%3B" />
|
||||
<EngineBindingVersionLine Include=" }" />
|
||||
<EngineBindingVersionLine Include="}" />
|
||||
</ItemGroup>
|
||||
<WriteLinesToFile File="$(EngineBindingVersionFile)" Lines="@(EngineBindingVersionLine)" Overwrite="true" WriteOnlyWhenDifferent="true" />
|
||||
<ItemGroup>
|
||||
<Compile Include="$(EngineBindingVersionFile)" />
|
||||
<FileWrites Include="$(EngineBindingVersionFile)" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
+5
-5
@@ -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
|
||||
# <expected>; 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
|
||||
@@ -125,7 +125,7 @@ RUN SERVER_ZIP_SUPPORT=1 SERVER_TAG_SURRENDER_CONFIRM=1 premake5 gmake \
|
||||
&& make -C build config=release -j"$(nproc)" ygopro \
|
||||
&& cp bin/release/ygopro /out/ygoserver
|
||||
RUN file /out/libygol-engine.so /out/ygoserver \
|
||||
&& export-gate nm /out/libygol-engine.so 855 "$VERSION" /out
|
||||
&& export-gate nm /out/libygol-engine.so 856 "$VERSION" /out
|
||||
|
||||
FROM scratch AS linux
|
||||
COPY --from=linux-build /out/ /
|
||||
@@ -140,7 +140,7 @@ RUN YGOL_ENGINE_VERSION=$VERSION premake5 gmake \
|
||||
&& make -C build config=release_android_arm64 -j"$(nproc)" ygoserver \
|
||||
&& mkdir -p /out && cp bin/android_arm64/release/libygol-engine.so /out/
|
||||
RUN file /out/libygol-engine.so \
|
||||
&& export-gate "$NDK_DIR"/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-nm /out/libygol-engine.so 849 "$VERSION" /out
|
||||
&& export-gate "$NDK_DIR"/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-nm /out/libygol-engine.so 850 "$VERSION" /out
|
||||
|
||||
FROM scratch AS android
|
||||
COPY --from=android-build /out/ /
|
||||
+7
-6
@@ -16,11 +16,12 @@
|
||||
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,
|
||||
the script FAILS unless the DLL exports exactly 335 symbols (start_server,
|
||||
stop_server, ygol_engine_version, and the core C API re-exported, ygol_sb_*
|
||||
and ygol_preview_attack included). The Unity repo's old ygoserver.dll had 327:
|
||||
its own core copy never carried patch 0008's six ygol_sb_* exports.
|
||||
@@ -29,7 +30,7 @@
|
||||
param(
|
||||
[string]$Premake = "C:\premake\premake5.exe",
|
||||
[string]$Version = "local",
|
||||
[int]$ExpectedExports = 334
|
||||
[int]$ExpectedExports = 335
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -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"
|
||||
+121
-16
@@ -1,8 +1,9 @@
|
||||
# The ygol-engine contract
|
||||
|
||||
This is the one spec every consumer of `ygol-engine` reads instead of the C++. It has four parts:
|
||||
This is the one spec every consumer of `ygol-engine` reads instead of the C++. It has five parts:
|
||||
(a) the C API, (b) the wire protocol the duel server speaks, (c) the engine message stream a duel
|
||||
produces, (d) the setup pairs and the Lua API. A change to any part is a row in `CHANGELOG.md`
|
||||
produces, (d) the setup pairs and the Lua API, (e) the C# binding `YGOLegacy.Engine`. A change to any
|
||||
part is a row in `CHANGELOG.md`
|
||||
(proposal 47, Rule 2). The facts here are read from the source: `core/ocgapi.h`,
|
||||
`server/gframe/serverapi.h`, `server/gframe/network.h`, `server/gframe/netserver.cpp`,
|
||||
`server/gframe/single_duel.cpp` / `tag_duel.cpp`, `core/common.h`. When this file and the source
|
||||
@@ -24,18 +25,20 @@ next to the library (`out/win64/engine.json` on Windows):
|
||||
```json
|
||||
{
|
||||
"version": "v0.0.1",
|
||||
"exports": 334,
|
||||
"protocol": 8,
|
||||
"capabilities": 2047
|
||||
"exports": 335,
|
||||
"protocol": 9,
|
||||
"capabilities": 10239,
|
||||
"binding": "v0.0.1"
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Type | Source |
|
||||
|---|---|---|
|
||||
| `version` | string | The `-Version` the build was given; `local` when none. The same string `ygol_engine_version()` returns. |
|
||||
| `exports` | integer | The library's export count after the gate passed (Windows: 334). |
|
||||
| `protocol` | integer | `FEATURE_PROTOCOL` in `server/gframe/network.h` (8 as of 2026-10-13). |
|
||||
| `capabilities` | integer | The OR of every `FEATURE_*` bit `SendServerCapability` advertises (`single_duel.cpp` and `tag_duel.cpp` must agree), as a decimal integer. 2047 = `0x7FF` = bits `0x1` to `0x400`. |
|
||||
| `exports` | integer | The library's export count after the gate passed (Windows: 335). |
|
||||
| `protocol` | integer | `FEATURE_PROTOCOL` in `server/gframe/network.h` (9 as of 2026-10-15). |
|
||||
| `capabilities` | integer | The OR of every `FEATURE_*` bit `SendServerCapability` advertises (`single_duel.cpp` and `tag_duel.cpp` must agree), as a decimal integer. 10239 = `0x27FF` = bits `0x1` to `0x400` plus `0x2000` (`0x800` and `0x1000` are reserved by proposals 44 and 45). |
|
||||
| `binding` | string | The version of the C# binding released with this engine (section (e)); the same string as `version`. |
|
||||
|
||||
The build reads `protocol` and `capabilities` from the source every time; nothing types them in.
|
||||
|
||||
@@ -49,7 +52,7 @@ the caller's.
|
||||
The library also exports 289 `sqlite3_*` symbols because the server links SQLite with
|
||||
`SQLITE_API=__declspec(dllexport)`. They are NOT part of this contract: nothing of ours calls them
|
||||
through the library, and they are counted by the export gate only so that the number stays exact
|
||||
(Windows: 44 contract exports + 289 SQLite + 1 = 334; the extra 1 is `ygol_engine_version`, see below).
|
||||
(Windows: 45 contract exports + 289 SQLite + 1 = 335; the extra 1 is `ygol_engine_version`, see below).
|
||||
|
||||
### Server exports (`server/gframe/serverapi.h`)
|
||||
|
||||
@@ -107,6 +110,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
|
||||
| `preload_script` | `int32_t preload_script(intptr_t pduel, const char* script_name)` | Upstream |
|
||||
| `default_script_reader` | `byte* default_script_reader(const char* script_name, int* len)` | Upstream |
|
||||
| `ygol_preview_attack` | `int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_t location, uint8_t sequence, uint8_t target_location, uint8_t target_sequence, uint8_t* out)` | Patch 0022 (TICKET-374) + 0024 (TICKET-379), 2026-10-13. A read-only dry run of the damage step. Returns 1 answered, 0 refused (bad pointer, no such card, attacker not a face-up monster on `playerid`'s field, target not a monster on the other field); a refusal writes nothing. `target_location` `0xFF` = direct. `out` is 24 bytes: version (1), flags (bit 0 direct, bit 1 unknown, bit 2 attacker destroyed, bit 3 target destroyed, bit 4 pierce, bit 5 illegal), 2 pad bytes, then five `int32`: attacker value, target value, damage to player 0, damage to player 1, reserved 0. A face-down target answers unknown with every number 0. A pair the battle menu (`field::get_attack_target`) would not offer answers illegal alone with every number 0. Call it only while the engine is parked on a prompt; the duel is byte-identical afterwards. |
|
||||
| `ygol_query_tag_cards` | `int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out)` | v1.2.0 (TICKET-405), 2026-10-15. The waiting tag partner's cards of `playerid`'s side, read only. Returns the byte length written, 0 refused (bad pointer, bad player, not a tag duel); a refusal writes nothing. `out`: `u8 version` (1), `u8 hand_count`, `u8 extra_count`, `u8 pad` (0), `u16 deck_count`, then `u32 hand[hand_count]`, `u32 extra[extra_count]` (bit 31 = face-up, as in `MSG_TAG_SWAP`), `u32 deck[deck_count]` sorted ascending (the order stays secret). At most 7 + 4 x (255 + 255 + 250) bytes in practice; size the buffer for your deck limits. The duel is byte-identical afterwards. |
|
||||
| `get_registry_value` | `int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf)` | Upstream (koishi) |
|
||||
| `set_registry_value` | `void set_registry_value(intptr_t pduel, const char* key, const char* value)` | Upstream (koishi). The server writes every setup pair here before `special.lua` (patch 0009). |
|
||||
| `get_registry_keys` | `int32_t get_registry_keys(intptr_t pduel, byte* out_buf)` | Upstream (koishi) |
|
||||
@@ -128,7 +132,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
|
||||
|
||||
Locations the sandbox exports accept: DECK, HAND, MZONE, SZONE, GRAVE, REMOVED, EXTRA.
|
||||
|
||||
Export count on Windows: 3 server + 42 core = 45 contract exports, + 289 `sqlite3_*` = 334. The
|
||||
Export count on Windows: 3 server + 43 core = 46 contract exports, + 289 `sqlite3_*` = 335. The
|
||||
Unity repo's old `ygoserver.dll` had 327: its own core copy never carried patch 0008, and it had no
|
||||
`ygol_engine_version`.
|
||||
|
||||
@@ -161,14 +165,15 @@ the server itself speaks. The STOC form of a relayed message is always the CTOS
|
||||
stamp in front. "Stamp" in the tables below says whether the STOC message carries one.
|
||||
|
||||
**Capability.** The server sends `STOC_CAPABILITY` (stamp `0xFF`) to every connection between
|
||||
`STOC_JOIN_GAME` and `STOC_TYPE_CHANGE`: `protocol` = `FEATURE_PROTOCOL` (8) and `flags` = the OR of
|
||||
the bits below (`0x7FF`). A client sends its own `CTOS_CAPABILITY` after joining. A client refuses a
|
||||
`STOC_JOIN_GAME` and `STOC_TYPE_CHANGE`: `protocol` = `FEATURE_PROTOCOL` (9) and `flags` = the OR of
|
||||
the bits below (`0x27FF`). A client sends its own `CTOS_CAPABILITY` after joining. A client refuses a
|
||||
host without bit `0x4` as out of date.
|
||||
|
||||
**Join snapshot.** A joiner gets, per occupied seat, right after that seat's `STOC_HS_PLAYER_ENTER`:
|
||||
the seat's stored capability, appearance (0006), seat state (0013) and profile (0020) when present,
|
||||
then the setup pairs (0009), the seat plan (0011) if one was ever sent, and, during a duel, the field
|
||||
resync (0005) and the deck lists the audience may see (0019).
|
||||
resync (0005), the deck lists the audience may see (0019) and, for a seated Tag duelist, its side's
|
||||
partner cards (v1.2.0).
|
||||
|
||||
### Client to server
|
||||
|
||||
@@ -209,6 +214,7 @@ resync (0005) and the deck lists the audience may see (0019).
|
||||
| `0x5C` | `STOC_DECK_LIST` | `STOC_DeckList` (5): `u8 version` (1), `u8 side`, `u8 kind`, `u16 count`, then `u32 codes[count]` | No | Kind 0 (the deck's remaining cards, SORTED) to its owner (both teammates in Tag); kind 1 (real order, top first) and kind 2 (the submitted Main Deck of the duelist whose deck is in the zone, sorted) to observers only when spectators see all. Sent when a list differs from the last one that audience got; in the late-watcher snapshot | `0x100` | 6 | 0019 |
|
||||
| `0x5D` | `STOC_PROFILE` | `u16 sender` + `CTOS_Profile` (100) | Yes | Everyone; stored per seat, in the snapshot after APPEARANCE, swapped with the seat, kept across the 0014 lobby reset, cleared when the seat empties | `0x200` | 7 | 0020 |
|
||||
| `0x5E` | `STOC_ATTACK_PREVIEW` | `u8 version` (1), `u8 count`, then per pair the 4 ask bytes echoed + the 24-byte `ygol_preview_attack` answer | No | The asker only. Only attackers the open prompt listed; a pair the engine refuses is left out (the count shrinks); a valid ask whose every pair is left out still gets count 0 | `0x400` | 8 | 0023 |
|
||||
| `0x5F` | `STOC_TAG_PARTNER_CARDS` | `u8 side` + the `ygol_query_tag_cards` bytes (7 + 4 x the three counts) | No | The two seats of `side` only, never the other team and never an observer. Sent after `start_duel` (the waiting members' opening hands), after every `MSG_TAG_SWAP` for the side that swapped (the member that just left is the waiting one), and to a seated duelist in its field resync (`CTOS_REQUEST_FIELD`, after the `MSG_RELOAD_FIELD`). Tag rooms only; a Single / Match room never sends it | `0x2000` | 9 | v1.2.0 |
|
||||
|
||||
### Capability bits and protocol numbers
|
||||
|
||||
@@ -225,6 +231,9 @@ resync (0005) and the deck lists the audience may see (0019).
|
||||
| `0x100` | `FEATURE_DECK_LIST` | 6 | 0019 | Deck lists |
|
||||
| `0x200` | `FEATURE_PROFILE` | 7 | 0020 | Profile |
|
||||
| `0x400` | `FEATURE_ATTACK_PREVIEW` | 8 | 0023 | Attack preview over the wire |
|
||||
| `0x800` | reserved | - | - | Proposal 44 (agreed, not shipped) |
|
||||
| `0x1000` | reserved | - | - | Proposal 45 (agreed, not shipped) |
|
||||
| `0x2000` | `FEATURE_TAG_PARTNER_CARDS` | 9 | v1.2.0 | Tag partner cards (`STOC_TAG_PARTNER_CARDS`, `ygol_query_tag_cards`) |
|
||||
|
||||
`FEATURE_PROTOCOL` is bumped by every patch that adds a message a client must understand; the join
|
||||
list hides hosts older than the client's number. Rule 4 (proposal 47): one feature, one door. Never
|
||||
@@ -240,6 +249,7 @@ carry a new feature inside another feature's message.
|
||||
| 0016 | Tag: team B is loaded as seat 2 main deck + seat 3 tag deck, the prompt owner starts at seat 2; with core patch 0015 the turn order is seat 0, 2, 1, 3. |
|
||||
| 0018 | Spectators see all: every observer gets the UNMASKED stream (both hands, draws, set cards, extra, banished, the 0005 snapshot) unless the setup pair `ygol.room.spectatorview=hidden` is present, which restores the stock masked stream byte for byte. Duelists' streams never change. |
|
||||
| 0021 | START ends a rules-restart reservation window and stops the lobby clock, so an untimed duel no longer ends at once on "time limit up". |
|
||||
| v1.1.1 | Tag: no Battle Phase on turns 1, 2 and 3 (1A, 2A, 1B); the fourth duelist (2B) is the first who can battle. `MSG_SELECT_IDLECMD` carries `to_bp` = 0 on those turns and `Duel.IsAbleToEnterBP` answers false. Single duels: turn 1 only, as stock. |
|
||||
|
||||
### Replay
|
||||
|
||||
@@ -252,8 +262,8 @@ pair.
|
||||
|
||||
`process` + `get_message` hand the consumer a buffer of messages; each is `u8 id` + payload. The
|
||||
server relays them to clients inside `STOC_GAME_MSG` (`0x1`), masking the other side's hidden cards.
|
||||
The table is the one the Unity bot host reads (`LocalDuelHost.Scan`,
|
||||
`Assets/YGOLegacy/Scripts/Core/Bot/LocalDuelHost.cs`); the ids are `MSG_*` in `core/common.h`.
|
||||
The table is the one `MessageScan.Scan` in the C# binding reads (section (e)); the ids are `MSG_*` in
|
||||
`core/common.h`, the enum `GameMessage`.
|
||||
`n` = a count byte read at that point; "prompt" = the engine waits for `set_responsei` /
|
||||
`set_responseb` from `player`. **The fork adds NO message id and changes NO layout**; the only
|
||||
fork-related rows are marked.
|
||||
@@ -347,7 +357,7 @@ fork-related rows are marked.
|
||||
| 142 | `MSG_ANNOUNCE_CARD` | `u8 player`; `n` x 4 | yes |
|
||||
| 143 | `MSG_ANNOUNCE_NUMBER` | `u8 player`; `n` x 4 | yes |
|
||||
| 160 | `MSG_CARD_HINT` | 9 | - |
|
||||
| 161 | `MSG_TAG_SWAP` | `u8 player`, `u8 main count`, `u8 extra count`, `u8 extra pendulum count`, `u8 hand count`, `u32 top code`, then `u32` x hand, `u32` x extra. Not in `Scan` (the bot host never runs Tag). **Fork (core patch 0015): never emitted on a team's first turn; the first swap comes on turn 3 or later.** | - |
|
||||
| 161 | `MSG_TAG_SWAP` | `u8 player`, `u8 main count`, `u8 extra count`, `u8 extra pendulum count`, `u8 hand count`, `u32 top code`, then `u32` x hand, `u32` x extra. Not in `Scan` (the bot host never runs Tag). **Fork (core patch 0015): never emitted on a team's first turn; the first swap comes on turn 3 or later. v1.2.0: the server follows every swap with `STOC_TAG_PARTNER_CARDS` to the swapping side's two seats.** | - |
|
||||
| 162 | `MSG_RELOAD_FIELD` | `u8 duel rule`; per player: `u32 lp`, 7 monster zones (`u8 present`, +2 when present), 8 spell zones (`u8 present`, +1 when present), 6 count bytes; then ONE chain block `n` x 15 after both players. Produced by `query_field_info` and `Debug.ReloadFieldEnd()`; the server sends it as the 0005 field resync | - |
|
||||
| 163 | `MSG_AI_NAME` | `u16 len` + bytes + 1 | - |
|
||||
| 164 | `MSG_SHOW_HINT` | `u16 len` + bytes + 1 | - |
|
||||
@@ -397,3 +407,98 @@ the core sets). A name that is not there is not in the core; the card scripts' `
|
||||
rest. Regenerate with `python contract/lua-reference/generate.py` after any core change to those
|
||||
files and commit the result with it. The fork's core patches add no Lua function (0001 adds the
|
||||
setcode `0xFDF`, `SETCODE_FACEDOWN_TOKEN`, as a cdb convention, not an API).
|
||||
|
||||
## (e) C# binding
|
||||
|
||||
The managed side of the engine ships in the same release as the native libraries: the asset
|
||||
`ygol-engine-binding.zip` holds `YGOLegacy.Engine.dll` and `YGOLegacy.Engine.pdb`, built from
|
||||
`binding/YGOLegacy.Engine/` (`netstandard2.1`, LangVersion 9, unsafe allowed, no package and no Unity
|
||||
reference) and tested by `binding/YGOLegacy.Engine.Tests/` (`net8.0`, NUnit) in the release workflow's
|
||||
`windows` job. Unity, the Tools and the server repo's card-tester consume this DLL instead of their own
|
||||
copies of the sources.
|
||||
|
||||
Namespaces:
|
||||
|
||||
| Namespace | What |
|
||||
|---|---|
|
||||
| `YGOLegacy.Protocol.{Contracts, Codecs, Framing, Routing}` | Section (b) in C#: the message ids and payload records, the CTOS / STOC codecs, the frame codec and the STOC router. Unchanged from the Unity repo (TICKET-397); v1.2.0 adds `StocMessage.TagPartnerCards`, `FeatureFlags.TagPartnerCards`, the `TagPartnerCards` record and `StocCodecs.TagPartnerCards`, and `Capability.ProtocolVersion` is 9. |
|
||||
| `YGOLegacy.Engine` | The four types below (TICKET-398). |
|
||||
|
||||
| Type | What |
|
||||
|---|---|
|
||||
| `EngineApi` | `public static unsafe class`: one `DllImport("ygol-engine", Cdecl)` extern per export of section (a), C names kept, no overloads; the delegates `ScriptReader`, `CardReader`, `MessageHandler` (`UnmanagedFunctionPointer(Cdecl)`) beside it. `[MonoPInvokeCallback]` belongs on the consumer's callback methods (IL2CPP), not here. |
|
||||
| `MessageScan` | `public static class`: the section (c) layout scanner, moved from the Unity bot host (`LocalDuelHost`) with its bodies unchanged. `MsgInfo` (player, prompt, to-player-only, new-turn), `Scan(byte[] b, ref int pos, int id, int len)` (advances `pos` past one message and says who may see it; throws on an unknown id or an overrun), `Blank(id, msg, info, recipient)` (hidden-information blanking per recipient for `MSG_SHUFFLE_HAND`, `MSG_SHUFFLE_EXTRA`, `MSG_DRAW`, `MSG_MOVE`, `MSG_SET`), `BlankPileCodes(buf, all)` (zeroes the `QUERY_CODE` field of query records) and `PromptName(id)`. |
|
||||
| `GameMessage` | `public enum GameMessage : byte`: one member per `#define MSG_<NAME> <n>` in `core/common.h` (84), member = PascalCase of `<NAME>` (`MSG_SELECT_BATTLECMD` -> `SelectBattlecmd`), value = `<n>`. `GameMessageParityTests` parses the header and fails on a missing, extra or renumbered id. The commented-out defines (`MSG_WAITING`, `MSG_START`, `MSG_UPDATE_DATA`, ...) are not members. |
|
||||
| `EngineBinding` | `public const string Version` (the tag the DLL was built for, `local` when none; generated at build from the `EngineVersion` property) and `public static string CheckNative()`: returns `ygol_engine_version()` when it equals `Version`, else throws `InvalidOperationException` naming both strings. |
|
||||
|
||||
### `EngineApi` externs
|
||||
|
||||
Every row is one export of section (a) with its managed signature. A `string` parameter is
|
||||
`[MarshalAs(UnmanagedType.LPUTF8Str)]`.
|
||||
|
||||
| Export | Managed signature |
|
||||
|---|---|
|
||||
| `set_script_reader` | `void set_script_reader(ScriptReader f)` |
|
||||
| `set_card_reader` | `void set_card_reader(CardReader f)` |
|
||||
| `set_message_handler` | `void set_message_handler(MessageHandler f)` |
|
||||
| `create_duel` | `IntPtr create_duel(uint seed)` |
|
||||
| `create_duel_v2` | `IntPtr create_duel_v2(uint[] seed_sequence)` |
|
||||
| `create_duel_ex` | `IntPtr create_duel_ex(uint seed, uint create_flags)` |
|
||||
| `create_duel_v2_ex` | `IntPtr create_duel_v2_ex(uint[] seed_sequence, uint create_flags)` |
|
||||
| `start_duel` | `void start_duel(IntPtr pduel, uint options)` |
|
||||
| `end_duel` | `void end_duel(IntPtr pduel)` |
|
||||
| `set_player_info` | `void set_player_info(IntPtr pduel, int playerid, int lp, int startcount, int drawcount)` |
|
||||
| `get_log_message` | `void get_log_message(IntPtr pduel, byte[] buf)` |
|
||||
| `get_message` | `int get_message(IntPtr pduel, byte[] buf)` |
|
||||
| `process` | `uint process(IntPtr pduel)` |
|
||||
| `new_card` | `void new_card(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position)` |
|
||||
| `new_tag_card` | `void new_tag_card(IntPtr pduel, uint code, byte owner, byte location)` |
|
||||
| `query_card` | `int query_card(IntPtr pduel, byte playerid, byte location, byte sequence, uint query_flag, byte[] buf, int use_cache)` |
|
||||
| `query_field_count` | `int query_field_count(IntPtr pduel, byte playerid, byte location)` |
|
||||
| `query_field_card` | `int query_field_card(IntPtr pduel, byte playerid, byte location, uint query_flag, byte[] buf, int use_cache)` |
|
||||
| `query_field_info` | `int query_field_info(IntPtr pduel, byte[] buf)` |
|
||||
| `set_responsei` | `void set_responsei(IntPtr pduel, int value)` |
|
||||
| `set_responseb` | `void set_responseb(IntPtr pduel, byte[] buf)` |
|
||||
| `preload_script` | `int preload_script(IntPtr pduel, string script_name)` |
|
||||
| `default_script_reader` | `IntPtr default_script_reader(string script_name, int* len)` |
|
||||
| `ygol_preview_attack` | `int ygol_preview_attack(IntPtr pduel, byte playerid, byte location, byte sequence, byte target_location, byte target_sequence, byte[] @out)` |
|
||||
| `ygol_query_tag_cards` | `int ygol_query_tag_cards(IntPtr pduel, byte playerid, byte[] @out)` |
|
||||
| `get_registry_value` | `int get_registry_value(IntPtr pduel, string key, byte[] out_buf)` |
|
||||
| `set_registry_value` | `void set_registry_value(IntPtr pduel, string key, string value)` |
|
||||
| `get_registry_keys` | `int get_registry_keys(IntPtr pduel, byte[] out_buf)` |
|
||||
| `clear_registry` | `void clear_registry(IntPtr pduel)` |
|
||||
| `dump_registry` | `int dump_registry(IntPtr pduel, byte[] out_buf)` |
|
||||
| `load_registry` | `void load_registry(IntPtr pduel, byte[] in_buf, int in_len)` |
|
||||
| `get_lua_coverage_dump_size` | `int get_lua_coverage_dump_size(IntPtr pduel, string name)` |
|
||||
| `dump_lua_coverage` | `int dump_lua_coverage(IntPtr pduel, string name, byte[] out_buf, int out_len)` |
|
||||
| `get_all_lua_coverages_dump_size` | `int get_all_lua_coverages_dump_size(IntPtr pduel)` |
|
||||
| `dump_all_lua_coverages` | `int dump_all_lua_coverages(IntPtr pduel, byte[] out_buf, int out_len)` |
|
||||
| `clear_lua_coverage` | `void clear_lua_coverage(IntPtr pduel, string name)` |
|
||||
| `clear_all_lua_coverages` | `void clear_all_lua_coverages(IntPtr pduel)` |
|
||||
| `ygol_sb_add` | `int ygol_sb_add(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position)` |
|
||||
| `ygol_sb_move` | `int ygol_sb_move(IntPtr pduel, byte playerid, byte location, byte sequence, byte dst_playerid, byte dst_location, byte dst_sequence, byte position)` |
|
||||
| `ygol_sb_remove` | `int ygol_sb_remove(IntPtr pduel, byte playerid, byte location, byte sequence)` |
|
||||
| `ygol_sb_set_position` | `int ygol_sb_set_position(IntPtr pduel, byte playerid, byte location, byte sequence, byte position)` |
|
||||
| `ygol_sb_set_lp` | `int ygol_sb_set_lp(IntPtr pduel, byte playerid, int lp)` |
|
||||
| `ygol_sb_reask` | `int ygol_sb_reask(IntPtr pduel)` |
|
||||
| `start_server` | `int start_server(string args)` |
|
||||
| `stop_server` | `void stop_server()` |
|
||||
| `ygol_engine_version` | `IntPtr ygol_engine_version()` |
|
||||
|
||||
Delegates: `IntPtr ScriptReader(string script_name, int* len)`, `uint CardReader(uint code, IntPtr data)`
|
||||
(`data` is the `card_data*` the core wants filled), `uint MessageHandler(IntPtr pduel, uint msg_type)`.
|
||||
|
||||
**Type rule** (the header has no wide string, so `CharSet.Unicode` appears nowhere): `intptr_t` ->
|
||||
`IntPtr`; `int32_t` / `int` -> `int`; `uint32_t` -> `uint`; `uint8_t` -> `byte`; `uint_fast32_t` ->
|
||||
`uint` (32-bit on MSVC x64, 64-bit on glibc x64; the register is zero-extended); `byte*`, `char* buf`,
|
||||
`uint8_t* out`, `const byte*` -> `byte[]`; `uint32_t seed_sequence[]` -> `uint[]`; `const char*` in ->
|
||||
`string` with `LPUTF8Str`; `const char*` out (`ygol_engine_version`) and `byte*` out
|
||||
(`default_script_reader`) -> `IntPtr`; `int*` -> `int*`; `card_data*` -> `IntPtr`; function pointers ->
|
||||
the delegates. `EngineApiParityTests` parses `contract/ocgapi.h` and fails when a header export has no
|
||||
extern of that name or an extern has no header line.
|
||||
|
||||
**Version rule.** The binding's version is the engine tag: `EngineBinding.Version` = `engine.json`'s
|
||||
`binding` = `engine.json`'s `version` = `ygol_engine_version()`, all the same string for one release. A
|
||||
consumer calls `EngineBinding.CheckNative()` once at start and treats the exception as "fetch the engine
|
||||
release whose tag equals the binding version". The native libraries and the binding are released
|
||||
together even when only one of them changed.
|
||||
@@ -83,6 +83,13 @@ OCGCORE_API byte* default_script_reader(const char* script_name, int* len);
|
||||
// the duel is byte-identical afterwards (proposal 43).
|
||||
OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_t location, uint8_t sequence, uint8_t target_location, uint8_t target_sequence, uint8_t* out);
|
||||
|
||||
// [YGOL] v1.2.0 (tag partner cards, TICKET-405): the waiting tag partner's cards of playerid's side, read
|
||||
// only. out: version (1), hand count, extra count, one pad byte, uint16 deck count, then the uint32 hand
|
||||
// codes, the uint32 extra codes (bit 31 = face-up, like MSG_TAG_SWAP) and the uint32 deck codes sorted
|
||||
// ascending (the order stays secret). Returns the byte length, 0 refused (bad pointer, bad player, not a
|
||||
// tag duel); a refusal writes nothing. The duel is byte-identical afterwards (proposal 33 Rule 11).
|
||||
OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out);
|
||||
|
||||
// koishi specific
|
||||
OCGCORE_API int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf);
|
||||
OCGCORE_API void set_registry_value(intptr_t pduel, const char* key, const char* value);
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
# python Tools/YGOLegacy/probe-feature-messages.py --dll <path\to\ygoserver.dll>
|
||||
# hosts its own lobby from that DLL (cwd must be the repo root, like
|
||||
# BotArena: the DLL reads ./expansions and friends) on --port (default
|
||||
# 7961) and stops it at the end. This is how a freshly built, not yet
|
||||
# 27961) and stops it at the end. This is how a freshly built, not yet
|
||||
# installed DLL is probed.
|
||||
#
|
||||
# With --dll it then gates patch 0009 (TICKET-258, setup pairs): it hosts five
|
||||
@@ -113,7 +113,8 @@
|
||||
#
|
||||
# With --dll it also gates patch 0023 (TICKET-378, attack preview): the server's
|
||||
# capability says protocol 8 + flag 0x400; each side summons a Probe Knight and
|
||||
# the second seat enters its Battle Phase; its ATTACK_PREVIEW ask (0x5E: version,
|
||||
# the second seat enters its Battle Phase (Tag: the fourth duelist on turn 4, since
|
||||
# v1.1.1 allows no Battle Phase on tag turns 1-3); its ATTACK_PREVIEW ask (0x5E: version,
|
||||
# count, 4 bytes per pair) is answered to that seat alone (0x5E: version, count,
|
||||
# per pair the 4 bytes echoed + the engine's 24-byte answer): the knight into the
|
||||
# knight says both die, a direct attack says illegal, a pair the prompt does not
|
||||
@@ -121,6 +122,18 @@
|
||||
# a wrong version, too many pairs and a wrong length are dropped without a reply;
|
||||
# a seat that never asks gets no 0x5E and the duel goes on. Single and Tag.
|
||||
#
|
||||
# With --dll it also gates v1.2.0 (TICKET-405, tag partner cards): the server's
|
||||
# capability says protocol 9 + flag 0x2000 (single and tag); in a Tag room each
|
||||
# seat gets TAG_PARTNER_CARDS (0x5F: side, version 1, hand count, extra count,
|
||||
# pad, u16 deck count, then the hand, Extra Deck and deck codes) for its own side
|
||||
# only -- at the start the waiting member's 5-card opening hand, its two Probe
|
||||
# Fusions and its 35 remaining cards SORTED; after each MSG_TAG_SWAP the member
|
||||
# that just left, hand = every card it drew, deck = its deck minus them; a seat's
|
||||
# field resync (CTOS_REQUEST_FIELD) carries the same list again to that seat
|
||||
# alone -- and the other team, the watcher, a watcher's resync and a late
|
||||
# watcher's snapshot never get one. The hand a swap brings in is the hand the
|
||||
# opening 0x5F announced.
|
||||
#
|
||||
# Exit 0 only when every check passed. Stock DLL: the first check fails; the
|
||||
# 0011 DLL fails at the capability flags.
|
||||
import argparse, base64, ctypes, lzma, os, shutil, socket, sqlite3, struct, sys, tempfile, threading, time
|
||||
@@ -266,7 +279,7 @@ def check_snapshot(who, pkts, expect_seat_appearance, forbid_seat):
|
||||
check(len(server_caps) == 1 and j < server_caps[0][0] < t, "%s: the server's CAPABILITY(0xFF) sits between JOIN_GAME and TYPE_CHANGE" % who)
|
||||
if server_caps:
|
||||
proto, flags = struct.unpack_from("<HI", server_caps[0][1], 2)
|
||||
check(proto == 8 and flags == 0x7FF, "%s: server capability is protocol 8, flags 0x7FF (appearance | dialogue | setup pairs | seat plan | rules restart | seat state | lobby after match | coin toss | deck lists | profile | attack preview), got %d / 0x%x" % (who, proto, flags))
|
||||
check(proto == 9 and flags == 0x27FF, "%s: server capability is protocol 9, flags 0x27FF (appearance | dialogue | setup pairs | seat plan | rules restart | seat state | lobby after match | coin toss | deck lists | profile | attack preview | tag partner cards), got %d / 0x%x" % (who, proto, flags))
|
||||
for seat, expected in expect_seat_appearance.items():
|
||||
enters = [i for i, (p, d) in enumerate(pkts) if p == STOC_HS_PLAYER_ENTER and d[40] == seat]
|
||||
apps = [i for i, (p, d) in enumerate(pkts) if p == STOC_APPEARANCE and struct.unpack_from("<H", d, 0)[0] == seat]
|
||||
@@ -295,7 +308,7 @@ def host_dll(path, port, mode=0, tail=""):
|
||||
deadline = time.time() + 20
|
||||
while time.time() < deadline:
|
||||
if not t.is_alive():
|
||||
sys.exit("ygoserver thread ended before it listened (cwd must be the repo root; port %d free?)" % port)
|
||||
sys.exit("ygoserver thread ended before it listened (cwd must be the repo root; port %d free? a port inside the OS dynamic range collides with the probe's own connections)" % port)
|
||||
try:
|
||||
socket.create_connection(("127.0.0.1", port), timeout=0.3).close()
|
||||
return dll, t
|
||||
@@ -310,7 +323,10 @@ def main():
|
||||
ap.add_argument("--port", type=int, default=None)
|
||||
ap.add_argument("--dll", default=None, help="host a lobby from this ygoserver.dll instead of connecting to one")
|
||||
o = ap.parse_args()
|
||||
port = o.port or (7961 if o.dll else 7911)
|
||||
# Above every OS dynamic (ephemeral) port range: this machine hands outgoing connections ports
|
||||
# 1024-15000 (netsh int ipv4 show dynamicport tcp), and a probe client that drew the next room's
|
||||
# port made that room's bind fail ("0", then "ended before it listened") on most runs.
|
||||
port = o.port or (27961 if o.dll else 7911)
|
||||
feature_suite(o, port)
|
||||
if o.dll:
|
||||
setup_suite(o.dll, port + 1)
|
||||
@@ -323,6 +339,7 @@ def main():
|
||||
deck_list_suite(o.dll, port + 80)
|
||||
profile_suite(o.dll, port + 90)
|
||||
attack_preview_suite(o.dll, port + 100)
|
||||
tag_partner_suite(o.dll, port + 110)
|
||||
print()
|
||||
if failures:
|
||||
print("FAILED: %d check(s)" % len(failures))
|
||||
@@ -494,6 +511,9 @@ def make_workspace():
|
||||
# patch 0023: a level-4 normal monster, so a seat can summon without a tribute and attack with it
|
||||
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 17, 1800, 1000, 4, 1, 16, 0)", (PROBE_KNIGHT,))
|
||||
db.execute("INSERT INTO texts VALUES(?, 'Probe Knight', ''" + ", ''" * 16 + ")", (PROBE_KNIGHT,))
|
||||
# v1.2.0 (TICKET-405): a Fusion monster, so a submitted deck has an Extra Deck
|
||||
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 65, 2000, 2000, 6, 1, 16, 0)", (PROBE_FUSION,))
|
||||
db.execute("INSERT INTO texts VALUES(?, 'Probe Fusion', ''" + ", ''" * 16 + ")", (PROBE_FUSION,))
|
||||
db.commit()
|
||||
db.close()
|
||||
return root
|
||||
@@ -2393,7 +2413,7 @@ def preview_answer(flags, attacker=0, target=0, damage0=0, damage1=0):
|
||||
|
||||
def attack_preview_room(dll_path, port, label, mode):
|
||||
seats = 4 if mode == 2 else 2
|
||||
print("== attack preview, %s (%d seats + a watcher: a summon each, then the second seat's Battle Phase)" % (label, seats))
|
||||
print("== attack preview, %s (%d seats + a watcher: a summon each, then the %s Battle Phase)" % (label, seats, "fourth duelist's turn-4" if mode == 2 else "second seat's"))
|
||||
root = make_workspace()
|
||||
here = os.getcwd()
|
||||
os.chdir(root)
|
||||
@@ -2456,6 +2476,16 @@ def attack_preview_room(dll_path, port, label, mode):
|
||||
second = summon("turn 2")
|
||||
if not second:
|
||||
return
|
||||
if mode == 2:
|
||||
# v1.1.1: a Tag duel has no Battle Phase on turns 1-3; the fourth duelist (2B) is the first who may battle
|
||||
for stage in ("turn 3", "turn 4"):
|
||||
before = marks_of(everyone)
|
||||
answer(second, struct.pack("<i", 7)) # idle command 7: to the End Phase
|
||||
ok = pump(everyone, lambda: any(game_msgs(since(c, before), MSG_SELECT_IDLECMD) for c in seated if c is not second), limit=8, chain=True)
|
||||
holders = [c for c in seated if game_msgs(since(c, before), MSG_SELECT_IDLECMD)]
|
||||
if not check(ok and len(holders) == 1, "%s: %s: the turn passed and one swapped-in seat holds the idle prompt (%s)" % (label, stage, [c.name for c in holders])):
|
||||
return
|
||||
second = holders[0]
|
||||
before = marks_of(everyone)
|
||||
answer(second, struct.pack("<i", 6)) # idle command 6: to the Battle Phase
|
||||
ok = pump(everyone, lambda: game_msgs(since(second, before), MSG_SELECT_BATTLECMD), limit=6, chain=True)
|
||||
@@ -2525,5 +2555,187 @@ def attack_preview_suite(dll_path, port):
|
||||
attack_preview_room(dll_path, port + 1, "tag", 2)
|
||||
|
||||
|
||||
# --- v1.2.0 (TICKET-405): tag partner cards --------------------------------------
|
||||
STOC_TAG_PARTNER_CARDS, CTOS_REQUEST_FIELD, MSG_RELOAD_FIELD = 0x5F, 0x30, 162
|
||||
NAMES.update({0x5F: "TAG_PARTNER_CARDS"})
|
||||
PROBE_FUSION = PROBE_CARD + 600 # a Fusion monster: it goes to the Extra Deck
|
||||
TAG_PARTNER_DECKS = [DECK_LIST_CODES[seat] + [PROBE_FUSION, PROBE_FUSION] for seat in range(4)]
|
||||
|
||||
|
||||
def partner_cards(pkts, side=None):
|
||||
# (side, version, hand, extra, deck, size); hand / extra / deck are None when the size does not match the counts
|
||||
out = []
|
||||
for p, d in pkts:
|
||||
if p != STOC_TAG_PARTNER_CARDS or len(d) < 7:
|
||||
continue
|
||||
s, version, hand_n, extra_n, _pad, deck_n = struct.unpack_from("<BBBBBH", d, 0)
|
||||
if side is not None and s != side:
|
||||
continue
|
||||
n = hand_n + extra_n + deck_n
|
||||
if len(d) != 7 + 4 * n:
|
||||
out.append((s, version, None, None, None, len(d)))
|
||||
continue
|
||||
codes = list(struct.unpack_from("<%dI" % n, d, 7))
|
||||
out.append((s, version, codes[:hand_n], codes[hand_n:hand_n + extra_n], codes[hand_n + extra_n:], len(d)))
|
||||
return out
|
||||
|
||||
|
||||
def server_capability(pkts):
|
||||
for p, d in pkts:
|
||||
if p == STOC_CAPABILITY and len(d) == 8 and struct.unpack_from("<H", d, 0)[0] == SERVER:
|
||||
return struct.unpack_from("<HI", d, 2)
|
||||
return None
|
||||
|
||||
|
||||
def tag_swap_hand(d):
|
||||
# MSG_TAG_SWAP: player, main count, extra count, pendulum count, hand count, u32 top, u32 x hand, u32 x extra
|
||||
hcount = d[5]
|
||||
return [c & 0x7FFFFFFF for c in struct.unpack_from("<%dI" % hcount, d, 10)]
|
||||
|
||||
|
||||
def tag_partner_room(dll_path, port, label):
|
||||
print("== tag partner cards, %s (4 seats + a watcher: the opening hands, both swaps, a seat's field resync, a late watcher)" % label)
|
||||
root = make_workspace()
|
||||
here = os.getcwd()
|
||||
os.chdir(root)
|
||||
try:
|
||||
write_special(root, [])
|
||||
dll, thread = host_dll(dll_path, port, 2)
|
||||
clients = []
|
||||
|
||||
def client(name):
|
||||
c = Client("127.0.0.1", port, name)
|
||||
c.log = list(c.join())
|
||||
clients.append(c)
|
||||
return c
|
||||
|
||||
seated = [client("tp-seat%d" % i) for i in range(4)]
|
||||
w = client("tp-watch")
|
||||
everyone = seated + [w]
|
||||
check([c.seat for c in everyone] == [0, 1, 2, 3, OBSERVER], "%s: four seats and a watcher (%r)" % (label, [c.seat for c in everyone]))
|
||||
cap = server_capability(seated[0].log)
|
||||
check(cap == (9, 0x27FF), "%s: the tag server's capability is protocol 9, flags 0x27FF (got %s)" % (label, cap))
|
||||
drain_all(everyone)
|
||||
for c in seated:
|
||||
c.send(CTOS_UPDATE_DECK, deck_bytes(TAG_PARTNER_DECKS[c.seat]))
|
||||
pump(everyone, lambda: False, limit=0.8)
|
||||
marks = start_duel_on(label, seated[0], everyone, None, "tag partner cards")
|
||||
ok = pump(everyone, lambda: all(len(draws(since(c, marks))) >= 2 for c in everyone) and any(game_msgs(since(c, marks), MSG_SELECT_IDLECMD) for c in seated), limit=10)
|
||||
check(ok, "%s: the opening draws and the first idle prompt reached the seats" % label)
|
||||
side_of = {}
|
||||
for c in seated:
|
||||
s = starts(since(c, marks))
|
||||
side_of[c] = s[0] if len(s) == 1 else -1
|
||||
by_side = {p: [c for c in seated if side_of[c] == p] for p in (0, 1)}
|
||||
if not check(all(len(by_side[p]) == 2 for p in (0, 1)), "%s: every seat got one MSG_START naming its side (%s)" % (label, {k: [c.name for c in v] for k, v in by_side.items()})):
|
||||
return
|
||||
first_seat = {p: min(c.seat for c in by_side[p]) for p in (0, 1)}
|
||||
partner_seat = {p: max(c.seat for c in by_side[p]) for p in (0, 1)}
|
||||
extra_expected = [PROBE_FUSION, PROBE_FUSION]
|
||||
|
||||
def check_cards(side, since_marks, stage, waiting_seat, expect_hand=None):
|
||||
pool = set(DECK_LIST_CODES[waiting_seat])
|
||||
latest = None
|
||||
for c in by_side[side]:
|
||||
got = partner_cards(since(c, since_marks), side)
|
||||
check(len(got) == 1, "%s: %s: seat %d got exactly one TAG_PARTNER_CARDS for its side %d (%d)" % (label, stage, c.seat, side, len(got)))
|
||||
check(not partner_cards(since(c, since_marks), 1 - side), "%s: %s: seat %d got none for the other side" % (label, stage, c.seat))
|
||||
if not got:
|
||||
continue
|
||||
s, version, hand, extra, deck, size = got[-1]
|
||||
if not check(hand is not None, "%s: %s: seat %d's TAG_PARTNER_CARDS is 7 + 4 x counts bytes (%d)" % (label, stage, c.seat, size)):
|
||||
continue
|
||||
check(version == 1, "%s: %s: seat %d's list is version 1 (%d)" % (label, stage, c.seat, version))
|
||||
if expect_hand is None:
|
||||
check(len(hand) == 5 and set(hand) <= pool, "%s: %s: seat %d's partner hand is 5 cards of seat %d's deck (%s)" % (label, stage, c.seat, waiting_seat, hand))
|
||||
else:
|
||||
check(sorted(hand) == sorted(expect_hand), "%s: %s: seat %d's partner hand is every card seat %d drew (%d; expected %d)" % (label, stage, c.seat, waiting_seat, len(hand), len(expect_hand)))
|
||||
check(extra == extra_expected, "%s: %s: seat %d's partner Extra Deck is the two Probe Fusions, face-down (%s)" % (label, stage, c.seat, extra))
|
||||
check(deck == sorted(deck) and len(deck) == len(set(deck)), "%s: %s: seat %d's partner deck is sorted ascending" % (label, stage, c.seat))
|
||||
check(deck == sorted(pool - set(hand)), "%s: %s: seat %d's partner deck is seat %d's Main Deck minus the hand (%d)" % (label, stage, c.seat, waiting_seat, len(deck)))
|
||||
latest = got[-1]
|
||||
for c in by_side[1 - side]:
|
||||
check(not partner_cards(since(c, since_marks), side), "%s: %s: seat %d (the other team) got no TAG_PARTNER_CARDS for side %d" % (label, stage, c.seat, side))
|
||||
check(not partner_cards(since(w, since_marks)), "%s: %s: the watcher got no TAG_PARTNER_CARDS" % (label, stage))
|
||||
return latest
|
||||
|
||||
opening = {}
|
||||
for p in (0, 1):
|
||||
opening[p] = check_cards(p, marks, "opening", partner_seat[p])
|
||||
|
||||
def end_turn(stage):
|
||||
holders = [c for c in seated if game_msgs(since(c, end_turn.marks), MSG_SELECT_IDLECMD)]
|
||||
check(len(holders) == 1, "%s: %s: exactly one seat holds the idle prompt (%s)" % (label, stage, [c.name for c in holders]))
|
||||
if not holders:
|
||||
return None
|
||||
before = marks_of(everyone)
|
||||
holders[0].send(CTOS_TIME_CONFIRM) # the timed server holds the seat until the clock is acknowledged
|
||||
holders[0].send(CTOS_RESPONSE, struct.pack("<i", 7)) # idle command 7: to the End Phase
|
||||
ok = pump(everyone, lambda: any(draws(since(c, before)) for c in seated) and any(game_msgs(since(c, before), MSG_SELECT_IDLECMD) for c in seated), limit=10, chain=True)
|
||||
check(ok, "%s: %s: the turn passed and the next seat drew" % (label, stage))
|
||||
end_turn.marks = before
|
||||
return before
|
||||
end_turn.marks = marks
|
||||
|
||||
def check_swap(side, before, stage):
|
||||
owner = by_side[side][0]
|
||||
new = since(owner, before)
|
||||
cut = next((i for i, (pid, _) in enumerate(new) if pid == STOC_TAG_PARTNER_CARDS), None)
|
||||
if not check(cut is not None, "%s: %s: side %d got a TAG_PARTNER_CARDS after its swap" % (label, stage, side)):
|
||||
return
|
||||
pre = owner.log[marks[owner]:before[owner] + cut]
|
||||
drawn = [x for d in draws(pre, side) for x in draw_codes(d)]
|
||||
check(len(drawn) >= 5, "%s: %s: seat %d drew %d cards before the swap" % (label, stage, first_seat[side], len(drawn)))
|
||||
check_cards(side, before, stage, first_seat[side], expect_hand=drawn)
|
||||
swaps = [d for d in game_msgs(new, MSG_TAG_SWAP) if len(d) > 10 and d[1] == side]
|
||||
check(len(swaps) == 1, "%s: %s: side %d saw one MSG_TAG_SWAP for itself (%d)" % (label, stage, side, len(swaps)))
|
||||
if swaps and opening.get(side) and opening[side][2] is not None:
|
||||
check(sorted(tag_swap_hand(swaps[0])) == sorted(opening[side][2]), "%s: %s: the hand the swap brought in is the hand the opening TAG_PARTNER_CARDS announced" % (label, stage))
|
||||
|
||||
before = end_turn("pass 1") # turn 2: side 1's first turn, no swap
|
||||
if before:
|
||||
check(all(not partner_cards(since(c, before)) for c in everyone), "%s: pass 1: a turn without a swap sent nobody a TAG_PARTNER_CARDS" % label)
|
||||
before = end_turn("pass 2") # turn 3: side 0 swaps to its partner
|
||||
if before:
|
||||
check_swap(0, before, "pass 2")
|
||||
before = end_turn("pass 3") # turn 4: side 1 swaps to its partner
|
||||
if before:
|
||||
check_swap(1, before, "pass 3")
|
||||
|
||||
asker = by_side[0][1]
|
||||
last = partner_cards(asker.log[marks[asker]:], 0)
|
||||
marks3 = marks_of(everyone)
|
||||
asker.send(CTOS_REQUEST_FIELD)
|
||||
w.send(CTOS_REQUEST_FIELD)
|
||||
pump(everyone, lambda: partner_cards(since(asker, marks3)) and game_msgs(since(w, marks3), MSG_RELOAD_FIELD), limit=3)
|
||||
got = partner_cards(since(asker, marks3), 0)
|
||||
check(len(got) == 1 and bool(game_msgs(since(asker, marks3), MSG_RELOAD_FIELD)), "%s: a seat's field resync carried one TAG_PARTNER_CARDS for its side (%d)" % (label, len(got)))
|
||||
check(bool(got) and bool(last) and got[0][2:5] == last[-1][2:5], "%s: the resync list equals the last list that seat got" % label)
|
||||
check(bool(game_msgs(since(w, marks3), MSG_RELOAD_FIELD)) and all(not partner_cards(since(c, marks3)) for c in everyone if c is not asker), "%s: the watcher's resync and everyone else carried no TAG_PARTNER_CARDS" % label)
|
||||
|
||||
l = client("tp-late")
|
||||
l.log += l.drain(quiet=0.6)
|
||||
check(l.seat == OBSERVER and STOC_DUEL_START in ids_of(l.log), "%s: a mid-duel joiner is an observer and got DUEL_START" % label)
|
||||
check(not partner_cards(l.log), "%s: the late watcher's snapshot has no TAG_PARTNER_CARDS" % label)
|
||||
|
||||
marks4 = marks_of(everyone + [l])
|
||||
for c in by_side[0]:
|
||||
c.send(CTOS_SURRENDER)
|
||||
ok = pump(everyone + [l], lambda: all(match_overs(since(c, marks4)) for c in everyone + [l]), limit=10)
|
||||
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone" % label)
|
||||
for c in clients:
|
||||
c.close()
|
||||
stop_dll(dll, thread, label)
|
||||
finally:
|
||||
os.chdir(here)
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
|
||||
|
||||
def tag_partner_suite(dll_path, port):
|
||||
print()
|
||||
print("hosting the tag partner cards room from %s" % dll_path)
|
||||
tag_partner_room(dll_path, port, "tag")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+7
-1
@@ -3704,8 +3704,14 @@ int32_t field::check_spself_from_hand_trigger(const chain& ch) const {
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
// [YGOL] Tag: the first three duelists (1A, 2A, 1B) have no Battle Phase; the fourth is the first who can battle.
|
||||
int32_t field::is_opening_turn_without_bp() {
|
||||
if(core.duel_options & DUEL_ATTACK_FIRST_TURN)
|
||||
return FALSE;
|
||||
return infos.turn_id <= ((core.duel_options & DUEL_TAG_MODE) ? 3 : 1);
|
||||
}
|
||||
int32_t field::is_able_to_enter_bp() {
|
||||
return ((core.duel_options & DUEL_ATTACK_FIRST_TURN) || infos.turn_id != 1)
|
||||
return !is_opening_turn_without_bp()
|
||||
&& infos.phase < PHASE_BATTLE_START
|
||||
&& !is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP);
|
||||
}
|
||||
@@ -531,6 +531,7 @@ public:
|
||||
int32_t check_trigger_effect(const chain& ch) const;
|
||||
int32_t check_spself_from_hand_trigger(const chain& ch) const;
|
||||
int32_t is_able_to_enter_bp();
|
||||
int32_t is_opening_turn_without_bp();
|
||||
|
||||
void add_process(uint16_t type, uint16_t step, effect* peffect, group* target, int32_t arg1, int32_t arg2, int32_t arg3 = 0, int32_t arg4 = 0, void* ptr1 = nullptr, void* ptr2 = nullptr);
|
||||
uint32_t process();
|
||||
|
||||
@@ -441,6 +441,34 @@ OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_
|
||||
buffer_write<int32_t>(ptr, 0);
|
||||
return 1;
|
||||
}
|
||||
// [YGOL] v1.2.0 (tag partner cards) -- see ocgapi.h. Reads the three tag_list_* vectors the core keeps for the
|
||||
// waiting member; nothing is moved, nothing is written to the duel.
|
||||
OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out) {
|
||||
duel* pd = (duel*)pduel;
|
||||
if(!pd || !out || !duel_set.count(pd) || !pd->game_field)
|
||||
return 0;
|
||||
if(!check_playerid(playerid) || !(pd->game_field->core.duel_options & DUEL_TAG_MODE))
|
||||
return 0;
|
||||
const auto& p = pd->game_field->player[playerid];
|
||||
std::vector<uint32_t> deck;
|
||||
deck.reserve(p.tag_list_main.size());
|
||||
for(auto& pcard : p.tag_list_main)
|
||||
deck.push_back(pcard->data.code);
|
||||
std::sort(deck.begin(), deck.end());
|
||||
byte* ptr = out;
|
||||
buffer_write<uint8_t>(ptr, 1);
|
||||
buffer_write<uint8_t>(ptr, (uint8_t)p.tag_list_hand.size());
|
||||
buffer_write<uint8_t>(ptr, (uint8_t)p.tag_list_extra.size());
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint16_t>(ptr, (uint16_t)deck.size());
|
||||
for(auto& pcard : p.tag_list_hand)
|
||||
buffer_write<uint32_t>(ptr, pcard->data.code | (pcard->is_position(POS_FACEUP) ? 0x80000000 : 0));
|
||||
for(auto& pcard : p.tag_list_extra)
|
||||
buffer_write<uint32_t>(ptr, pcard->data.code | (pcard->is_position(POS_FACEUP) ? 0x80000000 : 0));
|
||||
for(auto code : deck)
|
||||
buffer_write<uint32_t>(ptr, code);
|
||||
return (int32_t)(ptr - out);
|
||||
}
|
||||
OCGCORE_API int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf) {
|
||||
if (!pduel || !key || !out_buf) return -1;
|
||||
|
||||
|
||||
@@ -80,6 +80,13 @@ OCGCORE_API byte* default_script_reader(const char* script_name, int* len);
|
||||
// the duel is byte-identical afterwards (proposal 43).
|
||||
OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_t location, uint8_t sequence, uint8_t target_location, uint8_t target_sequence, uint8_t* out);
|
||||
|
||||
// [YGOL] v1.2.0 (tag partner cards, TICKET-405): the waiting tag partner's cards of playerid's side, read
|
||||
// only. out: version (1), hand count, extra count, one pad byte, uint16 deck count, then the uint32 hand
|
||||
// codes, the uint32 extra codes (bit 31 = face-up, like MSG_TAG_SWAP) and the uint32 deck codes sorted
|
||||
// ascending (the order stays secret). Returns the byte length, 0 refused (bad pointer, bad player, not a
|
||||
// tag duel); a refusal writes nothing. The duel is byte-identical afterwards (proposal 33 Rule 11).
|
||||
OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out);
|
||||
|
||||
// koishi specific
|
||||
OCGCORE_API int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf);
|
||||
OCGCORE_API void set_registry_value(intptr_t pduel, const char* key, const char* value);
|
||||
|
||||
+1
-1
@@ -2078,7 +2078,7 @@ int32_t field::process_idle_command(uint16_t step) {
|
||||
chain newchain;
|
||||
core.to_bp = TRUE;
|
||||
core.to_ep = TRUE;
|
||||
if((!(core.duel_options & DUEL_ATTACK_FIRST_TURN) && infos.turn_id == 1) || infos.phase == PHASE_MAIN2 || is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP))
|
||||
if(is_opening_turn_without_bp() || infos.phase == PHASE_MAIN2 || is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP))
|
||||
core.to_bp = FALSE;
|
||||
if(infos.phase == PHASE_MAIN1) {
|
||||
for(auto& pcard : player[infos.turn_player].list_mzone) {
|
||||
|
||||
@@ -224,7 +224,7 @@ static_assert(sizeof(CTOS_Appearance) == 352, "size mismatch: CTOS_Appearance");
|
||||
check_trivially_copyable(CTOS_Dialogue);
|
||||
static_assert(sizeof(CTOS_Dialogue) == 204, "size mismatch: CTOS_Dialogue");
|
||||
constexpr int SIZE_STOC_FEATURE = sizeof(uint16_t) + sizeof(CTOS_Appearance);
|
||||
constexpr uint16_t FEATURE_PROTOCOL = 8; // YGOL host seats: 1 -> 2; YGOL seat state: 2 -> 3; YGOL lobby after match: 3 -> 4; YGOL coin toss: 4 -> 5; YGOL deck lists: 5 -> 6; YGOL profile: 6 -> 7; YGOL attack preview: 7 -> 8
|
||||
constexpr uint16_t FEATURE_PROTOCOL = 9; // YGOL host seats: 1 -> 2; YGOL seat state: 2 -> 3; YGOL lobby after match: 3 -> 4; YGOL coin toss: 4 -> 5; YGOL deck lists: 5 -> 6; YGOL profile: 6 -> 7; YGOL attack preview: 7 -> 8; YGOL tag partner cards: 8 -> 9
|
||||
constexpr uint32_t FEATURE_APPEARANCE = 0x1;
|
||||
constexpr uint32_t FEATURE_DIALOGUE = 0x2;
|
||||
constexpr uint16_t FEATURE_SENDER_SERVER = 0xff;
|
||||
@@ -462,6 +462,9 @@ constexpr uint8_t ATTACK_PREVIEW_VERSION = 1;
|
||||
constexpr uint8_t ATTACK_PREVIEW_DIRECT = 0xFF;
|
||||
constexpr int ATTACK_PREVIEW_MAX_PAIRS = 64;
|
||||
constexpr int ATTACK_PREVIEW_ANSWER_SIZE = 24; // the ygol_preview_attack answer, echoed after the pair
|
||||
// YGOL tag partner cards: the waiting teammate's hand, Extra Deck and deck (ygol_query_tag_cards), sent to that side's two seats only; 0x800 and 0x1000 are reserved by proposals 44 and 45
|
||||
constexpr uint32_t FEATURE_TAG_PARTNER_CARDS = 0x2000;
|
||||
constexpr uint8_t TAG_PARTNER_CARDS_VERSION = 1;
|
||||
// the one-use bootstrap secret of a replacement server: a host-string token parsed apart from the ygol.* pairs, never stored anywhere else
|
||||
extern uint8_t bootstrap_secret[16];
|
||||
extern bool bootstrap_closed;
|
||||
@@ -666,6 +669,7 @@ inline bool IsFeatureMessage(unsigned char pktType) {
|
||||
#define STOC_DECK_LIST 0x5C // STOC_DeckList + uint32_t codes[count], no sender stamp (YGOL deck lists)
|
||||
#define STOC_PROFILE 0x5D // uint16_t + CTOS_Profile (YGOL profile)
|
||||
#define STOC_ATTACK_PREVIEW 0x5E // uint8_t version, uint8_t count, count x (CTOS_AttackPreviewPair + 24-byte answer), no sender stamp, to the asker only (YGOL attack preview)
|
||||
#define STOC_TAG_PARTNER_CARDS 0x5F // uint8_t side + the ygol_query_tag_cards bytes, no sender stamp, to that side's two seats only (YGOL tag partner cards)
|
||||
|
||||
// STOC_GAME_MSG header
|
||||
#define MSG_WAITING 3
|
||||
|
||||
@@ -98,7 +98,7 @@ void SingleDuel::AttackPreview(DuelPlayer* dp, unsigned char* pdata, int len) {
|
||||
void SingleDuel::SendServerCapability(DuelPlayer* dp) {
|
||||
CTOS_Capability cap;
|
||||
cap.protocol = FEATURE_PROTOCOL;
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW | FEATURE_TAG_PARTNER_CARDS; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag partner cards
|
||||
unsigned char buf[SIZE_STOC_FEATURE];
|
||||
const auto size = NetServer::CreateStampedPacket((unsigned char*)&cap, sizeof cap, buf, FEATURE_SENDER_SERVER);
|
||||
NetServer::SendBufferToPlayer(dp, STOC_CAPABILITY, buf, size);
|
||||
|
||||
@@ -96,7 +96,7 @@ void TagDuel::AttackPreview(DuelPlayer* dp, unsigned char* pdata, int len) {
|
||||
void TagDuel::SendServerCapability(DuelPlayer* dp) {
|
||||
CTOS_Capability cap;
|
||||
cap.protocol = FEATURE_PROTOCOL;
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW | FEATURE_TAG_PARTNER_CARDS; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag partner cards
|
||||
unsigned char buf[SIZE_STOC_FEATURE];
|
||||
const auto size = NetServer::CreateStampedPacket((unsigned char*)&cap, sizeof cap, buf, FEATURE_SENDER_SERVER);
|
||||
NetServer::SendBufferToPlayer(dp, STOC_CAPABILITY, buf, size);
|
||||
@@ -1375,6 +1375,8 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
RefreshExtra(0);
|
||||
RefreshExtra(1);
|
||||
start_duel(pduel, opt);
|
||||
SendTagPartnerCards(0); // YGOL tag partner cards: the waiting members' opening hands
|
||||
SendTagPartnerCards(1);
|
||||
if(host_info.time_limit) {
|
||||
time_elapsed = 0;
|
||||
#ifdef YGOPRO_SERVER_MODE
|
||||
@@ -2722,6 +2724,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
RefreshSzone(1, 0x681fff, 0);
|
||||
RefreshHand(0, 0x781fff, 0);
|
||||
RefreshHand(1, 0x781fff, 0);
|
||||
SendTagPartnerCards(player); // YGOL tag partner cards: the member that just left is the waiting one now
|
||||
break;
|
||||
}
|
||||
case MSG_MATCH_KILL: {
|
||||
@@ -2903,6 +2906,7 @@ void TagDuel::RequestField(DuelPlayer* dp) {
|
||||
std::vector<uint32_t> codes;
|
||||
if(BuildDeckList(player, DECK_LIST_SORTED, codes))
|
||||
SendDeckList(dp, player, DECK_LIST_SORTED, codes);
|
||||
SendTagPartnerCards(player, dp); // YGOL tag partner cards: a seat's field resync carries its side's waiting cards
|
||||
}
|
||||
|
||||
uint8_t query_buffer[SIZE_QUERY_BUFFER];
|
||||
@@ -3032,6 +3036,24 @@ void TagDuel::FlushDeckLists() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// YGOL tag partner cards: STOC_TAG_PARTNER_CARDS 0x5F = uint8_t side + the ygol_query_tag_cards bytes, to that side's two
|
||||
// seats only (never the other team, never an observer): after start_duel, after every MSG_TAG_SWAP, in a seat's field resync.
|
||||
void TagDuel::SendTagPartnerCards(int side, DuelPlayer* dp) {
|
||||
if(!pduel)
|
||||
return;
|
||||
unsigned char buf[1 + 6 + (2 * UINT8_MAX + MAINC_MAX) * sizeof(uint32_t)];
|
||||
buf[0] = (uint8_t)side;
|
||||
const int len = ygol_query_tag_cards(pduel, (uint8_t)side, buf + 1);
|
||||
if(len <= 0)
|
||||
return;
|
||||
if(dp) {
|
||||
NetServer::SendBufferToPlayer(dp, STOC_TAG_PARTNER_CARDS, buf, 1 + len);
|
||||
return;
|
||||
}
|
||||
for(int seat = side * 2; seat < side * 2 + 2; ++seat)
|
||||
if(players[seat])
|
||||
NetServer::SendBufferToPlayer(players[seat], STOC_TAG_PARTNER_CARDS, buf, 1 + len);
|
||||
}
|
||||
void TagDuel::TimeConfirm(DuelPlayer* dp) {
|
||||
if(host_info.time_limit == 0)
|
||||
return;
|
||||
|
||||
@@ -99,6 +99,7 @@ protected:
|
||||
bool has_profile[4]{};
|
||||
CTOS_Profile profile[4]{};
|
||||
std::vector<uint16_t> preview_attackers; // YGOL attack preview: location << 8 | sequence of every attacker the open battle prompt lists
|
||||
void SendTagPartnerCards(int side, DuelPlayer* dp = nullptr); // YGOL tag partner cards: STOC 0x5F to the side's two seats, or to dp alone
|
||||
// YGOL coin toss
|
||||
void BeginChoose(int chooser, uint8_t face);
|
||||
int choose_seat{};
|
||||
|
||||
Reference in new issue
Block a user