diff --git a/CHANGELOG.md b/CHANGELOG.md index b6724aa..473a017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,17 @@ 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.1.0 — 2026-10-15 -Nothing yet. +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 diff --git a/README.md b/README.md index 578b856..8d33371 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ library per platform, `ygol-engine`, behind a written contract. Proposal 47 in t | `build/windows.ps1` | Builds `out/win64/ygol-engine.dll` (+ `engine.json`), checks the contract header, runs the export gate. | | `build/Dockerfile` | The Linux x64 and Android arm64 builds, targets `linux` and `android`, same checks and gates. | | `build/linux.sh`, `build/android.sh` | Run the Docker targets into `out/linux-x64/` and `out/android-arm64/`. Need Docker and nothing else. | -| `binding/` | The C# binding `YGOLegacy.Engine` (the wire protocol: contracts, codecs, framing, routing) and its NUnit tests. See "Binding". | +| `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. | @@ -133,9 +133,15 @@ Windows VM: it has no nested virtualisation). From a clean clone on any Linux bo (`YGOLegacy.Engine.dll`, LangVersion 9, unsafe allowed, no package and no Unity reference) that holds the wire protocol under `Protocol/` in the namespaces `YGOLegacy.Protocol.{Contracts, Codecs, Framing, Routing}`: the message ids and payload records, the CTOS / STOC codecs, the -frame codec and the STOC router. Unity, the tools and the server repo's card-tester consume this -DLL instead of their own copies of the sources. `binding/YGOLegacy.Engine.Tests/` (`net8.0`, -NUnit) holds the fixtures; nothing in either project touches the native library. +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 diff --git a/binding/YGOLegacy.Engine.Tests/EngineApiParityTests.cs b/binding/YGOLegacy.Engine.Tests/EngineApiParityTests.cs new file mode 100644 index 0000000..073520b --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/EngineApiParityTests.cs @@ -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 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 ExternNames() + { + return typeof(EngineApi) + .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly) + .Where(m => m.GetCustomAttribute() != null) + .Select(m => m.Name) + .ToList(); + } + + [Test] + public void HeaderHas45Exports() + { + Assert.That(HeaderNames().Count, Is.EqualTo(45)); + } + + [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() != null) + .ToList(); + foreach (var method in methods) + { + var import = method.GetCustomAttribute(); + 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"); + } + } +} diff --git a/binding/YGOLegacy.Engine.Tests/GameMessageParityTests.cs b/binding/YGOLegacy.Engine.Tests/GameMessageParityTests.cs new file mode 100644 index 0000000..5c4fd4e --- /dev/null +++ b/binding/YGOLegacy.Engine.Tests/GameMessageParityTests.cs @@ -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 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 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"); + } + } +} diff --git a/binding/YGOLegacy.Engine/EngineApi.cs b/binding/YGOLegacy.Engine/EngineApi.cs new file mode 100644 index 0000000..fdc7488 --- /dev/null +++ b/binding/YGOLegacy.Engine/EngineApi.cs @@ -0,0 +1,154 @@ +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 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(); + } +} diff --git a/binding/YGOLegacy.Engine/EngineBinding.cs b/binding/YGOLegacy.Engine/EngineBinding.cs new file mode 100644 index 0000000..e487131 --- /dev/null +++ b/binding/YGOLegacy.Engine/EngineBinding.cs @@ -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."); + } + } +} diff --git a/binding/YGOLegacy.Engine/GameMessage.cs b/binding/YGOLegacy.Engine/GameMessage.cs new file mode 100644 index 0000000..eaa920f --- /dev/null +++ b/binding/YGOLegacy.Engine/GameMessage.cs @@ -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, + } +} diff --git a/binding/YGOLegacy.Engine/MessageScan.cs b/binding/YGOLegacy.Engine/MessageScan.cs new file mode 100644 index 0000000..4642ff2 --- /dev/null +++ b/binding/YGOLegacy.Engine/MessageScan.cs @@ -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; + } + } +} diff --git a/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj b/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj index 9c4bb18..ccfb287 100644 --- a/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj +++ b/binding/YGOLegacy.Engine/YGOLegacy.Engine.csproj @@ -16,4 +16,24 @@ false + + + $(IntermediateOutputPath)EngineBindingVersion.cs + + + + + + + + + + + + + + + + + diff --git a/contract/engine-contract.md b/contract/engine-contract.md index db4a703..329e28e 100644 --- a/contract/engine-contract.md +++ b/contract/engine-contract.md @@ -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 @@ -26,7 +27,8 @@ next to the library (`out/win64/engine.json` on Windows): "version": "v0.0.1", "exports": 334, "protocol": 8, - "capabilities": 2047 + "capabilities": 2047, + "binding": "v0.0.1" } ``` @@ -36,6 +38,7 @@ next to the library (`out/win64/engine.json` on Windows): | `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`. | +| `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. @@ -252,8 +255,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. @@ -397,3 +400,97 @@ 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). | +| `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_ ` in `core/common.h` (84), member = PascalCase of `` (`MSG_SELECT_BATTLECMD` -> `SelectBattlecmd`), value = ``. `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)` | +| `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.