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 | TagTwoFields | TagPartnerCards | TagSharedExtra | PromptContext; // 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 on Master Rule 4/5 gives each partner a Field slot (Spell/Trap sequence 5 and 6); a Tag room refuses a joiner without the bit. Client: it shows sequence 6 as the Field Zone and refuses a host without the bit. 0x800 is reserved by proposal 44. public const uint TagTwoFields = 0x1000; // 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. public const uint TagPartnerCards = 0x2000; // Server: with the setup pair ygol.tag.extra=shared a Tag team has one Extra Deck and its Extra Deck refreshes carry the partner each card came from; a Tag room refuses a joiner without the bit. Client: it reads the value and refuses a host without the bit. public const uint TagSharedExtra = 0x4000; // Server: right before every relayed prompt but rock-paper-scissors, the answering seat gets which card and which effect asks (0x44); never observers, never a replay. Client: it keeps the context on the open prompt. public const uint PromptContext = 0x8000; // 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 = 12; public const int ServerSender = 0xFF; public ushort Protocol { get; } public uint Flags { get; } public Capability(ushort protocol, uint flags) { Protocol = protocol; Flags = flags; } public bool Has(uint flag) { return (Flags & flag) == flag; } } public readonly struct AppearanceState { public const int ItemCount = 8; public const int DeckNameChars = 48; public const int CharacterIdChars = 64; public const int DeckGroupChars = 48; // Case, Protector, Field, Grave, Stand, Mate, Face, Frame: OnlineAppearanceSync's order. public int[] Items { get; } public string DeckName { get; } public string CharacterId { get; } public string DeckGroup { get; } public AppearanceState(int[] items, string deckName, string characterId, string deckGroup) { var copy = new int[ItemCount]; if (items != null) Array.Copy(items, copy, Math.Min(items.Length, ItemCount)); Items = copy; DeckName = deckName ?? string.Empty; CharacterId = characterId ?? string.Empty; DeckGroup = deckGroup ?? string.Empty; } } // CTOS/STOC 0x5D (patch 0020): a seated human's avatar id and frame id, as the sender wrote them; a receiver sanitizes both. public readonly struct ProfileState { public const byte CurrentVersion = 1; public const int AvatarIdChars = 32; public const int FrameIdChars = 16; public byte Version { get; } public string AvatarId { get; } public string FrameId { get; } public ProfileState(string avatarId, string frameId) : this(CurrentVersion, avatarId, frameId) { } public ProfileState(byte version, string avatarId, string frameId) { Version = version; AvatarId = avatarId ?? string.Empty; FrameId = frameId ?? string.Empty; } } // One attacker x target pair of CTOS/STOC 0x5E (patch 0023), in the asking seat's own zones; target location 0xFF = direct. public readonly struct AttackPreviewPair { public const byte DirectTarget = 0xFF; public const int Size = 4; public byte AttackerLocation { get; } public byte AttackerSequence { get; } public byte TargetLocation { get; } public byte TargetSequence { get; } public AttackPreviewPair(byte attackerLocation, byte attackerSequence, byte targetLocation, byte targetSequence) { AttackerLocation = attackerLocation; AttackerSequence = attackerSequence; TargetLocation = targetLocation; TargetSequence = targetSequence; } public static AttackPreviewPair Direct(byte attackerLocation, byte attackerSequence) => new AttackPreviewPair(attackerLocation, attackerSequence, DirectTarget, 0); public bool IsDirect => TargetLocation == DirectTarget; } // CTOS 0x5E: every pair of one battle prompt, asked once when the prompt opens. public readonly struct AttackPreviewQuery { public const byte CurrentVersion = 1; public const int MaxPairs = 255; public byte Version { get; } public AttackPreviewPair[] Pairs { get; } public AttackPreviewQuery(AttackPreviewPair[] pairs) : this(CurrentVersion, pairs) { } public AttackPreviewQuery(byte version, AttackPreviewPair[] pairs) { Version = version; Pairs = pairs ?? Array.Empty(); } } // One answered pair: the request echoed and the 24 bytes ygol_preview_attack wrote, undecoded (the duel's service decodes them). public readonly struct AttackPreviewEntry { public const int AnswerBytes = 24; public const int Size = AttackPreviewPair.Size + AnswerBytes; public AttackPreviewPair Pair { get; } public byte[] Answer { get; } public AttackPreviewEntry(AttackPreviewPair pair, byte[] answer) { Pair = pair; var copy = new byte[AnswerBytes]; if (answer != null) Array.Copy(answer, copy, Math.Min(answer.Length, AnswerBytes)); Answer = copy; } } // STOC 0x5E, to the asking seat only, no sender stamp: a refused pair is left out, never answered with zeros. public readonly struct AttackPreviewResult { public const byte CurrentVersion = 1; public byte Version { get; } public AttackPreviewEntry[] Entries { get; } public AttackPreviewResult(AttackPreviewEntry[] entries) : this(CurrentVersion, entries) { } public AttackPreviewResult(byte version, AttackPreviewEntry[] entries) { Version = version; Entries = entries ?? Array.Empty(); } } public readonly struct DialogueLine { public const byte CurrentVersion = 1; public const int KeyChars = 48; public byte Version { get; } public bool TargetFaceDown { get; } public short Index { get; } public uint CardCode { get; } public uint TargetCode { get; } public string CorpusKey { get; } public string EventKey { get; } public DialogueLine(byte version, bool targetFaceDown, short index, uint cardCode, uint targetCode, string corpusKey, string eventKey) { Version = version; TargetFaceDown = targetFaceDown; Index = index; CardCode = cardCode; TargetCode = targetCode; CorpusKey = corpusKey ?? string.Empty; EventKey = eventKey ?? string.Empty; } } public enum SeatPlanKind : byte { Open = 0, Cpu = 1, Reserved = 2, } public enum SeatStateKind : byte { None = 0, PickingDeck = 1, } // What a seated duelist is doing right now; the server keeps one per seat and replays it to joiners after the seat's appearance. public readonly struct SeatState { public const byte CurrentVersion = 1; public byte Version { get; } public SeatStateKind Kind { get; } // State-specific; 0 for every state today. public ushort Value { get; } public SeatState(SeatStateKind kind, ushort value = 0) : this(CurrentVersion, kind, value) { } public SeatState(byte version, SeatStateKind kind, ushort value) { Version = version; Kind = kind; Value = value; } } // CTOS from the host carries the claim tokens; the server's STOC echo carries neither tokens nor the deadline. public readonly struct SeatPlan { public const int MaxSeats = 4; public const int IdBytes = 16; public byte[] RestartId { get; } public uint DeadlineMs { get; } public ushort Revision { get; } public byte SeatCount { get; } public SeatPlanKind[] Kinds { get; } public byte[][] Tokens { get; } public SeatPlan(byte[] restartId, uint deadlineMs, ushort revision, byte seatCount, SeatPlanKind[] kinds, byte[][] tokens) { RestartId = SeatIds.Fixed(restartId); DeadlineMs = deadlineMs; Revision = revision; SeatCount = seatCount; Kinds = new SeatPlanKind[MaxSeats]; if (kinds != null) Array.Copy(kinds, Kinds, Math.Min(kinds.Length, MaxSeats)); Tokens = new byte[MaxSeats][]; for (var i = 0; i < MaxSeats; i++) Tokens[i] = SeatIds.Fixed(tokens != null && i < tokens.Length ? tokens[i] : null); } public SeatPlanKind Kind(int seat) => Kinds != null && seat >= 0 && seat < MaxSeats && seat < SeatCount ? Kinds[seat] : SeatPlanKind.Open; } public readonly struct SeatRequest { public const byte Observer = 0xFF; public ushort Protocol { get; } public byte[] RestartId { get; } public byte Seat { get; } public byte[] Token { get; } public SeatRequest(ushort protocol, byte[] restartId, byte seat, byte[] token) { Protocol = protocol; RestartId = SeatIds.Fixed(restartId); Seat = seat; Token = SeatIds.Fixed(token); } } public readonly struct SeatSwap { public byte First { get; } public byte Second { get; } public SeatSwap(byte first, byte second) { First = first; Second = second; } } // From = 0xFF: the sender, as a watcher. To = 0xFF: the watchers. public readonly struct SeatMove { public const byte Watchers = 0xFF; public byte From { get; } public byte To { get; } public SeatMove(byte from, byte to) { From = from; To = to; } } public enum RestartPhase : byte { None = 0, Prepare = 1, Commit = 2, Abort = 3, } public enum RestartReason : byte { None = 0, IncompatiblePeer = 1, AckTimeout = 2, NotInLobby = 3, NotHost = 4, Busy = 5, } public enum SeatResumeAction : byte { Complete = 1, Release = 2, } // Host -> server: one claim token per seat and one for every observer; the server hands each connection only its own. public readonly struct RestartPrepare { public byte[] RestartId { get; } public uint TimeoutMs { get; } public byte SeatCount { get; } public byte[][] SeatTokens { get; } public byte[] ObserverToken { get; } public RestartPrepare(byte[] restartId, uint timeoutMs, byte seatCount, byte[][] seatTokens, byte[] observerToken) { RestartId = SeatIds.Fixed(restartId); TimeoutMs = timeoutMs; SeatCount = seatCount; SeatTokens = new byte[SeatPlan.MaxSeats][]; for (var i = 0; i < SeatPlan.MaxSeats; i++) SeatTokens[i] = SeatIds.Fixed(seatTokens != null && i < seatTokens.Length ? seatTokens[i] : null); ObserverToken = SeatIds.Fixed(observerToken); } } // Server -> one connection: its own seat (0xFF = observer) and, in Prepare only, its own token. public readonly struct RoomRestarting { public RestartPhase Phase { get; } public byte[] RestartId { get; } public byte Seat { get; } public byte[] Token { get; } public uint TimeoutMs { get; } public RoomRestarting(RestartPhase phase, byte[] restartId, byte seat, byte[] token, uint timeoutMs) { Phase = phase; RestartId = SeatIds.Fixed(restartId); Seat = seat; Token = SeatIds.Fixed(token); TimeoutMs = timeoutMs; } } public readonly struct RestartAck { public byte[] RestartId { get; } public RestartPhase Phase { get; } public RestartAck(byte[] restartId, RestartPhase phase) { RestartId = SeatIds.Fixed(restartId); Phase = phase; } } public readonly struct RestartControl { public byte[] RestartId { get; } public RestartPhase Action { get; } public RestartControl(byte[] restartId, RestartPhase action) { RestartId = SeatIds.Fixed(restartId); Action = action; } } public readonly struct RestartStatus { public RestartPhase Phase { get; } public byte[] RestartId { get; } public byte Acked { get; } public byte Expected { get; } public bool Complete { get; } public RestartReason Reason { get; } public RestartStatus(RestartPhase phase, byte[] restartId, byte acked, byte expected, bool complete, RestartReason reason) { Phase = phase; RestartId = SeatIds.Fixed(restartId); Acked = acked; Expected = expected; Complete = complete; Reason = reason; } } public readonly struct SeatResume { public byte[] RestartId { get; } public SeatResumeAction Action { get; } public byte Reason { get; } public SeatResume(byte[] restartId, SeatResumeAction action, byte reason) { RestartId = SeatIds.Fixed(restartId); Action = action; Reason = reason; } } public readonly struct SeatResumeResult { public byte[] RestartId { get; } public bool Accepted { get; } public byte Seat { get; } public byte Reason { get; } public SeatResumeResult(byte[] restartId, bool accepted, byte seat, byte reason) { RestartId = SeatIds.Fixed(restartId); Accepted = accepted; Seat = seat; Reason = reason; } } // Host -> replacement server: the observers' shared claim token, then admission opens. public readonly struct RestartOpen { public byte[] RestartId { get; } public byte[] ObserverToken { get; } public RestartOpen(byte[] restartId, byte[] observerToken) { RestartId = SeatIds.Fixed(restartId); ObserverToken = SeatIds.Fixed(observerToken); } } public readonly struct RestartOpened { public byte[] RestartId { get; } public bool Opened { get; } public RestartOpened(byte[] restartId, bool opened) { RestartId = SeatIds.Fixed(restartId); Opened = opened; } } // STOC 0x5A, server-stamped: the match ended and the room stayed; the lobby every connection is back in (READY false on every seat). public readonly struct MatchOver { public const byte CurrentVersion = 1; public const int MaxSeats = 4; public byte Version { get; } public byte SeatCount { get; } private readonly byte occupied0, occupied1, occupied2, occupied3; public MatchOver(byte seatCount, bool[] occupied) : this(CurrentVersion, seatCount, occupied) { } public MatchOver(byte version, byte seatCount, bool[] occupied) { Version = version; SeatCount = seatCount; occupied0 = (byte)(occupied != null && occupied.Length > 0 && occupied[0] ? 1 : 0); occupied1 = (byte)(occupied != null && occupied.Length > 1 && occupied[1] ? 1 : 0); occupied2 = (byte)(occupied != null && occupied.Length > 2 && occupied[2] ? 1 : 0); occupied3 = (byte)(occupied != null && occupied.Length > 3 && occupied[3] ? 1 : 0); } public bool Occupied(int seat) => seat switch { 0 => occupied0 != 0, 1 => occupied1 != 0, 2 => occupied2 != 0, 3 => occupied3 != 0, _ => false }; } // Sorted: the owner's remaining cards by code. Ordered: the real order, top first. Submitted: the Main Deck in the zone, sorted. 1 and 2 reach observers only. public enum DeckListKind : byte { Sorted = 0, Ordered = 1, Submitted = 2, } // STOC 0x5C (patch 0019): one deck's contents for the side that owns it; no sender stamp. public readonly struct DeckList { public const byte CurrentVersion = 1; public const int MaxCards = 250; public byte Version { get; } public byte Side { get; } public DeckListKind Kind { get; } public int[] Codes { get; } public DeckList(byte side, DeckListKind kind, int[] codes) : this(CurrentVersion, side, kind, codes) { } public DeckList(byte version, byte side, DeckListKind kind, int[] codes) { Version = version; Side = side; Kind = kind; Codes = codes ?? Array.Empty(); } } // 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(); Extra = extra ?? Array.Empty(); Deck = deck ?? Array.Empty(); } public static int CodeOf(uint raw) => (int)(raw & ~FaceUpBit); public static bool IsFaceUp(uint raw) => (raw & FaceUpBit) != 0; } // STOC 0x44 (v1.7.0, TICKET-451): which card and which effect asks the prompt that follows; to the answering seat only, no sender stamp. public readonly struct PromptContext { public const byte CurrentVersion = 1; public const ushort UnknownIndex = 0xFFFF; public const byte PhaseOther = 0; public const byte PhaseCost = 1; public const byte PhaseTarget = 2; public const byte PhaseOperation = 3; public const byte PhaseAsk = 4; public const byte AnnouncePlain = 0; public const byte AnnounceLevel = 1; public const byte AnnounceDice = 2; public byte Version { get; } // False: no effect function runs (battle and idle commands, a plain summon); every other value is zero and EffectIndex is UnknownIndex. public bool HasEffect { get; } // The handler's current code; 0 when the answering player cannot see the card (EffectIndex and Description are then unknown too). public uint Code { get; } public byte Controller { get; } public byte Location { get; } public byte Sequence { get; } public byte Position { get; } // The effect's description (the aux.Stringid value), 0 when it has none. public ulong Description { get; } // The order the card's script registered the effect (the same in every duel); UnknownIndex for an effect the script did not register at load. public ushort EffectIndex { get; } // PhaseCost, PhaseTarget, PhaseOperation: that function of the effect runs; PhaseAsk: the core asks whether to use the effect. public byte Phase { get; } // The chain link the effect is, 0 when it is not on the chain. public byte ChainLink { get; } // MSG_ANNOUNCE_NUMBER only: AnnounceLevel (the script called Duel.AnnounceLevel), AnnounceDice (the asking effect is a visible dice effect); AnnouncePlain everywhere else. public byte AnnounceKind { get; } // The MSG_* id of the prompt this context belongs to. public byte Prompt { get; } public PromptContext(bool hasEffect, uint code, byte controller, byte location, byte sequence, byte position, ulong description, ushort effectIndex, byte phase, byte chainLink, byte announceKind, byte prompt) : this(CurrentVersion, hasEffect, code, controller, location, sequence, position, description, effectIndex, phase, chainLink, announceKind, prompt) { } public PromptContext(byte version, bool hasEffect, uint code, byte controller, byte location, byte sequence, byte position, ulong description, ushort effectIndex, byte phase, byte chainLink, byte announceKind, byte prompt) { Version = version; HasEffect = hasEffect; Code = code; Controller = controller; Location = location; Sequence = sequence; Position = position; Description = description; EffectIndex = effectIndex; Phase = phase; ChainLink = chainLink; AnnounceKind = announceKind; Prompt = prompt; } public static PromptContext None(byte prompt) => new PromptContext(false, 0, 0, 0, 0, 0, 0, UnknownIndex, PhaseOther, 0, AnnouncePlain, prompt); public bool IsHidden => HasEffect && Code == 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 { public int Seat { get; } public T Payload { get; } public Stamped(int seat, T payload) { Seat = seat; Payload = payload; } } }