15 Commits
Author SHA1 Message Date
donnyandClaude Opus 5.5 d1df1ffd67 server: no Side Deck limit, YGOPRO_MAX_SIDE 99 (TICKET-465, v1.7.3)
Release / linux (push) Successful in 2m35s
Release / windows (push) Successful in 44s
Release / android (push) Successful in 2m14s
Release / release (push) Successful in 6s
Release / attach-windows (push) Successful in 1s
LoadDeck dropped Side Deck cards past 15 while it received the deck, with no
error. The cap is 99 now, like the Extra Deck; DECKCOUNT_SIDE too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:31:37 -07:00
donny 9f924161d6 ci: runs-on [winold, windows] instead of unity-windows [skip ci]
The runner label unity-windows is retired (docs/runners.md in colony). Until this
pipeline works on any machine, its jobs stay on winold.
2026-11-26 17:19:16 -07:00
donnyandClaude Opus 5.5 d31b7b62d8 core: a Tag Field Spell takes the team's free Field slot (v1.7.2)
Release / release (push) Successful in 9s
Release / windows (push) Successful in 33s
Release / linux (push) Successful in 1m19s
Release / android (push) Successful in 59s
Release / attach-windows (push) Successful in 1s
get_fzone_landing sent a Field Spell to the playing partner's slot and
replaced the card there even when the other partner's slot was free; only
a control change took the free slot. A partner who got both of the team's
Fields back with Giant Trunade and played them one after the other lost
the first. Now a Field Spell takes the free slot whenever the playing
partner's is taken; with both taken it replaces the playing partner's.

Probe: new room "tag, two in one turn" (seq 5 then 6 on turn 1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WoiqG2TqZQmJ8tTn8tYpgy
2026-11-12 14:54:23 -07:00
donnyandClaude Opus 5.5 00ed2796f1 core: a card with a distant alias keeps its own setcodes (v1.7.1)
Release / release (push) Successful in 5s
Release / attach-windows (push) Successful in 3s
Release / linux (push) Successful in 2m4s
Release / windows (push) Successful in 54s
Release / android (push) Successful in 1m3s
A rule_code card answered is_set_card from the named card only, so a custom
card that adds an archetype its base card lacks lost it in the duel
(Vennominon 810000878 was not a "Venom" monster for Venom Fangs).
check_code_setcode adds the card's own setcodes while it bears its own
rule_code; is_set_card, is_pre_set_card and is_special_summon_set_card use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WoiqG2TqZQmJ8tTn8tYpgy
2026-11-11 11:48:31 -07:00
donnyandClaude Opus 5.5 313d8f34de changelog: v1.7.0 (TICKET-451)
Release / linux (push) Successful in 1m55s
Release / windows (push) Successful in 38s
Release / android (push) Successful in 1m13s
Release / release (push) Successful in 7s
Release / attach-windows (push) Successful in 2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:19:32 -07:00
donnyandClaude Opus 5.5 954fbfc65b prompt context: announce kind byte, record 23 bytes, STOC 0x44 24 bytes (TICKET-451, v1.7.0)
u8 announce_kind after chain_link, set only while MSG_ANNOUNCE_NUMBER is
open: 1 when the script called Duel.AnnounceLevel (it passes playerid +
0x10000 to the unit), else 2 when the asking effect has CATEGORY_DICE and is
visible to the answering player, else 0. Contract, changelog, binding
PromptContext.AnnounceKind + AnnouncePlain / Level / Dice, codec 24 bytes,
probe: plain 0, AnnounceLevel 1, a dice effect's AnnounceNumber 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:46:05 -07:00
donnyandClaude Opus 5.5 3f84b0b50b core: prompt context phase 4, the core asks whether to use an effect (TICKET-451, v1.7.0)
The core's own "use this effect?" prompts carry the asked effect in their
PROCESSOR_SELECT_EFFECTYN / SELECT_YESNO unit (optional trigger, lone quick
trigger 221, activation 94, replacements 218 / 219 / 220, Scrap Chimera), and
the unit pushes it on core.ygol_running as phase 4 while the prompt is open.
Contract row, changelog, binding PromptContext.PhaseAsk, probe check: an
optional End Phase trigger is asked with that card, index 2, phase 4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:11:14 -07:00
donnyandClaude Opus 5.5 ca2004112b contract: prompt context rows, changelog v1.7.0, probe suite (TICKET-451)
Release / windows (push) Successful in 40s
Release / android (push) Successful in 53s
Release / linux (push) Successful in 1m34s
Release / release (push) Skipped
Release / attach-windows (push) Skipped
Contract: the export row (22 bytes, the stable index, the hidden rule), the
0x44 message row (23 bytes), bit 0x8000, protocol 12, binding rows. README
export counts. Probe: Single, a second Single duel with another deck order
and an opponent without the bit, Tag: a card asks in cost, target and
operation, a Fusion's material procedure asks inside that operation and the
outer context comes back, then the card hides in the deck and asks both
players.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:05:09 -07:00
donnyandClaude Opus 5.5 458c9df105 binding: PromptContext record + codec, FeatureFlags.PromptContext, protocol 12 (TICKET-451, v1.7.0)
StocMessage.PromptContext 0x44, PromptContextCodec (23 bytes),
EngineApi.ygol_query_prompt_context, Capability.ProtocolVersion 12, tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:05:09 -07:00
donnyandClaude Opus 5.5 50706080c2 server: STOC_PROMPT_CONTEXT 0x44, FEATURE_PROMPT_CONTEXT 0x8000, protocol 12 (TICKET-451, v1.7.0)
The answering seat (Tag: cur_player) gets the 22 ygol_query_prompt_context
bytes + the prompt's MSG id right before every relayed prompt but
rock-paper-scissors, only when its capability has the bit. Never observers,
recorders or replays; no room refuses a joiner without the bit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:05:09 -07:00
donnyandClaude Opus 5.5 b6ef8a31bc core: ygol_query_prompt_context names the effect that asks a prompt (TICKET-451, v1.7.0)
field::execute_cost / execute_target / execute_operation push the running
effect (handler, description, stable index, phase 1 / 2 / 3, chain link) on
core.ygol_running at step 0 and pop it when the function finishes; the
innermost entry is the effect that asks. effect::ygol_script_index is stamped
in card::add_effect while the card loads (initial_effect.size()), 0xffff
otherwise. The export writes 22 bytes; a handler the asking player does not
control and that is not face-up answers code 0, index 0xffff, description 0.
Export gates 335 / 856 / 850 -> 336 / 857 / 851.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:05:08 -07:00
donnyandClaude Opus 5.5 4cd908d7af contract: Tag shared Extra Deck rows, changelog v1.6.0, probe suite (TICKET-433)
Release / release (push) Successful in 4s
Release / attach-windows (push) Successful in 1s
Release / linux (push) Successful in 1m19s
Release / windows (push) Successful in 41s
Release / android (push) Successful in 52s
The suite plays a pair-present and a pair-absent Tag room: a Summon of the
waiting partner's monster, the partner value across a move, and the replay
played back through the library. The contract states that bit 0x100000 stays
unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:54:35 -07:00
donnyandClaude Opus 5.5 c0dfa8ef19 binding: FeatureFlags.TagSharedExtra, protocol 11 (TICKET-433, v1.6.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:54:35 -07:00
donnyandClaude Opus 5.5 fa14698115 server: ygol.tag.extra=shared, FEATURE_TAG_SHARED_EXTRA 0x4000, protocol 11 (TICKET-433, v1.6.0)
The fourth server-read pair. TagDuel sets the option in opt, sends the sum of
both partners' Extra Decks in the opening MSG_START, runs the opening
RefreshExtra after start_duel, and adds QUERY_TAG_MEMBER in RefreshExtra. A Tag
room refuses a joiner without the bit; a Single room keeps it. Without the pair
every stream is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:54:35 -07:00
donnyandClaude Opus 5.5 8a73120dbb core: a Tag team can share one Extra Deck, each card keeps its partner (TICKET-433, v1.6.0)
Option DUEL_TAG_SHARED_EXTRA 0x200: start_duel moves tag_list_extra into
list_extra and renumbers, for both teams; tag_swap skips its Extra block.
card::tag_member is 0 from new_card and 1 from new_tag_card. QUERY_TAG_MEMBER
0x1000000 is written last in get_infos. Bit 0x100000 stays unused: old flags
(0xf81fff, 0x181fff, 0xFFFFFF) set it with no value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:54:34 -07:00
30 changed files with 1334 additions and 113 deletions

No files matched your search

+5 -5
View File
@@ -33,7 +33,7 @@ env:
jobs:
windows:
runs-on: unity-windows
runs-on: [winold, windows]
defaults:
run:
shell: powershell
@@ -57,7 +57,7 @@ jobs:
git clean -fdx -e out
if ($LASTEXITCODE -ne 0) { exit 1 }
- name: Build (contract check, export gate 335, engine.json)
- name: Build (contract check, export gate 336, engine.json)
id: build
run: |
$version = "local"
@@ -104,7 +104,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build (contract check, export gate 856, engine.json)
- name: Build (contract check, export gate 857, engine.json)
run: |
version=local
case "$GITHUB_REF" in refs/tags/v*) version="$GITHUB_REF_NAME";; esac
@@ -126,7 +126,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build (contract check, export gate 850, engine.json)
- name: Build (contract check, export gate 851, engine.json)
run: |
version=local
case "$GITHUB_REF" in refs/tags/v*) version="$GITHUB_REF_NAME";; esac
@@ -206,7 +206,7 @@ jobs:
attach-windows:
needs: [windows, release]
if: startsWith(github.ref, 'refs/tags/v')
runs-on: unity-windows
runs-on: [winold, windows]
defaults:
run:
shell: powershell
+49
View File
@@ -5,6 +5,55 @@ 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`).
## v1.7.3 — 2026-12-05
No Side Deck limit: the cap is 99, like the Extra Deck. No new export, message or capability bit:
exports 336 / 857 / 851, protocol 12, capabilities `0xF7FF`.
| Date | Change | Ticket | Contract part |
|---|---|---|---|
| 2026-12-05 | Server: `YGOPRO_MAX_SIDE` 15 -> 99 in `server/gframe/deck_manager.h` (`SIDE_MAX_SIZE`). `DeckManager::LoadDeck` dropped every Side Deck card past the cap while it RECEIVED the deck, before any rule check and with no error, and `CheckDeck` refused a longer Side Deck. `DECKCOUNT_SIDE` (server mode) is 99 too. The hard bound stays `SIDEC_MAX` (250). Every player of a room needs this engine, or the old one drops the surplus. | TICKET-465 | (b) wire: behaviour |
## v1.7.2 — 2026-11-12
In Tag, a Field Spell takes the team's free Field slot when the playing partner's slot is taken. No new export, message
or capability bit: exports 336 / 857 / 851, protocol 12, capabilities `0xF7FF`.
| Date | Change | Ticket | Contract part |
|---|---|---|---|
| 2026-11-12 | Core: `field::get_fzone_landing` sent a Field Spell to the playing partner's slot and replaced the card there even when the other partner's slot was free; only a control change took the free slot. A partner who got both of the team's Fields back to the hand ("Giant Trunade") and played them one after the other lost the first. Now any Field Spell that lands (activated, Set, `Duel.MoveToField` to `LOCATION_FZONE`) while the playing partner's slot is taken and the other is free takes the free one; when both are taken it replaces the playing partner's, as before. A Set offers that landing slot's bit. Probe: room "tag, two in one turn". | none (owner) | (d) Lua API: behaviour |
## v1.7.1 — 2026-11-11
A card whose cdb alias names another card keeps its own setcodes. No new export, message or capability bit:
exports 336 / 857 / 851, protocol 12, capabilities `0xF7FF`.
| Date | Change | Ticket | Contract part |
|---|---|---|---|
| 2026-11-11 | Core: a card read with a `rule_code` (a cdb alias outside the artwork range, which the readers turn into `rule_code`) answered `is_set_card` from the NAMED card's setcodes only, so a custom card that adds an archetype its base card lacks lost it in the duel ("Vennominon" 810000878, setcode `0x50`, named 72677437, setcode 0: "Venom Fangs" could not equip it; 21 cards of the custom pack). `card::check_code_setcode`: while the card's code is its own `rule_code`, its own `data.setcode` answers too, then the named card's. Used by `is_set_card`, `is_pre_set_card` and `is_special_summon_set_card`. A card renamed by `EFFECT_CHANGE_CODE` takes the new name's setcodes only, as before. Card.IsSetCard / IsPreviousSetCard / IsSummonSetCard. | none (owner) | (d) Lua API: behaviour |
## v1.7.0 — 2026-11-08
Prompt context (proposal 55): right before every prompt the answering seat learns which card and which effect asks.
One export, one message, capability `0x8000`, protocol 12: exports 336 / 857 / 851, capabilities `0xF7FF`. Record 23 bytes, message 24 bytes.
| Date | Change | Ticket | Contract part |
|---|---|---|---|
| 2026-11-08 | Core: `ygol_query_prompt_context(pduel, playerid, out)` (23 bytes: version, has effect, code, controller, location, sequence, position, u64 description, u16 effect index, phase, chain link, announce kind: 1 `Duel.AnnounceLevel`, 2 a visible `CATEGORY_DICE` effect, on `MSG_ANNOUNCE_NUMBER` only). `field::execute_cost` / `execute_target` / `execute_operation` push the running effect (handler, description, index, phase 1 / 2 / 3, chain link) on `core.ygol_running` at step 0 and pop it when the function finishes; the innermost one answers. The core's own "use this effect?" asks (optional trigger, lone quick trigger desc 221, desc 94, replacements 218 / 219 / 220, Scrap Chimera) carry the asked effect in their `PROCESSOR_SELECT_EFFECTYN` / `SELECT_YESNO` unit and push it as phase 4 (ask) while the prompt is open. `effect::ygol_script_index`: `card::add_effect` stamps `initial_effect.size()` while the card loads (`STATUS_INITIALIZING`), `0xFFFF` otherwise. A handler the asking player does not control and that is not face-up answers code 0, index `0xFFFF`, description 0. | TICKET-451 | (a) new export |
| 2026-11-08 | Server: `STOC_PROMPT_CONTEXT` `0x44` = those 23 bytes + the prompt's `MSG_*` id (24 bytes), to the answering seat (Tag: `cur_player`) right before every relayed prompt but rock-paper-scissors, only when its capability has the bit; never observers, recorders or replays. `FEATURE_PROMPT_CONTEXT` `0x8000` advertised by Single and Tag rooms, protocol 11 -> 12; no room refuses a joiner without it. Export gates 335 / 856 / 850 -> 336 / 857 / 851. | TICKET-451 | Wire: message `0x44`, capability bit `0x8000`, protocol 12 |
| 2026-11-08 | Binding: `StocMessage.PromptContext`, `FeatureFlags.PromptContext` (in `All`), the `PromptContext` record + `StocCodecs.PromptContext`, `EngineApi.ygol_query_prompt_context`, `Capability.ProtocolVersion` 12. Probe: the prompt context rooms (Single, a second Single duel whose opponent lacks the bit, Tag): a card asks in its cost, target and operation, a Fusion's material procedure asks inside that operation and the outer context comes back, the Fusion's optional End Phase trigger is asked with phase 4, announces say kind 0 / 1 / 2, then the card hides itself in the Deck and asks both players; a second duel with another deck order has the same indexes. | TICKET-451 | (e) C# binding |
## v1.6.0 — 2026-11-02
Tag shared Extra Deck (proposal 53): a setup pair gives a Tag team one Extra Deck, and each card keeps the partner who
brought it. No new export or message; capability `0x4000`, protocol 11: exports 335 / 856 / 850, capabilities `0x77FF`.
| Date | Change | Ticket | Contract part |
|---|---|---|---|
| 2026-11-02 | Core: option `DUEL_TAG_SHARED_EXTRA` `0x200`: `start_duel` moves `tag_list_extra` into `list_extra` and renumbers, for both teams; `tag_swap` skips its Extra block. `card::tag_member` (0 `new_card`, 1 `new_tag_card`), `QUERY_TAG_MEMBER` `0x1000000` written last in `get_infos`. Bit `0x100000` stays unused: old flags set it with no value. | TICKET-433 | (a) `start_duel` option; (c) Query records |
| 2026-11-02 | Server: `ygol.tag.extra=shared` is the fourth server-read pair. `TagDuel` sets the option in `opt`, sends the sum of both partners' Extra Decks in the opening `MSG_START`, runs the opening `RefreshExtra` after `start_duel`, and adds `QUERY_TAG_MEMBER` in `RefreshExtra`. `FEATURE_TAG_SHARED_EXTRA` `0x4000` advertised by Single and Tag rooms, protocol 10 -> 11; a Tag room refuses a joiner without the bit. | TICKET-433 | Wire: capability bit `0x4000`, protocol 11; (d) setup pair `ygol.tag.extra`; `0x5F` Extra count 0 in such a duel |
| 2026-11-02 | Binding: `FeatureFlags.TagSharedExtra` (in `All`), `Capability.ProtocolVersion` 11. Probe: the tag shared Extra Deck rooms (pair present, pair absent, a Summon of the waiting partner's monster, the replay played back through the library, the Tag refusal, the Single room that keeps an old client). | TICKET-433 | (e) C# binding |
## v1.5.0 — 2026-10-24
Tag two Field slots (proposal 45): a Tag team on Master Rule 4/5 holds one Field Spell per partner. No new
+6 -6
View File
@@ -81,9 +81,9 @@ pwsh C:\ygol-engine\build\windows.ps1 -Version v0.0.1
### The export gate is the truth
The script FAILS unless the DLL exports exactly **334** symbols: `start_server`, `stop_server`,
The script FAILS unless the DLL exports exactly **336** symbols: `start_server`, `stop_server`,
`ygol_engine_version`, and the core's whole C API re-exported, including the six `ygol_sb_*` Sandbox
exports and `ygol_preview_attack` (45 contract exports + 289 `sqlite3_*`; see the contract). A different count means the wrong tree, not "a small difference". For the
exports and `ygol_preview_attack` (47 contract exports, `ygol_query_tag_cards` and `ygol_query_prompt_context` included, + 289 `sqlite3_*`; see the contract). A different count means the wrong tree, not "a small difference". For the
record: the Unity repo's old `ygoserver.dll` exported 327 because its build applied patch 0008
(the `ygol_sb_*` six) only to `ocgcore.dll`, never to the server's own core copy; with one core they
are in the one library.
@@ -119,10 +119,10 @@ Windows VM: it has no nested virtualisation). From a clean clone on any Linux bo
built any more.
- The same contract-header check runs first, and the same export gate runs last, with the plain C
export count (`nm --dynamic --defined-only --extern-only`, names without a leading underscore; C++
symbols are `_Z`-mangled) and every name in `contract/ocgapi.h` present. Expected: **Linux 855**,
**Android 849** (the shipped Android server had 842: 841 + `ygol_preview_attack`; one core adds
symbols are `_Z`-mangled) and every name in `contract/ocgapi.h` present. Expected: **Linux 857**,
**Android 851** (the shipped Android server had 842: 841 + `ygol_preview_attack`; one core adds
the six `ygol_sb_*` and `ygol_engine_version`; `lua_*`, `event_*`, `z*`, ... count on these
platforms, unlike on Windows, so the numbers differ from 334; Linux has one more than Android,
platforms, unlike on Windows, so the numbers differ from 336; Linux has one more than Android,
`evutil_secure_rng_add_bytes`, which libevent only builds where glibc has no `arc4random`, so the
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/`.
@@ -190,7 +190,7 @@ the run's own `GITHUB_TOKEN`.
| `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, 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) |
| `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 (336 / 857 / 851) |
## Line endings
@@ -40,9 +40,9 @@ namespace YGOLegacy.Engine.Tests
}
[Test]
public void HeaderHas46Exports()
public void HeaderHas47Exports()
{
Assert.That(HeaderNames().Count, Is.EqualTo(46));
Assert.That(HeaderNames().Count, Is.EqualTo(47));
}
[Test]
@@ -158,7 +158,7 @@ namespace YGOLegacy.Protocol.Tests
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(0x37FB));
Assert.That(FeatureFlags.All, Is.EqualTo(0xF7FB));
var id = Enumerable.Repeat((byte)0xAB, 16).ToArray();
var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray();
@@ -273,11 +273,66 @@ namespace YGOLegacy.Protocol.Tests
}
[Test]
public void TagTwoFields_Flag_AndProtocol_ArePinned_0x1000_10()
public void TagTwoFields_Flag_IsPinned_0x1000()
{
Assert.That(FeatureFlags.TagTwoFields, Is.EqualTo(0x1000));
Assert.That(FeatureFlags.All & FeatureFlags.TagTwoFields, Is.EqualTo(FeatureFlags.TagTwoFields));
Assert.That(Capability.ProtocolVersion, Is.EqualTo(10));
}
[Test]
public void TagSharedExtra_Flag_IsPinned_0x4000()
{
Assert.That(FeatureFlags.TagSharedExtra, Is.EqualTo(0x4000));
Assert.That(FeatureFlags.All & FeatureFlags.TagSharedExtra, Is.EqualTo(FeatureFlags.TagSharedExtra));
}
[Test]
public void PromptContext_Id_Flag_Protocol_AndRoundTrip_ArePinned_0x44_0x8000_12_24()
{
Assert.That((int)StocCodecs.PromptContext.Id, Is.EqualTo(0x44));
Assert.That((int)StocMessage.PromptContext, Is.EqualTo(0x44));
Assert.That(FeatureFlags.PromptContext, Is.EqualTo(0x8000));
Assert.That(FeatureFlags.All & FeatureFlags.PromptContext, Is.EqualTo(FeatureFlags.PromptContext));
Assert.That(Capability.ProtocolVersion, Is.EqualTo(12));
Assert.That(PromptContextCodec.Size, Is.EqualTo(24));
Assert.That(new[] { PromptContext.AnnouncePlain, PromptContext.AnnounceLevel, PromptContext.AnnounceDice }, Is.EqualTo(new byte[] { 0, 1, 2 }));
Assert.That(new[] { PromptContext.PhaseOther, PromptContext.PhaseCost, PromptContext.PhaseTarget, PromptContext.PhaseOperation, PromptContext.PhaseAsk }, Is.EqualTo(new byte[] { 0, 1, 2, 3, 4 }));
const ulong description = 12960005233ul;
var payload = new PromptContext(true, 16178681u, 1, 0x04, 2, 0x1, description, 3, PromptContext.PhaseOperation, 2, PromptContext.AnnounceDice, 143);
var bytes = Bytes(w => StocCodecs.PromptContext.Write(w, payload));
Assert.That(bytes.Length, Is.EqualTo(24));
Assert.That(bytes[0], Is.EqualTo(1));
Assert.That(bytes[1], Is.EqualTo(1));
Assert.That(BitConverter.ToUInt32(bytes, 2), Is.EqualTo(16178681u));
Assert.That(bytes.Skip(6).Take(4).ToArray(), Is.EqualTo(new byte[] { 1, 0x04, 2, 0x1 }));
Assert.That(BitConverter.ToUInt64(bytes, 10), Is.EqualTo(description));
Assert.That(BitConverter.ToUInt16(bytes, 18), Is.EqualTo(3));
Assert.That(bytes.Skip(20).ToArray(), Is.EqualTo(new byte[] { 3, 2, 2, 143 }));
var read = StocCodecs.PromptContext.Read(Reader(bytes));
Assert.That(read.Version, Is.EqualTo(1));
Assert.That(read.HasEffect, Is.True);
Assert.That(read.IsHidden, Is.False);
Assert.That(read.Code, Is.EqualTo(16178681u));
Assert.That(read.Controller, Is.EqualTo(1));
Assert.That(read.Location, Is.EqualTo(0x04));
Assert.That(read.Sequence, Is.EqualTo(2));
Assert.That(read.Position, Is.EqualTo(0x1));
Assert.That(read.Description, Is.EqualTo(description));
Assert.That(read.EffectIndex, Is.EqualTo(3));
Assert.That(read.Phase, Is.EqualTo(PromptContext.PhaseOperation));
Assert.That(read.ChainLink, Is.EqualTo(2));
Assert.That(read.AnnounceKind, Is.EqualTo(PromptContext.AnnounceDice));
Assert.That(read.Prompt, Is.EqualTo(143));
var none = Bytes(w => StocCodecs.PromptContext.Write(w, PromptContext.None(10)));
Assert.That(none, Is.EqualTo(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 10 }));
Assert.That(StocCodecs.PromptContext.Read(Reader(none)).HasEffect, Is.False);
var hidden = StocCodecs.PromptContext.Read(Reader(Bytes(w => StocCodecs.PromptContext.Write(w, new PromptContext(true, 0, 1, 0x02, 0, 0x8, 0, PromptContext.UnknownIndex, PromptContext.PhaseCost, 1, PromptContext.AnnouncePlain, 13)))));
Assert.That(hidden.IsHidden, Is.True);
Assert.That(hidden.EffectIndex, Is.EqualTo(PromptContext.UnknownIndex));
Assert.Throws<EndOfStreamException>(() => StocCodecs.PromptContext.Read(Reader(bytes.Take(23).ToArray())));
}
[Test]
@@ -286,7 +341,6 @@ namespace YGOLegacy.Protocol.Tests
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(10));
Assert.That(TagPartnerCardsCodec.HeaderSize, Is.EqualTo(7));
var faceUpPendulum = 0x80000000u | 16178681u;
@@ -430,7 +484,7 @@ namespace YGOLegacy.Protocol.Tests
{
var bytes = Bytes(w => LobbyCodecs.Capability.Write(w, new Capability(Capability.ProtocolVersion, FeatureFlags.All)));
Assert.That(bytes, Is.EqualTo(Concat(Le16(10), Le32(0x37FB))));
Assert.That(bytes, Is.EqualTo(Concat(Le16(12), Le32(0xF7FB))));
var read = LobbyCodecs.Capability.Read(Reader(bytes));
Assert.That(read.Protocol, Is.EqualTo(Capability.ProtocolVersion));
@@ -283,7 +283,7 @@ namespace YGOLegacy.Protocol.Tests
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" });
"RoomRestarting", "RestartStatus", "SeatResumeResult", "RestartOpen", "SeatState", "MatchOver", "CoinToss", "DeckList", "Profile", "AttackPreview", "TagPartnerCards", "PromptContext" });
}
private static void AssertCatalogParity(Type catalog, Type[] legacyEnums, string[] expectedExtras)
+3
View File
@@ -91,6 +91,9 @@ namespace YGOLegacy.Engine
[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 ygol_query_prompt_context(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);
@@ -43,6 +43,7 @@ namespace YGOLegacy.Protocol.Codecs
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();
public static readonly PromptContextCodec PromptContext = new PromptContextCodec();
internal static long Remaining(BinaryReader reader)
{
@@ -213,6 +214,50 @@ namespace YGOLegacy.Protocol.Codecs
}
}
// The 23-byte ygol_query_prompt_context record (version, has effect, uint32 code, controller, location, sequence, position, uint64 description, uint16 effect index, phase, chain link, announce kind) + the prompt's MSG id; no sender stamp (v1.7.0, TICKET-451).
public sealed class PromptContextCodec : IStocCodec<PromptContext>
{
public const int Size = 24;
public StocMessage Id => StocMessage.PromptContext;
public PromptContext Read(BinaryReader reader)
{
StocCodecs.Require(reader, Size, Id);
var version = reader.ReadByte();
var hasEffect = reader.ReadByte() != 0;
var code = reader.ReadUInt32();
var controller = reader.ReadByte();
var location = reader.ReadByte();
var sequence = reader.ReadByte();
var position = reader.ReadByte();
var description = reader.ReadUInt64();
var effectIndex = reader.ReadUInt16();
var phase = reader.ReadByte();
var chainLink = reader.ReadByte();
var announceKind = reader.ReadByte();
var prompt = reader.ReadByte();
return new PromptContext(version, hasEffect, code, controller, location, sequence, position, description, effectIndex, phase, chainLink, announceKind, prompt);
}
public void Write(BinaryWriter writer, PromptContext payload)
{
writer.Write(payload.Version);
writer.Write((byte)(payload.HasEffect ? 1 : 0));
writer.Write(payload.Code);
writer.Write(payload.Controller);
writer.Write(payload.Location);
writer.Write(payload.Sequence);
writer.Write(payload.Position);
writer.Write(payload.Description);
writer.Write(payload.EffectIndex);
writer.Write(payload.Phase);
writer.Write(payload.ChainLink);
writer.Write(payload.AnnounceKind);
writer.Write(payload.Prompt);
}
}
public sealed class HostInfoCodec : IStocCodec<HostInfo>
{
public StocMessage Id => StocMessage.JoinGame;
@@ -6,7 +6,7 @@ namespace YGOLegacy.Protocol.Contracts
{
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;
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.
@@ -29,6 +29,10 @@ namespace YGOLegacy.Protocol.Contracts
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;
}
@@ -58,7 +62,7 @@ namespace YGOLegacy.Protocol.Contracts
public readonly struct Capability
{
public const ushort ProtocolVersion = 10;
public const ushort ProtocolVersion = 12;
public const int ServerSender = 0xFF;
public ushort Protocol { get; }
@@ -584,6 +588,67 @@ namespace YGOLegacy.Protocol.Contracts
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)
@@ -68,6 +68,7 @@ namespace YGOLegacy.Protocol.Contracts
Appearance = 0x41,
Dialogue = 0x42,
SetupPairs = 0x43,
PromptContext = 0x44,
SeatPlan = 0x50,
RoomRestarting = 0x54,
RestartStatus = 0x56,
+2 -2
View File
@@ -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 856 "$VERSION" /out
&& export-gate nm /out/libygol-engine.so 857 "$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 850 "$VERSION" /out
&& export-gate "$NDK_DIR"/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-nm /out/libygol-engine.so 851 "$VERSION" /out
FROM scratch AS android
COPY --from=android-build /out/ /
+2 -2
View File
@@ -21,7 +21,7 @@
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 335 symbols (start_server,
the script FAILS unless the DLL exports exactly 336 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.
@@ -30,7 +30,7 @@
param(
[string]$Premake = "C:\premake\premake5.exe",
[string]$Version = "local",
[int]$ExpectedExports = 335
[int]$ExpectedExports = 336
)
$ErrorActionPreference = "Stop"
+45 -18
View File
@@ -25,9 +25,9 @@ next to the library (`out/win64/engine.json` on Windows):
```json
{
"version": "v0.0.1",
"exports": 335,
"protocol": 10,
"capabilities": 14335,
"exports": 336,
"protocol": 12,
"capabilities": 63487,
"binding": "v0.0.1"
}
```
@@ -35,9 +35,9 @@ next to the library (`out/win64/engine.json` on Windows):
| 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: 335). |
| `protocol` | integer | `FEATURE_PROTOCOL` in `server/gframe/network.h` (10 as of 2026-10-24). |
| `capabilities` | integer | The OR of every `FEATURE_*` bit `SendServerCapability` advertises (`single_duel.cpp` and `tag_duel.cpp` must agree), as a decimal integer. 14335 = `0x37FF` = bits `0x1` to `0x400` plus `0x1000` and `0x2000` (`0x800` is reserved by proposal 44). |
| `exports` | integer | The library's export count after the gate passed (Windows: 336). |
| `protocol` | integer | `FEATURE_PROTOCOL` in `server/gframe/network.h` (12 as of 2026-11-08). |
| `capabilities` | integer | The OR of every `FEATURE_*` bit `SendServerCapability` advertises (`single_duel.cpp` and `tag_duel.cpp` must agree), as a decimal integer. 63487 = `0xF7FF` = bits `0x1` to `0x400` plus `0x1000` to `0x8000` (`0x800` is reserved by proposal 44). |
| `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.
@@ -52,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: 45 contract exports + 289 SQLite + 1 = 335; the extra 1 is `ygol_engine_version`, see below).
(Windows: 46 contract exports + 289 SQLite + 1 = 336; the extra 1 is `ygol_engine_version`, see below).
### Server exports (`server/gframe/serverapi.h`)
@@ -93,7 +93,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
| `create_duel_v2` | `intptr_t create_duel_v2(uint32_t seed_sequence[])` | Upstream (`SEED_COUNT` = 8 words) |
| `create_duel_ex` | `intptr_t create_duel_ex(uint_fast32_t seed, uint32_t create_flags)` | Upstream |
| `create_duel_v2_ex` | `intptr_t create_duel_v2_ex(uint32_t seed_sequence[], uint32_t create_flags)` | Upstream |
| `start_duel` | `void start_duel(intptr_t pduel, uint32_t options)` | Upstream |
| `start_duel` | `void start_duel(intptr_t pduel, uint32_t options)` | Upstream. v1.6.0: option `DUEL_TAG_SHARED_EXTRA` `0x200` with `DUEL_TAG_MODE` merges each team's Extra Decks (section (b), behaviour v1.6.0). |
| `end_duel` | `void end_duel(intptr_t pduel)` | Upstream |
| `set_player_info` | `void set_player_info(intptr_t pduel, int32_t playerid, int32_t lp, int32_t startcount, int32_t drawcount)` | Upstream |
| `get_log_message` | `void get_log_message(intptr_t pduel, char* buf)` | Upstream |
@@ -111,6 +111,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
| `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. |
| `ygol_query_prompt_context` | `int32_t ygol_query_prompt_context(intptr_t pduel, uint8_t playerid, uint8_t* out)` | v1.7.0 (TICKET-451), 2026-11-08. Which effect asks the prompt the engine is parked on, read only; `playerid` is the answering player. Returns 23 (the bytes written), 0 refused (bad pointer, bad player); a refusal writes nothing. `out` (23 bytes, little-endian): `u8 version` (1), `u8 has_effect`, `u32 code` (the handler's `get_code()` now), `u8 controller`, `u8 location`, `u8 sequence`, `u8 position` (the handler now), `u64 description` (the effect's, 0 when none), `u16 effect_index`, `u8 phase` (1 cost, 2 target, 3 operation, 4 ask), `u8 chain_link` (the newest chain link whose effect it is, 0 when none), `u8 announce_kind` (only while a `MSG_ANNOUNCE_NUMBER` is open: 1 the script called `Duel.AnnounceLevel`, which passes `playerid + 0x10000` to the unit; else 2 when the asking effect has `CATEGORY_DICE` and is visible to `playerid`; else 0; always 0 for any other prompt). The effect is the innermost frame on `core.ygol_running`: a cost / target / operation function running (`field::execute_cost` / `execute_target` / `execute_operation`, the core's only coroutine calls; phases 1 / 2 / 3), or an effect the core itself asks about (phase 4, "ask"): the frame lives while that `MSG_SELECT_EFFECTYN` / `MSG_SELECT_YESNO` is open, at the optional trigger (`processor.cpp`, desc 0), the lone quick trigger (desc 221), the cost-time activation ask (desc 94), the three replacement asks (`operations.cpp`, desc 218 / 220 / 219) and Scrap Chimera's material ask (its own description). Other prompts the core builds itself either list several effects (`MSG_SELECT_CHAIN`, `IDLECMD`, `BATTLECMD`, the `SELECT_OPTION` among replacement effects or activation ways) or ask about no effect (attack, desc 31; the Pendulum / Spell-zone redirect, desc 97; Tribute and material prompts): they push nothing and show whatever runs around them. None running (battle and idle commands, chain prompts, a Summon without an effect) = `has_effect` 0, every other byte 0 but `announce_kind`, and `effect_index` `0xFFFF`. **`effect_index`** is the order the card's script registered the effect while the card loaded (`card::add_effect` under `STATUS_INITIALIZING` stamps `initial_effect.size()`): the same in every duel and on every machine for that card's script; an effect registered at any other time (a clone, a copy, a grant, an effect made during the duel) is `0xFFFF`. **Hidden**: when the handler is not controlled by `playerid` and is not face-up (`is_position(POS_FACEUP)`: a face-down card, the other player's hand, Deck or face-down Extra Deck), `code` is 0, `effect_index` `0xFFFF` and `description` 0; the other fields stay. 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) |
@@ -132,7 +133,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 + 43 core = 46 contract exports, + 289 `sqlite3_*` = 335. The
Export count on Windows: 3 server + 44 core = 47 contract exports, + 289 `sqlite3_*` = 336. The
Unity repo's old `ygoserver.dll` had 327: its own core copy never carried patch 0008, and it had no
`ygol_engine_version`.
@@ -165,11 +166,12 @@ 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` (10) and `flags` = the OR of
the bits below (`0x37FF`). A client sends its own `CTOS_CAPABILITY` after joining. A client refuses a
`STOC_JOIN_GAME` and `STOC_TYPE_CHANGE`: `protocol` = `FEATURE_PROTOCOL` (12) and `flags` = the OR of
the bits below (`0xF7FF`). A client sends its own `CTOS_CAPABILITY` after joining. A client refuses a
host without bit `0x4` as out of date, and without bit `0x1000` too (v1.5.0). A Tag room refuses a
client whose `CTOS_CAPABILITY` lacks `0x1000`: `STOC_ERROR_MSG` `ERRMSG_VERERROR` (code =
`FEATURE_PROTOCOL`), then the connection is closed; a Single room keeps it.
client whose `CTOS_CAPABILITY` lacks `0x1000` or `0x4000` (v1.6.0): `STOC_ERROR_MSG` `ERRMSG_VERERROR`
(code = `FEATURE_PROTOCOL`), then the connection is closed; a Single room keeps it. No room refuses a client
without `0x8000` (v1.7.0): it just never gets `STOC_PROMPT_CONTEXT`.
**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,
@@ -205,6 +207,7 @@ duelist's own side (v1.2.0), both sides for an observer when spectators see all
| `0x41` | `STOC_APPEARANCE` | `u16 sender` + `CTOS_Appearance` (354) | Yes | Everyone; stored per seat, replayed to joiners, dropped when the seat empties or moves to the watchers | `0x1` | 1 | 0006 |
| `0x42` | `STOC_DIALOGUE` | `u16 sender` + `CTOS_Dialogue` (206) | Yes | Everyone | `0x2` | 1 | 0006 |
| `0x43` | `STOC_SETUP_PAIRS` | `u16 0xFF`, `u16 count`, then per pair `u16 length` + `key=value` bytes (no terminator) | Yes (`0xFF`) | Every joiner, in the snapshot | `0x4` | 1 | 0009 |
| `0x44` | `STOC_PROMPT_CONTEXT` | The 23 `ygol_query_prompt_context` bytes (section (a)) + `u8 prompt` (the `MSG_*` id of the prompt it belongs to); 24 bytes | No | The seat that answers the prompt (Tag: the team's current hand), and only when its `CTOS_CAPABILITY` had `0x8000`; the packet right before that prompt's `STOC_GAME_MSG`. Sent before every prompt the server relays but `MSG_ROCK_PAPER_SCISSORS`: `MSG_SELECT_BATTLECMD`, `IDLECMD`, `EFFECTYN`, `YESNO`, `OPTION`, `CARD`, `TRIBUTE`, `UNSELECT_CARD`, `CHAIN`, `PLACE`, `DISFIELD`, `POSITION`, `COUNTER`, `SUM`, `MSG_SORT_CARD`, `MSG_ANNOUNCE_RACE`, `ATTRIB`, `CARD`, `NUMBER`. A prompt with no effect running gets `has_effect` 0, so a client never keeps a stale context. Never to observers, the waiting Tag partner or the server-mode recorders, never in a replay; a `MSG_RETRY` re-ask gets none (the context still stands) | `0x8000` | 12 | v1.7.0 |
| `0x50` | `STOC_SEAT_PLAN` | `u16 0xFF` + `STOC_SeatPlan` (23): `u8 restart_id[16]`, `u16 revision`, `u8 seat_count`, `u8 kind[4]` (25 total; no token on the wire) | Yes (`0xFF`) | Everyone after a plan, swap or move; joiners in the snapshot | `0x8` | 2 | 0011 |
| `0x54` | `STOC_ROOM_RESTARTING` | `u16 0xFF` + `STOC_RoomRestarting` (38): `u8 phase` (1 Prepare, 2 Commit, 3 Abort), `u8 restart_id[16]`, `u8 seat`, `u8 token[16]`, `u32 timeout_ms` | Yes (`0xFF`) | Each participant, with ITS OWN seat and token only | `0x10` | 2 | 0012 |
| `0x56` | `STOC_RESTART_STATUS` | `u16 0xFF` + `STOC_RestartStatus` (21): `u8 phase`, `u8 restart_id[16]`, `u8 acked`, `u8 expected`, `u8 complete`, `u8 reason` (0 none, 1 incompatible, 2 ack timeout, 3 not lobby, 4 not host, 5 busy, 6 bad request) | Yes (`0xFF`) | The host only | `0x10` | 2 | 0012 |
@@ -236,6 +239,10 @@ duelist's own side (v1.2.0), both sides for an observer when spectators see all
| `0x800` | reserved | - | - | Proposal 44 (agreed, not shipped) |
| `0x1000` | `FEATURE_TAG_TWO_FIELDS` | 10 | v1.5.0 | Tag two Field slots: Spell/Trap sequence 6 is a team's second Field Zone (no message); a Tag room refuses a joiner without it |
| `0x2000` | `FEATURE_TAG_PARTNER_CARDS` | 9 | v1.2.0 | Tag partner cards (`STOC_TAG_PARTNER_CARDS`, `ygol_query_tag_cards`) |
| `0x4000` | `FEATURE_TAG_SHARED_EXTRA` | 11 | v1.6.0 | Tag shared Extra Deck: the setup pair `ygol.tag.extra=shared`, `QUERY_TAG_MEMBER` on Extra Deck refreshes; a Tag room refuses a joiner without it |
| v1.7.1 | A card read with a `rule_code` (a distant cdb alias) is a member of its OWN setcodes as well as those of the card it names: `Card.IsSetCard`, `Card.IsPreviousSetCard` and `Card.IsSummonSetCard` check `data.setcode` while the card bears its own `rule_code` (`card::check_code_setcode`). A card renamed by `EFFECT_CHANGE_CODE` answers from the new name only, as stock. No new message, no capability bit. |
| v1.7.2 | In Tag on Master Rule 4/5 a Field Spell that lands while the playing partner's Field slot is taken and the other partner's is free takes the free slot (`field::get_fzone_landing`); with both taken it replaces the playing partner's. Before, only a card that changed control took the free slot, so a partner who played the team's two Fields one after the other lost the first. No new export, message or bit; protocol 12. |
| `0x8000` | `FEATURE_PROMPT_CONTEXT` | 12 | v1.7.0 | Prompt context (`STOC_PROMPT_CONTEXT`, `ygol_query_prompt_context`): which card and which effect asks; no room refuses a joiner without it |
`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
@@ -246,7 +253,7 @@ carry a new feature inside another feature's message.
| Patch | Change |
|---|---|
| 0002 | Tag duel: teammates share one visible hand. |
| 0003 | `YGOPRO_MAX_EXTRA` = 99: `CTOS_UPDATE_DECK` with up to 99 extra deck cards is accepted (the stock server dropped the surplus silently while receiving). Rush rulesets cap it lower in the client. |
| 0003 | `YGOPRO_MAX_EXTRA` = 99: `CTOS_UPDATE_DECK` with up to 99 extra deck cards is accepted (the stock server dropped the surplus silently while receiving). |
| 0005 | The server keeps listening after the duel starts. A late observer gets `STOC_DUEL_START` and a field resync (`STOC_GAME_MSG` with `MSG_RELOAD_FIELD`), unmasked when spectators see all. |
| 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. |
@@ -254,7 +261,9 @@ carry a new feature inside another feature's message.
| 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. |
| v1.3.0 | Tag partner cards reach observers: when spectators see all, `STOC_TAG_PARTNER_CARDS` goes to every observer for both sides at every send point, plus both sides in an observer's resync and the late-watcher snapshot. Same id, same payload, no new capability bit (TICKET-412). |
| v1.4.0 | Life points per side: with the setup pair `ygol.side.b.lp=<n>` (section (d)) seat side B (seat 1; Tag seats 2 and 3) starts at `n` LP and side A at slot 8; without it both sides start at slot 8, as before. `set_player_info` gets each duel player its own LP, and `MSG_START` (the start and the late-watcher snapshot) carries `lp[0]`, `lp[1]` in duel player order: the side that goes first is player 0, so the two values swap when side B won the toss. `STOC_JOIN_GAME`'s `start_lp` stays side A's. Single, Match (every duel) and Tag; no new message, no capability bit. |
| v1.5.0 | Tag two Field slots (proposal 45, TICKET-384; core `field::has_two_fields` = `DUEL_TAG_MODE` on Master Rule 4 or 5): a team has a Field slot per partner, Spell/Trap sequence 5 for the partner who plays the team's first turn and 6 for the other (`player_info::tag_partner` flips in `tag_swap`). A Field Spell that lands (activated, Set, `Duel.MoveToField` to `LOCATION_FZONE`) goes to the playing partner's slot and replaces only the card there; one that changes control while that slot is taken and the other is free takes the free one. A Set opens only the landing slot's bit in `MSG_SELECT_PLACE`. `LOCATION_FZONE` covers both slots (`Card.IsLocation`, `Duel.GetMatchingGroup` and the other filters, `Duel.IsEnvironment`, `Duel.CheckLocation(p, LOCATION_FZONE, 0/1)`), `Duel.GetFieldCard(p, LOCATION_FZONE, 0)` is the playing partner's field, else the other one, and sequence 1 the remaining one; `Duel.GetFieldCard(p, LOCATION_SZONE, 6)` works. The second field reaches a client as `MSG_MOVE` to Spell/Trap sequence 6 and in `MSG_RELOAD_FIELD`'s sixth Spell/Trap entry: no new message. Singles, Match and Master Rule 3 (where slot 6 is a Pendulum Zone) are unchanged. Scripts that name Spell/Trap sequence 5 by number see one field (the TICKET-384 closing note lists them). Capability `0x1000`, protocol 9 -> 10. |
| v1.5.0 | Tag two Field slots (proposal 45, TICKET-384; core `field::has_two_fields` = `DUEL_TAG_MODE` on Master Rule 4 or 5): a team has a Field slot per partner, Spell/Trap sequence 5 for the partner who plays the team's first turn and 6 for the other (`player_info::tag_partner` flips in `tag_swap`). A Field Spell that lands (activated, Set, `Duel.MoveToField` to `LOCATION_FZONE`) goes to the playing partner's slot and replaces only the card there; while that slot is taken and the other is free it takes the free one (since v1.7.2; before, only a card that changed control did). A Set opens only the landing slot's bit in `MSG_SELECT_PLACE`. `LOCATION_FZONE` covers both slots (`Card.IsLocation`, `Duel.GetMatchingGroup` and the other filters, `Duel.IsEnvironment`, `Duel.CheckLocation(p, LOCATION_FZONE, 0/1)`), `Duel.GetFieldCard(p, LOCATION_FZONE, 0)` is the playing partner's field, else the other one, and sequence 1 the remaining one; `Duel.GetFieldCard(p, LOCATION_SZONE, 6)` works. The second field reaches a client as `MSG_MOVE` to Spell/Trap sequence 6 and in `MSG_RELOAD_FIELD`'s sixth Spell/Trap entry: no new message. Singles, Match and Master Rule 3 (where slot 6 is a Pendulum Zone) are unchanged. Scripts that name Spell/Trap sequence 5 by number see one field (the TICKET-384 closing note lists them). Capability `0x1000`, protocol 9 -> 10. |
| v1.6.0 | Tag shared Extra Deck (proposal 53, TICKET-433): with the setup pair `ygol.tag.extra=shared` (section (d)) `TagDuel` sets the duel option `DUEL_TAG_SHARED_EXTRA` `0x200`. `start_duel` moves each team's `tag_list_extra` into `list_extra` (the first partner's cards first) and renumbers the sequences, so either partner can Summon any of the cards; `tag_swap` leaves the Extra Deck alone, `MSG_TAG_SWAP` keeps its layout and sends the one list, and `ygol_query_tag_cards` / `0x5F` report an Extra count of 0. The opening `MSG_START` carries the sum of both partners' Extra Decks, and the opening Extra Deck refreshes run after `start_duel`. The core has one `owner` per team, so each card has `card::tag_member`, set once when it is loaded (0 `new_card`, 1 `new_tag_card`), and `RefreshExtra` adds `QUERY_TAG_MEMBER` to its flag in such a duel (section (c), Query records). Replays need no format change: `opt` holds the option and every reader passes `opt` to `start_duel`; a reader that writes its own `MSG_START` before `start_duel` must add the partner's Extra count. An older engine ignores the option and plays such a replay wrongly. Without the pair every stream is unchanged. Capability `0x4000`, protocol 10 -> 11. |
| v1.7.3 | `YGOPRO_MAX_SIDE` = 99 (and `DECKCOUNT_SIDE` in server mode): `CTOS_UPDATE_DECK` with up to 99 Side Deck cards is accepted, at the first deck and when side-decking between Match duels (before, the server dropped Side cards past 15 silently while receiving). No new message or capability bit (TICKET-465). |
### Replay
@@ -276,7 +285,8 @@ The table is the one `MessageScan.Scan` in the C# binding reads (section (e)); t
`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.
fork-related rows are marked. The prompt context (v1.7.0) is read beside the stream through
`ygol_query_prompt_context` while the engine is parked on a prompt; no message carries it.
| Id | Name | Payload length rule | Prompt |
|---|---|---|---|
@@ -379,6 +389,21 @@ fork-related rows are marked.
Ids 6, 7 and 34 are server-side (`network.h`); the core's `common.h` lists the rest. Any other id is
an error for the consumer.
### Query records
`query_card`, `query_field_card` and the query buffer of `MSG_UPDATE_DATA` / `MSG_UPDATE_CARD` hold one
record per card: `i32 length`, `u32 flag`, then one value per set `QUERY_*` bit in bit order, the bits
in `core/common.h`. The fork adds one bit:
| Bit | Name | Value | Since |
|---|---|---|---|
| `0x1000000` | `QUERY_TAG_MEMBER` | `u32`, written LAST, after `QUERY_LINK`: the partner who brought the card, 0 from `new_card`, 1 from `new_tag_card`. It never changes when the card moves. The core writes it for any caller that sets the bit; the server sets it only on `RefreshExtra` in a duel with `ygol.tag.extra=shared` | v1.6.0 |
**Bit `0x100000` stays unused.** Old flags set it with no value after it: `RefreshSingle`'s default
`0xf81fff`, the hand refresh `0x181fff` and YGOSharp's `0xFFFFFF` mask, and saved `.yrp3d` replays are
recorded streams of them. A value for that bit would shift every later field of those records, with no
error.
## (d) Setup pairs and the Lua API
### Setup pairs (patch 0009, TICKET-258; ADR 0004 in the Unity repo)
@@ -390,13 +415,14 @@ never interprets a pair: it stores the ordered list (max 64 pairs, 512 bytes eac
`0x40000000`) and sends them to every joiner as `STOC_SETUP_PAIRS` (`0x43`). Values that need `,`,
`=`, `%` or a space are percent-encoded by the client (`MatchSetup.cs`).
Three pairs ARE read by the server itself:
Four pairs ARE read by the server itself:
| Key | Value | Read by |
|---|---|---|
| `ygol.room.watchers` | `0` = no observers: every observer join and HsToObserver is refused | 0012 |
| `ygol.room.spectatorview` | `hidden` = the stock masked observer stream; absent = spectators see all | 0018, 0019 |
| `ygol.side.b.lp` | a positive integer: seat side B's start LP (seat 1; Tag seats 2 and 3); side A keeps slot 8. Absent, `0`, negative or not a number = both sides at slot 8 | v1.4.0 |
| `ygol.tag.extra` | `shared` = a Tag team has one Extra Deck (option `0x200`, section (b) v1.6.0); anything else or absent = separate Extra Decks. A Single or Match room ignores it | v1.6.0 |
Keys the Unity client sends today (`Assets/YGOLegacy/Scripts/Core/Duel/MatchSetup.cs`,
`SetupPairKeys`); the rules Lua reads them from the registry:
@@ -435,7 +461,7 @@ 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; v1.4.0 adds `ReplayFlags` (`SetupPairs` = `0x40000000`, `SideLp` = `0x20000000`); v1.5.0 adds `FeatureFlags.TagTwoFields` (`0x1000`, in `All`) and `Capability.ProtocolVersion` is 10. |
| `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; v1.4.0 adds `ReplayFlags` (`SetupPairs` = `0x40000000`, `SideLp` = `0x20000000`); v1.5.0 adds `FeatureFlags.TagTwoFields` (`0x1000`, in `All`) and `Capability.ProtocolVersion` is 10; v1.6.0 adds `FeatureFlags.TagSharedExtra` (`0x4000`, in `All`) and `Capability.ProtocolVersion` is 11; v1.7.0 adds `StocMessage.PromptContext` (`0x44`), `FeatureFlags.PromptContext` (`0x8000`, in `All`), the `PromptContext` record (`HasEffect`, `Code`, `Controller`, `Location`, `Sequence`, `Position`, `Description`, `EffectIndex`, `Phase`, `ChainLink`, `AnnounceKind`, `Prompt`, `IsHidden`, `None(prompt)`, `UnknownIndex` `0xFFFF`, `PhaseCost` / `PhaseTarget` / `PhaseOperation` / `PhaseAsk` 1 / 2 / 3 / 4, `AnnouncePlain` / `AnnounceLevel` / `AnnounceDice` 0 / 1 / 2) and `StocCodecs.PromptContext` (`PromptContextCodec`, 24 bytes), and `Capability.ProtocolVersion` is 12. |
| `YGOLegacy.Engine` | The four types below (TICKET-398). |
| Type | What |
@@ -477,6 +503,7 @@ Every row is one export of section (a) with its managed signature. A `string` pa
| `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)` |
| `ygol_query_prompt_context` | `int ygol_query_prompt_context(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)` |
+10
View File
@@ -90,6 +90,16 @@ OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_
// 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);
// [YGOL] v1.7.0 (prompt context, TICKET-451): which effect asks the prompt the engine is parked on, read only.
// playerid = the answering player. out (23 bytes): version (1), has_effect, uint32 code (the handler's current
// code), controller, location, sequence, position, uint64 description, uint16 effect_index (the order the
// card's script registered the effect in initial_effect; 0xffff unknown), phase (1 cost, 2 target, 3 operation, 4 the core asks whether to use the effect),
// chain link (0 none), announce kind (MSG_ANNOUNCE_NUMBER only: 1 Duel.AnnounceLevel, 2 the effect has
// CATEGORY_DICE and is visible, else 0). has_effect 0 = no effect runs: every other byte 0 but announce kind, effect_index 0xffff. A
// handler playerid does not control and that is not face-up writes code 0, effect_index 0xffff, description 0.
// Returns 23, 0 refused (bad pointer, bad player); a refusal writes nothing.
OCGCORE_API int32_t ygol_query_prompt_context(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);
+772 -19
View File
@@ -160,6 +160,33 @@
# Duel.GetFieldCard(tp, LOCATION_FZONE, 0) is the playing partner's field and 1
# the other, Duel.IsEnvironment and Card.IsLocation see sequence 6.
#
# With --dll it also gates v1.6.0 (proposal 53 / TICKET-433, Tag shared Extra Deck):
# the capability says protocol 11 + flag 0x4000 (single and tag); a Tag room
# refuses a joiner whose CTOS_CAPABILITY lacks 0x4000, a Single room keeps it. With
# ygol.tag.extra=shared MSG_START carries the sum of both partners' Extra Decks,
# the opening Extra Deck refresh lists all of them with QUERY_TAG_MEMBER 0x1000000
# (0 from seat 0 / 2, 1 from seat 1 / 3; the other team's masked copy has flag 0),
# 0x5F reports an Extra count of 0, seat 0 Summons seat 1's monster on turn 1,
# seat 1 returns it on turn 3, and the value is still 1 in the refresh after the
# swap of turn 5; a late watcher's snapshot refresh has the values; no
# other query carries the bit; the replay has option 0x200 and plays back through
# the library to the same Summons. Without the pair the partners' lists stay
# apart and no query carries the bit.
#
# With --dll it also gates v1.7.0 (proposal 55 / TICKET-451, prompt context): the capability says protocol 12 +
# flag 0x8000 (single and tag) and no room refuses a joiner without it. A card (Probe Ask) registers two effects
# that never run, then an Activate that asks a yes/no in its cost, an option in its target and a yes/no in its
# operation, runs a Fusion Monster's material procedure (which asks) inside that operation and asks again, shuffles
# itself into the deck and asks the opponent, then its controller. Every prompt a seat with
# 0x8000 gets comes right after one 24-byte PROMPT_CONTEXT (0x44) naming that prompt: idle, chain and battle
# prompts say no effect; cost / target / operation say Probe Ask, phase 1 / 2 / 3, effect index 2, its
# description, chain link 1; the nested procedure names the Fusion (index 1, chain link 0) and the operation's
# next prompt names Probe Ask again; an announce says kind 0 (plain), 1 (Duel.AnnounceLevel) or 2 (a dice effect);
# the Fusion's optional End Phase trigger is asked with phase 4 (ask), index 2;
# the opponent's yes/no names the card in the deck as hidden (code 0, index 0xFFFF,
# description 0) while its controller's next one still names it. A watcher with 0x8000, a seat without it and
# the waiting Tag partners get none; a second duel with another deck order reports the same indexes.
#
# 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
@@ -305,7 +332,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 == 10 and flags == 0x37FF, "%s: server capability is protocol 10, flags 0x37FF (appearance | dialogue | setup pairs | seat plan | rules restart | seat state | lobby after match | coin toss | deck lists | profile | attack preview | tag two fields | tag partner cards), got %d / 0x%x" % (who, proto, flags))
check(proto == 12 and flags == 0xF7FF, "%s: server capability is protocol 12, flags 0xF7FF (appearance | dialogue | setup pairs | seat plan | rules restart | seat state | lobby after match | coin toss | deck lists | profile | attack preview | tag two fields | tag partner cards | tag shared extra | prompt context), 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]
@@ -368,6 +395,8 @@ def main():
tag_partner_suite(o.dll, port + 110)
tag_across_swap_suite(o.dll, port + 120)
tag_two_fields_suite(o.dll, port + 130)
tag_shared_extra_suite(o.dll, port + 140)
prompt_context_suite(o.dll, port + 150)
print()
if failures:
print("FAILED: %d check(s)" % len(failures))
@@ -558,6 +587,17 @@ def make_workspace():
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_FIELD), "w", newline="\n") as f:
f.write(FIELD_LUA)
# proposal 53 (TICKET-433): a Fusion per seat and a Spell that Summons one or returns it
db = sqlite3.connect(os.path.join(root, "cards.cdb"))
for i, code in enumerate(PROBE_SEAT_FUSIONS):
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 65, 2000, 2000, 6, 1, 16, 0)", (code,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Seat Fusion %d', ''" % i + ", ''" * 16 + ")", (code,))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0)", (PROBE_EXTRA_SPELL,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Extra Spell', ''" + ", ''" * 16 + ")", (PROBE_EXTRA_SPELL,))
db.commit()
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_EXTRA_SPELL), "w", newline="\n") as f:
f.write(EXTRA_SPELL_LUA)
return root
@@ -1141,7 +1181,7 @@ def restart_room(dll_path, port, label, mode):
pk = drain_all([h, g, w])
check(not statuses(pk[g]) and not restarting(pk[h]), "%s: a non-host's Prepare is ignored" % label)
for c in (h, g, w):
c.send(CTOS_CAPABILITY, capability_bytes(2, 0x1F | FEATURE_TAG_TWO_FIELDS)) # a Tag room refuses a client without 0x1000 (proposal 45)
c.send(CTOS_CAPABILITY, capability_bytes(2, 0x1F | FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_SHARED_EXTRA)) # a Tag room refuses a client without 0x1000 (proposal 45) or 0x4000 (proposal 53)
drain_all([h, g, w])
h.send(CTOS_RESTART_PREPARE, prepare_bytes(rid, 30000, seats + 1, [ta, tb], tw))
pk = drain_all([h, g, w])
@@ -2690,7 +2730,7 @@ def tag_partner_room(dll_path, port, label, hidden):
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 == (10, 0x37FF), "%s: the tag server's capability is protocol 10, flags 0x37FF (got %s)" % (label, cap))
check(cap == (12, 0xF7FF), "%s: the tag server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
drain_all(everyone)
for c in seated:
c.send(CTOS_UPDATE_DECK, deck_bytes(TAG_PARTNER_DECKS[c.seat]))
@@ -3065,8 +3105,11 @@ def error_msgs(pkts):
return [d[0] for p, d in pkts if p == STOC_ERROR_MSG and d]
def tag_two_fields_room(dll_path, port, label):
print("== tag two Field slots, %s (seat 0 plays a Field on turn 1, seat 1 on turn 3, seat 0 again on turn 5)" % label)
def tag_two_fields_room(dll_path, port, label, first_turn_fields=1):
if first_turn_fields == 1:
print("== tag two Field slots, %s (seat 0 plays a Field on turn 1, seat 1 on turn 3, seat 0 again on turn 5)" % label)
else:
print("== tag two Field slots, %s (seat 0 plays two Fields on turn 1, seat 1 one on turn 3, seat 0 one on turn 5)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
@@ -3080,7 +3123,7 @@ def tag_two_fields_room(dll_path, port, label):
seated.append(c)
check([c.seat for c in seated] == [0, 1, 2, 3], "%s: four seats (%r)" % (label, [c.seat for c in seated]))
cap = server_capability(seated[0].log)
check(cap == (10, 0x37FF), "%s: the tag server's capability is protocol 10, flags 0x37FF (got %s)" % (label, cap))
check(cap == (12, 0xF7FF), "%s: the tag server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
drain_all(seated)
old = Client("127.0.0.1", port, "tf-old")
old.log = list(old.join())
@@ -3090,10 +3133,10 @@ def tag_two_fields_room(dll_path, port, label):
"%s: a joiner whose capability lacks 0x1000 gets ERROR_MSG VERERROR and is disconnected (seat %r, errors %r, closed %r)" % (label, old.seat, error_msgs(old.log), old.closed))
new = Client("127.0.0.1", port, "tf-new")
new.log = list(new.join())
new.send(CTOS_CAPABILITY, capability_bytes(10, 0x37FB))
new.send(CTOS_CAPABILITY, capability_bytes(11, 0x77FB))
new.log += new.drain(quiet=0.4)
check(new.seat == OBSERVER and not error_msgs(new.log) and not new.closed and stamped(new.log, STOC_CAPABILITY, OBSERVER) == [capability_bytes(10, 0x37FB)],
"%s: a joiner with 0x1000 stays and its CAPABILITY is relayed (errors %r, closed %r)" % (label, error_msgs(new.log), new.closed))
check(new.seat == OBSERVER and not error_msgs(new.log) and not new.closed and stamped(new.log, STOC_CAPABILITY, OBSERVER) == [capability_bytes(11, 0x77FB)],
"%s: a joiner with 0x1000 and 0x4000 stays and its CAPABILITY is relayed (errors %r, closed %r)" % (label, error_msgs(new.log), new.closed))
new.close()
drain_all(seated)
decks = {0: [PROBE_FIELD] * 40, 1: [PROBE_FIELD] * 40, 2: [PROBE_CARD] * 40, 3: [PROBE_CARD] * 40}
@@ -3101,7 +3144,7 @@ def tag_two_fields_room(dll_path, port, label):
c.send(CTOS_UPDATE_DECK, deck_bytes(decks[c.seat]))
pump(seated, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "acted": 0, "retries": 0, "moves": []}
state = {"turn": 0, "acted": {}, "retries": 0, "moves": []}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
@@ -3131,8 +3174,9 @@ def tag_two_fields_room(dll_path, port, label):
for k in range(5):
n += 1 + d[n] * 7
activatable = d[n]
if activatable and state["acted"] != state["turn"]:
state["acted"] = state["turn"]
allowed = first_turn_fields if state["turn"] == 1 else 1
if activatable and state["acted"].get(state["turn"], 0) < allowed:
state["acted"][state["turn"]] = state["acted"].get(state["turn"], 0) + 1
answer(c, struct.pack("<i", 5)) # activate the first card: a Probe Field
else:
answer(c, struct.pack("<i", 7)) # to the End Phase
@@ -3159,14 +3203,22 @@ def tag_two_fields_room(dll_path, port, label):
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
fields = [(turn, prev, cur) for turn, code, prev, cur in state["moves"] if code == PROBE_FIELD]
to_field = [(turn, cur[2]) for turn, prev, cur in fields if cur[0] == 0 and cur[1] == LOCATION_SZONE]
check(to_field == [(1, 5), (3, 6), (5, 5)],
"%s: seat 0's Field lands in sequence 5 on turn 1, seat 1's in sequence 6 on turn 3, seat 0's next in sequence 5 on turn 5 (%r)" % (label, to_field))
left = [(turn, prev[2], cur[1]) for turn, prev, cur in fields if prev[0] == 0 and prev[1] == LOCATION_SZONE]
check(left == [(5, 5, LOCATION_GRAVE)],
"%s: only the sequence-5 Field left, to the Graveyard on turn 5; the sequence-6 Field never moved (%r)" % (label, left))
hints = field_hints(seated[0].log)
check(hints == [0x53D1, 0x61F2, 0x51F2],
"%s: the core saw it so: turn 1 seq 5, 1 field, slot 1 free; turn 3 seq 6, 2 fields, GetFieldCard(FZONE, 0) = the playing partner's, 1 = the other; turn 5 seq 5, 2 fields (%s)" % (label, ["0x%X" % h for h in hints]))
if first_turn_fields == 1:
check(to_field == [(1, 5), (3, 6), (5, 5)],
"%s: seat 0's Field lands in sequence 5 on turn 1, seat 1's in sequence 6 on turn 3, seat 0's next in sequence 5 on turn 5 (%r)" % (label, to_field))
check(left == [(5, 5, LOCATION_GRAVE)],
"%s: only the sequence-5 Field left, to the Graveyard on turn 5; the sequence-6 Field never moved (%r)" % (label, left))
check(hints == [0x53D1, 0x61F2, 0x51F2],
"%s: the core saw it so: turn 1 seq 5, 1 field, slot 1 free; turn 3 seq 6, 2 fields, GetFieldCard(FZONE, 0) = the playing partner's, 1 = the other; turn 5 seq 5, 2 fields (%s)" % (label, ["0x%X" % h for h in hints]))
else:
check(to_field == [(1, 5), (1, 6), (3, 6), (5, 5)],
"%s: seat 0's first Field lands in sequence 5 and its second in the free sequence 6 on turn 1; seat 1's replaces sequence 6 on turn 3, seat 0's replaces sequence 5 on turn 5 (%r)" % (label, to_field))
check(left == [(3, 6, LOCATION_GRAVE), (5, 5, LOCATION_GRAVE)],
"%s: no Field left on turn 1; the sequence-6 Field went to the Graveyard on turn 3, the sequence-5 one on turn 5 (%r)" % (label, left))
check(hints == [0x53D1, 0x60F2, 0x61F2, 0x51F2],
"%s: the core saw it so: turn 1 seq 5 then seq 6 with 2 fields and GetFieldCard(FZONE, 0) = the first; turn 3 seq 6; turn 5 seq 5 (%s)" % (label, ["0x%X" % h for h in hints]))
check(all(not c.closed for c in seated), "%s: every seat is still connected" % label)
marks = marks_of(seated)
for c in seated[:2]:
@@ -3192,7 +3244,7 @@ def tag_two_fields_single(dll_path, port, label):
h = Client("127.0.0.1", port, "tf-host")
h.log = list(h.join())
cap = server_capability(h.log)
check(cap == (10, 0x37FF), "%s: the single server's capability is protocol 10, flags 0x37FF (got %s)" % (label, cap))
check(cap == (12, 0xF7FF), "%s: the single server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
h.send(CTOS_CAPABILITY, capability_bytes(9, 0x27FF))
h.log += h.drain(quiet=0.4)
check(h.seat == 0 and not error_msgs(h.log) and not h.closed and stamped(h.log, STOC_CAPABILITY, 0) == [capability_bytes(9, 0x27FF)],
@@ -3208,7 +3260,708 @@ def tag_two_fields_suite(dll_path, port):
print()
print("hosting the tag two Field slots rooms from %s" % dll_path)
tag_two_fields_room(dll_path, port, "tag")
tag_two_fields_room(dll_path, port + 2, "tag, two in one turn", first_turn_fields=2)
tag_two_fields_single(dll_path, port + 1, "single")
# --- proposal 53 (TICKET-433): Tag shared Extra Deck --------------------------------------------
# With the setup pair ygol.tag.extra=shared the server sets option 0x200 and start_duel moves the
# waiting partner's Extra Deck into the live list; tag_swap leaves it there. Each card keeps the
# partner who brought it, sent as QUERY_TAG_MEMBER on Extra Deck refreshes of that duel only.
# Capability 0x4000, protocol 11. Without the pair the lists stay apart.
FEATURE_TAG_SHARED_EXTRA = 0x4000
QUERY_TAG_MEMBER = 0x1000000
DUEL_TAG_SHARED_EXTRA = 0x200
TAG_EXTRA_PAIR = "ygol.tag.extra=shared"
PROBE_EXTRA_SPELL = PROBE_CARD + 900
PROBE_SEAT_FUSIONS = [PROBE_CARD + 901 + seat for seat in range(4)]
SEAT_EXTRA = {0: [PROBE_SEAT_FUSIONS[0]] * 2, 1: [PROBE_SEAT_FUSIONS[1]], 2: [PROBE_SEAT_FUSIONS[2]], 3: [PROBE_SEAT_FUSIONS[3]] * 3}
MSG_UPDATE_DATA, MSG_UPDATE_CARD, LOCATION_EXTRA = 6, 7, 0x40
EXTRA_SPELL_LUA = """--Probe Extra Spell (proposal 53): return your face-up Fusion Monster to the Extra Deck; with none, Special Summon 1 from it.
local s,id,o=GetID()
function s.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.onfield(c)
return c:IsFaceup() and c:IsType(TYPE_FUSION)
end
function s.inextra(c)
return c:IsType(TYPE_FUSION)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.onfield,tp,LOCATION_MZONE,0,1,nil) or Duel.IsExistingMatchingCard(s.inextra,tp,LOCATION_EXTRA,0,1,nil) end
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local f=Duel.GetFirstMatchingCard(s.onfield,tp,LOCATION_MZONE,0,nil)
if f then
Duel.SendtoDeck(f,nil,0,REASON_EFFECT)
return
end
local tc=Duel.SelectMatchingCard(tp,s.inextra,tp,LOCATION_EXTRA,0,1,1,nil):GetFirst()
if tc then Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP) end
end
"""
def query_records(d, at):
# (flag, code or None, value of QUERY_TAG_MEMBER or None) per record of a query buffer
out = []
while at + 4 <= len(d):
(clen,) = struct.unpack_from("<i", d, at)
if clen < 4:
break
if clen >= 8:
(flag,) = struct.unpack_from("<I", d, at + 4)
code = struct.unpack_from("<I", d, at + 8)[0] if flag & 1 and clen >= 12 else None
member = struct.unpack_from("<I", d, at + clen - 4)[0] if flag & QUERY_TAG_MEMBER else None
out.append((flag, code, member))
at += clen
return out
def extra_refreshes(pkts, side):
return [query_records(d, 3) for p, d in pkts if p == 0x01 and len(d) >= 3 and d[0] == MSG_UPDATE_DATA and d[1] == side and d[2] == LOCATION_EXTRA]
def other_queries_with_bit(pkts):
bad = 0
for p, d in pkts:
if p != 0x01 or len(d) < 3:
continue
if d[0] == MSG_UPDATE_DATA and d[2] != LOCATION_EXTRA:
bad += sum(1 for r in query_records(d, 3) if r[0] & QUERY_TAG_MEMBER)
elif d[0] == MSG_UPDATE_CARD:
bad += sum(1 for r in query_records(d, 4) if r[0] & QUERY_TAG_MEMBER)
return bad
def start_extra_counts(pkts):
# MSG_START: player, rule, i32 lp[2], u16 deck0, extra0, deck1, extra1
return [(struct.unpack_from("<H", d, 13)[0], struct.unpack_from("<H", d, 17)[0]) for p, d in pkts if p == 0x01 and len(d) >= 19 and d[0] == MSG_START]
def members_by_code(records):
return sorted((r[1], r[2]) for r in records)
def replay_duel_parts(body, flag):
# the replay body up to the responses: (opt, start_lp, start_hand, draw_count, decks, responses)
at = 4 + struct.unpack_from("<I", body, 0)[0] if flag & REPLAY_YGOL_SETUP_PAIRS else 0
at += 4 * 40
start_lp, start_hand, draw_count, opt = struct.unpack_from("<iiiI", body, at)
at += 16
decks = []
for _ in range(8):
(n,) = struct.unpack_from("<i", body, at)
decks.append(list(struct.unpack_from("<%dI" % n, body, at + 4)))
at += 4 + 4 * n
responses = []
while at < len(body):
n = body[at]
responses.append(body[at + 1:at + 1 + n])
at += 1 + n
return opt, start_lp, start_hand, draw_count, decks, responses
def play_replay_back(dll, seeds, parts, pairs):
# the library plays the recorded duel again, as a replay reader does: what start_duel made, then the Summons
opt, start_lp, start_hand, draw_count, decks, responses = parts
h = ctypes.c_ssize_t
dll.create_duel_v2.restype = h
dll.create_duel_v2.argtypes = [ctypes.POINTER(ctypes.c_uint32)]
dll.set_player_info.argtypes = [h, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32]
dll.set_registry_value.argtypes = [h, ctypes.c_char_p, ctypes.c_char_p]
dll.preload_script.argtypes = [h, ctypes.c_char_p]
dll.new_card.argtypes = [h, ctypes.c_uint32, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint8]
dll.new_tag_card.argtypes = [h, ctypes.c_uint32, ctypes.c_uint8, ctypes.c_uint8]
dll.start_duel.argtypes = [h, ctypes.c_uint32]
dll.process.restype = ctypes.c_uint32
dll.process.argtypes = [h]
dll.get_message.argtypes = [h, ctypes.c_char_p]
dll.set_responseb.argtypes = [h, ctypes.c_char_p]
dll.query_field_count.argtypes = [h, ctypes.c_uint8, ctypes.c_uint8]
dll.query_field_card.argtypes = [h, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint32, ctypes.c_char_p, ctypes.c_int32]
dll.ygol_query_tag_cards.argtypes = [h, ctypes.c_uint8, ctypes.c_char_p]
dll.end_duel.argtypes = [h]
d = dll.create_duel_v2((ctypes.c_uint32 * 8)(*seeds))
for pair in pairs:
k, v = pair.split("=", 1)
dll.set_registry_value(d, k.encode(), v.encode())
dll.set_player_info(d, 0, start_lp, start_hand, draw_count)
dll.set_player_info(d, 1, start_lp, start_hand, draw_count)
dll.preload_script(d, b"./script/init.lua")
for i, codes in enumerate(decks):
team, kind = i // 4, i % 4
for code in codes:
location = LOCATION_EXTRA if kind % 2 else 0x01
if kind < 2:
dll.new_card(d, code, team, team, location, 0, 0x08)
else:
dll.new_tag_card(d, code, team, location)
dll.start_duel(d, opt)
buf = ctypes.create_string_buffer(0x40000)
out = {"counts": (dll.query_field_count(d, 0, LOCATION_EXTRA), dll.query_field_count(d, 1, LOCATION_EXTRA))}
def extra(team):
n = dll.query_field_card(d, team, LOCATION_EXTRA, 0x1 | QUERY_TAG_MEMBER, buf, 0)
return members_by_code(query_records(buf.raw[:n], 0))
def waiting_extra(team):
dll.ygol_query_tag_cards(d, team, buf)
return buf.raw[2]
out["opening"] = (extra(0), extra(1))
out["waiting"] = (waiting_extra(0), waiting_extra(1))
stream = b""
left = list(responses)
for _ in range(100000):
r = dll.process(d)
n = r & 0x0FFFFFFF
if n:
got = dll.get_message(d, buf)
stream += buf.raw[:got]
if r & 0x20000000:
break
if r & 0x10000000:
if not left:
break
one = ctypes.create_string_buffer(left.pop(0), 256)
dll.set_responseb(d, one)
out["responses_left"] = len(left)
out["summons"] = []
at = 0
while True:
at = stream.find(bytes([MSG_SPSUMMONING]), at)
if at < 0 or at + 5 > len(stream):
break
(code,) = struct.unpack_from("<I", stream, at + 1)
if code in PROBE_SEAT_FUSIONS:
out["summons"].append(code)
at += 1
out["end_extra"] = extra(0)
dll.end_duel(d)
return out
def tag_shared_extra_room(dll_path, port, label, shared):
print("== tag shared Extra Deck, %s" % label)
F0, F1, F2, F3 = PROBE_SEAT_FUSIONS
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
pairs = [TAG_EXTRA_PAIR] if shared else []
write_special(root, pairs)
dll, thread = host_dll(dll_path, port, 2, " ".join(pairs))
seated = []
for i in range(4):
c = Client("127.0.0.1", port, "se-seat%d" % i)
c.log = list(c.join())
seated.append(c)
check([c.seat for c in seated] == [0, 1, 2, 3], "%s: four seats (%r)" % (label, [c.seat for c in seated]))
cap = server_capability(seated[0].log)
check(cap == (12, 0xF7FF), "%s: the tag server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
drain_all(seated)
old = Client("127.0.0.1", port, "se-old")
old.log = list(old.join())
old.send(CTOS_CAPABILITY, capability_bytes(10, 0x37FF))
old.log += old.drain(quiet=0.4)
check(old.seat == OBSERVER and error_msgs(old.log) == [ERRMSG_VERERROR] and old.closed,
"%s: a joiner with 0x1000 but without 0x4000 gets ERROR_MSG VERERROR and is disconnected (seat %r, errors %r, closed %r)" % (label, old.seat, error_msgs(old.log), old.closed))
drain_all(seated)
watcher = Client("127.0.0.1", port, "se-watch")
watcher.log = list(watcher.join())
drain_all(seated + [watcher])
for c in seated:
spell = PROBE_EXTRA_SPELL if c.seat < 2 else PROBE_KNIGHT
c.send(CTOS_UPDATE_DECK, deck_bytes([spell] * 40 + SEAT_EXTRA[c.seat]))
pump(seated, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "acted": 0, "retries": 0, "selects": [], "summons": [], "swaps": []}
picks = {1: F1, 5: F0} if shared else {1: F0}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
c.send(CTOS_RESPONSE, payload)
def play(until, limit):
deadline = time.time() + limit
while time.time() < deadline:
watcher.log += watcher.drain(quiet=0.02, limit=0.1)
for c in seated:
for pid, d in c.drain(quiet=0.02, limit=0.2):
c.log.append((pid, d))
if pid == STOC_SELECT_TP:
c.send(CTOS_TP_RESULT, bytes([1 if c.seat == 0 else 0])) # side A (seats 0 + 1) goes first
continue
if pid != 0x01 or not d:
continue
t = d[0]
if t == MSG_NEW_TURN and c.seat == 0:
state["turn"] += 1
elif t == MSG_TAG_SWAP and c.seat == 0 and d[1] == 0:
state["swaps"].append((state["turn"], d[3], d[4], len(c.log) - 1))
elif t == MSG_SPSUMMONING and c.seat == 0:
state["summons"].append((state["turn"], struct.unpack_from("<I", d, 1)[0]))
elif t == MSG_RETRY:
state["retries"] += 1
elif t == MSG_SELECT_IDLECMD:
n = 2
for k in range(5):
n += 1 + d[n] * 7
activatable = d[n]
if activatable and state["acted"] != state["turn"]:
state["acted"] = state["turn"]
answer(c, struct.pack("<i", 5)) # activate the first card: the Spell
else:
answer(c, struct.pack("<i", 7)) # to the End Phase
elif t == MSG_SELECT_CARD:
cards = [struct.unpack_from("<II", d, 6 + 8 * i) for i in range(d[5])]
state["selects"].append((state["turn"], sorted((info_location(v)[2], code) for code, v in cards)))
want = picks.get(state["turn"])
answer(c, bytes([1, next((i for i, card in enumerate(cards) if card[0] == want), 0)]))
elif t == MSG_SELECT_TRIBUTE:
answer(c, bytes([1, 0]))
elif t == MSG_SELECT_CHAIN:
answer(c, struct.pack("<i", -1))
elif t in (MSG_SELECT_PLACE, MSG_SELECT_DISFIELD):
answer(c, first_free_zone(d))
elif t == MSG_SELECT_POSITION:
answer(c, struct.pack("<i", next(b for b in (1, 2, 4, 8) if d[6] & b)))
elif t in (MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO):
answer(c, struct.pack("<i", 1))
elif t in (MSG_SELECT_OPTION, MSG_SELECT_BATTLECMD):
answer(c, struct.pack("<i", 0 if t == MSG_SELECT_OPTION else 3))
if until():
return True
if any(c.closed for c in seated):
return False
return until()
last_turn = 6 if shared else 4
ok = play(lambda: state["turn"] >= last_turn, limit=60)
check(ok, "%s: the duel reached turn %d (turn %d)" % (label, last_turn, state["turn"]))
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
for c in seated:
check(start_extra_counts(c.log) == [(3, 4) if shared else (2, 1)], "%s: seat %d's MSG_START gives the Extra Deck counts %s (%r)" % (label, c.seat, (3, 4) if shared else (2, 1), start_extra_counts(c.log)))
check(other_queries_with_bit(c.log) == 0, "%s: seat %d: no other query carries QUERY_TAG_MEMBER (%d)" % (label, c.seat, other_queries_with_bit(c.log)))
if shared:
opening = {0: [(F0, 0), (F0, 0), (F1, 1)], 1: [(F2, 0), (F3, 1), (F3, 1), (F3, 1)]}
for c in seated:
own, other = c.seat // 2, 1 - c.seat // 2
first = extra_refreshes(c.log, own)
check(bool(first) and members_by_code(first[0]) == opening[own], "%s: seat %d's first Extra Deck refresh lists both partners' cards with the partner each came from (%r)" % (label, c.seat, members_by_code(first[0]) if first else None))
masked = extra_refreshes(c.log, other)
check(bool(masked) and len(masked[0]) == len(opening[other]) and all(r[0] == 0 for r in masked[0]), "%s: seat %d's copy of the other team's refresh is masked, flag 0, no value (%r)" % (label, c.seat, masked[0] if masked else None))
cards = partner_cards(c.log, own)
check(bool(cards) and all(g[3] == [] for g in cards) and len(cards[0][2]) == 5, "%s: seat %d's TAG_PARTNER_CARDS report an Extra count of 0, and the waiting hand stays (%r)" % (label, c.seat, [(g[3], len(g[2] or [])) for g in cards]))
for team in (0, 1):
first = extra_refreshes(watcher.log, team)
check(bool(first) and members_by_code(first[0]) == opening[team], "%s: the watcher's first refresh of side %d has the values too (%r)" % (label, team, members_by_code(first[0]) if first else None))
check(state["selects"][:1] == [(1, [(0, F0), (1, F0), (2, F1)])],
"%s: on turn 1 seat 0 is offered both partners' Fusions, in sequences 0, 1, 2 (%r)" % (label, state["selects"][:1]))
check(state["summons"] == [(1, F1), (5, F0)], "%s: seat 0 Summons seat 1's monster on turn 1, its own on turn 5 (%r)" % (label, state["summons"]))
check([s[:3] for s in state["swaps"]] == [(3, 2, 0), (5, 3, 0)],
"%s: MSG_TAG_SWAP keeps the one list: 2 cards on turn 3, 3 on turn 5 when seat 1 returned the Fusion (%r)" % (label, [s[:3] for s in state["swaps"]]))
log = seated[0].log
after = extra_refreshes(log[state["swaps"][1][3]:], 0) if len(state["swaps"]) > 1 else []
check(bool(after) and members_by_code(after[0]) == [(F0, 0), (F0, 0), (F1, 1)], "%s: after the swap of turn 5 the Fusion that moved still says partner 1 (%r)" % (label, members_by_code(after[0]) if after else None))
late = Client("127.0.0.1", port, "se-late")
late.log = list(late.join())
late.log += late.drain(quiet=0.6)
snapshot = extra_refreshes(late.log, 0)
check(bool(snapshot) and members_by_code(snapshot[0]) == [(F0, 0), (F1, 1)], "%s: a late watcher's snapshot refresh has the values (flag 0xefffff + the bit) (%r)" % (label, members_by_code(snapshot[0]) if snapshot else None))
late.close()
else:
for c in seated + [watcher]:
for team in (0, 1):
records = [r for refresh in extra_refreshes(c.log, team) for r in refresh]
check(bool(records) and not any(r[0] & QUERY_TAG_MEMBER for r in records), "%s: %s: no Extra Deck refresh of side %d carries the bit" % (label, c.name, team))
cards = partner_cards(seated[0].log, 0)
check(bool(cards) and cards[0][3] == [F1], "%s: the opening TAG_PARTNER_CARDS report the waiting partner's Extra Deck (%r)" % (label, cards[0][3] if cards else None))
check(state["selects"][:1] == [(1, [(0, F0), (1, F0)])], "%s: on turn 1 seat 0 is offered only its own Fusions (%r)" % (label, state["selects"][:1]))
check(state["summons"] == [(1, F0)], "%s: seat 0 Summons its own monster on turn 1 (%r)" % (label, state["summons"]))
check([s[:3] for s in state["swaps"]] == [(3, 1, 0)], "%s: the swap of turn 3 brings seat 1's Extra Deck (%r)" % (label, [s[:3] for s in state["swaps"]]))
marks = marks_of(seated)
for c in seated[:2]:
c.send(CTOS_SURRENDER)
ok = pump(seated, lambda: all(match_overs(since(c, marks)) for c in seated), limit=10)
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone" % label)
reps = replays(seated[0])
if check(len(reps) == 1, "%s: one REPLAY arrived (%d)" % (label, len(reps))):
flag, seeds, body = reps[0]
parts = replay_duel_parts(body, flag)
check(bool(parts[0] & DUEL_TAG_SHARED_EXTRA) == shared, "%s: the replay's opt %s option 0x200 (opt 0x%x)" % (label, "has" if shared else "does not have", parts[0]))
back = play_replay_back(dll, seeds, parts, pairs)
if shared:
check(back["counts"] == (3, 4) and back["waiting"] == (0, 0), "%s: replay: start_duel merged: live Extra Decks 3 and 4, waiting lists 0 (%r, %r)" % (label, back["counts"], back["waiting"]))
check(back["opening"] == ([(F0, 0), (F0, 0), (F1, 1)], [(F2, 0), (F3, 1), (F3, 1), (F3, 1)]), "%s: replay: the query gives each card its partner (%r)" % (label, back["opening"]))
check(back["summons"] == [F1, F0], "%s: replay: the recorded answers Summon the waiting partner's monster, then seat 0's (%r)" % (label, back["summons"]))
check(back["responses_left"] == 0 and back["end_extra"] == [(F0, 0), (F1, 1)], "%s: replay: every answer was used and the Extra Deck ends as it did live (%d left, %r)" % (label, back["responses_left"], back["end_extra"]))
else:
check(back["counts"] == (2, 1) and back["waiting"] == (1, 3), "%s: replay: the lists stay apart: live 2 and 1, waiting 1 and 3 (%r, %r)" % (label, back["counts"], back["waiting"]))
check(back["summons"] == [F0] and back["responses_left"] == 0, "%s: replay: the recorded answers Summon the same monster (%r, %d left)" % (label, back["summons"], back["responses_left"]))
for c in seated + [watcher]:
c.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_shared_extra_single(dll_path, port, label):
print("== tag shared Extra Deck, %s (a Single room keeps a client without 0x4000)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
write_special(root, [])
dll, thread = host_dll(dll_path, port, 0)
h = Client("127.0.0.1", port, "se-host")
h.log = list(h.join())
h.send(CTOS_CAPABILITY, capability_bytes(10, 0x37FF))
h.log += h.drain(quiet=0.4)
check(h.seat == 0 and not error_msgs(h.log) and not h.closed, "%s: a seat whose capability lacks 0x4000 stays (errors %r, closed %r)" % (label, error_msgs(h.log), h.closed))
h.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_shared_extra_suite(dll_path, port):
print()
print("hosting the tag shared Extra Deck rooms from %s" % dll_path)
tag_shared_extra_room(dll_path, port, "pair present", True)
tag_shared_extra_room(dll_path, port + 1, "pair absent", False)
tag_shared_extra_single(dll_path, port + 2, "single")
# --- v1.7.0 (proposal 55 / TICKET-451): prompt context ----------------------------
STOC_PROMPT_CONTEXT = 0x44
NAMES.update({0x44: "PROMPT_CONTEXT"})
PROBE_ASK = PROBE_CARD + 1000
PROBE_ASK_FUSION = PROBE_CARD + 1001
LOCATION_DECK = 0x01
MSG_ANNOUNCE_NUMBER = 143
PROMPT_MSGS = {10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 26, 140, 141, 142, 143}
ASK_LUA = """--Probe Ask (TICKET-451): two effects that never run, then an Activate that asks in its cost, target and operation,
--runs Probe Ask Fusion's material procedure (which asks too) and asks again, shuffles itself into the deck and asks
--the opponent, then its controller.
local s,id,o=GetID()
function s.initial_effect(c)
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_UPDATE_ATTACK)
e0:SetRange(LOCATION_MZONE)
e0:SetValue(0)
c:RegisterEffect(e0)
local e1=e0:Clone()
e1:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(id*16+1)
e2:SetCategory(CATEGORY_DICE)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetCost(s.cost)
e2:SetTarget(s.target)
e2:SetOperation(s.activate)
c:RegisterEffect(e2)
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SelectYesNo(tp,id*16+2)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SelectOption(tp,id*16+3,id*16+4)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.SelectYesNo(tp,id*16+5)
local fc=Duel.GetFirstMatchingCard(Card.IsCode,tp,LOCATION_EXTRA,0,nil,id+1)
if fc then Duel.SelectFusionMaterial(tp,fc,Duel.GetFieldGroup(tp,LOCATION_HAND,0)) end
Duel.SelectYesNo(tp,id*16+8)
Duel.AnnounceLevel(tp,1,12)
Duel.AnnounceNumber(tp,1,2,3,4,5,6)
c:CancelToGrave()
Duel.SendtoDeck(c,nil,0,REASON_EFFECT)
Duel.SelectYesNo(1-tp,id*16+6)
Duel.SelectYesNo(tp,id*16+7)
end
"""
ASK_DESCRIPTION = PROBE_ASK * 16 + 1
ASK_INDEX = 2
ASK_FUSION_LUA = """--Probe Ask Fusion (TICKET-451): a Fusion Monster whose material procedure (its second effect) asks a yes/no, and
--whose third effect is an optional trigger from the Extra Deck in its controller's End Phase (the core asks "use it?").
local s,id,o=GetID()
function s.initial_effect(c)
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_UPDATE_ATTACK)
e0:SetRange(LOCATION_MZONE)
e0:SetValue(0)
c:RegisterEffect(e0)
local e1=Effect.CreateEffect(c)
e1:SetDescription(id*16+1)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCondition(s.fcon)
e1:SetOperation(s.fop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(id*16+3)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetRange(LOCATION_EXTRA)
e2:SetCountLimit(1)
e2:SetCondition(s.econ)
e2:SetOperation(s.eop)
c:RegisterEffect(e2)
end
function s.econ(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function s.eop(e,tp,eg,ep,ev,re,r,rp)
end
function s.fcon(e,g,gc,chkf)
return true
end
function s.fop(e,tp,eg,ep,ev,re,r,rp,gc,chkf)
Duel.SelectYesNo(tp,id*16+2)
Duel.AnnounceNumber(tp,7,8)
Duel.SetFusionMaterial(Group.CreateGroup())
end
"""
ASK_FUSION_INDEX = 1
ASK_TRIGGER_INDEX = 2
def prompt_context(d):
# 23-byte record + the prompt's MSG id: version, has effect, u32 code, controller, location, sequence, position,
# u64 description, u16 effect index, phase, chain link, announce kind, prompt
keys = ("version", "has", "code", "controller", "location", "sequence", "position", "description", "index", "phase", "chain", "announce", "prompt")
return dict(zip(keys, struct.unpack("<BBIBBBBQHBBBB", d)))
def prompts_with_context(c):
# every prompt this seat got, with the PROMPT_CONTEXT packet right before it (None when there was none)
out = []
for i, (p, d) in enumerate(c.log):
if p == 0x01 and d and d[0] in PROMPT_MSGS:
prev = c.log[i - 1] if i else (None, b"")
ctx = prompt_context(prev[1]) if prev[0] == STOC_PROMPT_CONTEXT and len(prev[1]) == 24 else None
out.append((d[0], d, ctx))
return out
def contexts_of(c):
return [d for p, d in c.log if p == STOC_PROMPT_CONTEXT]
def is_none_context(ctx, prompt):
return ctx == {"version": 1, "has": 0, "code": 0, "controller": 0, "location": 0, "sequence": 0, "position": 0,
"description": 0, "index": 0xFFFF, "phase": 0, "chain": 0, "announce": 0, "prompt": prompt}
def prompt_context_room(dll_path, port, label, mode, opponent_bit=True, fusion_first=False):
seats = 4 if mode == 2 else 2
print("== prompt context, %s (%d seats + a watcher that advertises 0x8000; the first player activates Probe Ask)" % (label, seats))
root = make_workspace()
here = os.getcwd()
os.chdir(root)
seen = {}
try:
db = sqlite3.connect(os.path.join(root, "cards.cdb"))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0)", (PROBE_ASK,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Ask', ''" + ", ''" * 16 + ")", (PROBE_ASK,))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 65, 2000, 2000, 6, 1, 16, 0)", (PROBE_ASK_FUSION,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Ask Fusion', ''" + ", ''" * 16 + ")", (PROBE_ASK_FUSION,))
db.commit()
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_ASK), "w", newline="\n") as f:
f.write(ASK_LUA)
with open(os.path.join(root, "script", "c%d.lua" % PROBE_ASK_FUSION), "w", newline="\n") as f:
f.write(ASK_FUSION_LUA)
write_special(root, [])
dll, thread = host_dll(dll_path, port, mode)
clients = []
def client(name):
c = Client("127.0.0.1", port, name)
c.log = list(c.join())
clients.append(c)
return c
seated = [client("pc-seat%d" % i) for i in range(seats)]
w = client("pc-watch")
everyone = seated + [w]
check([c.seat for c in everyone] == list(range(seats)) + [OBSERVER], "%s: %d seats and a watcher (%r)" % (label, seats, [c.seat for c in everyone]))
cap = server_capability(seated[0].log)
check(cap == (12, 0xF7FF), "%s: the server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
bitless = set()
for c in everyone:
if c is seated[-1] and not opponent_bit:
c.send(CTOS_CAPABILITY, capability_bytes(12, 0x77FF))
bitless.add(c)
else:
c.send(CTOS_CAPABILITY, capability_bytes(12, 0xF7FF))
drain_all(everyone)
check(not any(c.closed for c in everyone), "%s: every joiner stays, with or without 0x8000" % label)
for c in seated:
c.send(CTOS_UPDATE_DECK, deck_bytes([PROBE_ASK_FUSION] + [PROBE_ASK] * 40 if fusion_first else [PROBE_ASK] * 40 + [PROBE_ASK_FUSION]))
pump(everyone, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "activated": None, "bp": False, "done": False, "retries": 0}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
c.send(CTOS_RESPONSE, payload)
def play(limit):
deadline = time.time() + limit
while time.time() < deadline:
w.log += w.drain(quiet=0.02, limit=0.1)
for c in seated:
for pid, d in c.drain(quiet=0.02, limit=0.2):
c.log.append((pid, d))
if pid == STOC_SELECT_TP:
c.send(CTOS_TP_RESULT, bytes([1 if c.seat == 0 else 0])) # seat 0's side goes first
continue
if pid != 0x01 or not d:
continue
t = d[0]
if t == MSG_NEW_TURN and c is seated[0]:
state["turn"] += 1
elif t == MSG_RETRY:
state["retries"] += 1
elif t == MSG_SELECT_IDLECMD:
if state["turn"] == 1 and state["activated"] is None:
state["activated"] = c
answer(c, struct.pack("<i", 5)) # activate the first card: a Probe Ask
elif state["turn"] == 1:
answer(c, struct.pack("<i", 7)) # to the End Phase
elif mode != 2 and not state["bp"]:
state["bp"] = True
answer(c, struct.pack("<i", 6)) # to the Battle Phase
else:
state["done"] = True # Tag: turn 2 has no Battle Phase; stop on its idle prompt
elif t == MSG_SELECT_BATTLECMD:
state["done"] = True
elif t == MSG_SELECT_CHAIN:
answer(c, struct.pack("<i", -1))
elif t in (MSG_SELECT_PLACE, MSG_SELECT_DISFIELD):
answer(c, first_free_zone(d))
elif t in (MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO):
answer(c, struct.pack("<i", 1))
elif t in (MSG_SELECT_OPTION, MSG_ANNOUNCE_NUMBER):
answer(c, struct.pack("<i", 0))
if state["done"]:
return True
if any(c.closed for c in seated):
return False
return state["done"]
ok = play(limit=30)
check(ok, "%s: the duel reached the second player's %s prompt (turn %d)" % (label, "idle" if mode == 2 else "battle", state["turn"]))
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
a = state["activated"]
if not check(a is not None, "%s: a seat activated Probe Ask on turn 1" % label):
return seen
for c in seated:
got = prompts_with_context(c)
if c in bitless:
check(not contexts_of(c), "%s: %s advertised no 0x8000 and got no PROMPT_CONTEXT (%d)" % (label, c.name, len(contexts_of(c))))
continue
missing = [hex(t) for t, _, ctx in got if ctx is None or ctx["prompt"] != t]
check(not missing, "%s: %s: each of its %d prompts came right after a 24-byte PROMPT_CONTEXT naming that prompt (missing: %s)" % (label, c.name, len(got), missing))
check(len(contexts_of(c)) == len(got), "%s: %s: one PROMPT_CONTEXT per prompt, none on its own (%d contexts, %d prompts)" % (label, c.name, len(contexts_of(c)), len(got)))
check(not contexts_of(w), "%s: the watcher advertised 0x8000 and got no PROMPT_CONTEXT (%d)" % (label, len(contexts_of(w))))
mine = [(t, d, ctx) for t, d, ctx in prompts_with_context(a) if ctx]
player = next((d[1] for t, d, ctx in mine if t == MSG_SELECT_IDLECMD), None)
idle = [ctx for t, d, ctx in mine if t == MSG_SELECT_IDLECMD]
check(bool(idle) and all(is_none_context(ctx, MSG_SELECT_IDLECMD) for ctx in idle),
"%s: the idle prompt's context says no effect: every field 0, index 0xFFFF (%s)" % (label, idle[:1]))
chains = [ctx for c in seated for t, d, ctx in prompts_with_context(c) if t == MSG_SELECT_CHAIN and ctx]
check(all(is_none_context(ctx, MSG_SELECT_CHAIN) for ctx in chains), "%s: every chain prompt's context says no effect (%d)" % (label, len(chains)))
asks = [ctx for t, d, ctx in mine if ctx["has"] and ctx["prompt"] in (MSG_SELECT_YESNO, MSG_SELECT_OPTION)]
shape = [(ctx["prompt"], ctx["phase"], ctx["code"], ctx["chain"]) for ctx in asks]
Y, O, A, F = MSG_SELECT_YESNO, MSG_SELECT_OPTION, PROBE_ASK, PROBE_ASK_FUSION
check(shape == [(Y, 1, A, 1), (O, 2, A, 1), (Y, 3, A, 1), (Y, 3, F, 0), (Y, 3, A, 1), (Y, 3, A, 1)],
"%s: the activator's effect prompts are Probe Ask's cost yes/no (phase 1), target option (2), operation yes/no (3), then Probe Ask Fusion's material procedure inside that operation (3, chain link 0), then Probe Ask again: the outer context is back (chain link 1), then once more from the deck (%s)" % (label, shape))
if len(asks) == 6:
on_field = asks[:3] + [asks[4]]
check(all(ctx["code"] == PROBE_ASK and ctx["controller"] == player and ctx["location"] == LOCATION_SZONE and ctx["position"] & 0x5
and ctx["description"] == ASK_DESCRIPTION and ctx["index"] == ASK_INDEX and ctx["chain"] == 1 for ctx in on_field),
"%s: cost, target and both operation prompts name Probe Ask, its controller %r, face-up in the Spell & Trap Zone, description id*16+1, effect index 2, chain link 1 (%s)" % (label, player, on_field))
nested = asks[3]
check(nested["controller"] == player and nested["location"] == LOCATION_EXTRA and nested["index"] == ASK_FUSION_INDEX and nested["description"] == PROBE_ASK_FUSION * 16 + 1,
"%s: the nested procedure names Probe Ask Fusion in its controller's Extra Deck, effect index 1, its own description (%s)" % (label, nested))
last = asks[5]
check(last["location"] == LOCATION_DECK and last["index"] == ASK_INDEX and last["description"] == ASK_DESCRIPTION,
"%s: after it shuffled itself into the deck its controller still sees it: code, index 2, description, location Deck (%s)" % (label, last))
seen["index"] = [ctx["index"] for ctx in asks]
optional = [ctx for t, d, ctx in mine if t == MSG_SELECT_EFFECTYN]
check(len(optional) == 1 and optional[0]["has"] == 1 and optional[0]["code"] == PROBE_ASK_FUSION and optional[0]["controller"] == player
and optional[0]["location"] == LOCATION_EXTRA and optional[0]["index"] == ASK_TRIGGER_INDEX and optional[0]["description"] == PROBE_ASK_FUSION * 16 + 3
and optional[0]["phase"] == 4 and optional[0]["chain"] == 0,
"%s: the End Phase \"use this effect?\" for the optional trigger names Probe Ask Fusion in the Extra Deck, effect index 2, its description, phase 4 (ask), chain link 0 (%s)" % (label, optional))
if optional:
seen["index"] = seen.get("index", []) + [optional[0]["index"]]
announces = [(ctx["code"], ctx["phase"], ctx["announce"]) for t, d, ctx in mine if t == MSG_ANNOUNCE_NUMBER]
check(announces == [(PROBE_ASK_FUSION, 3, 0), (PROBE_ASK, 3, 1), (PROBE_ASK, 3, 2)],
"%s: announce kind: the Fusion's plain Duel.AnnounceNumber says 0, Probe Ask's Duel.AnnounceLevel 1 (level wins over dice), its dice effect's Duel.AnnounceNumber 2 (%s)" % (label, announces))
others = [ctx["announce"] for c in seated for t, d, ctx in prompts_with_context(c) if ctx and t != MSG_ANNOUNCE_NUMBER]
check(others and not any(others), "%s: every other prompt's context has announce kind 0 (%d prompts)" % (label, len(others)))
opponent = [c for c in seated if c is not a and any(t == MSG_SELECT_YESNO for t, _, _ in prompts_with_context(c))]
check(len(opponent) == 1, "%s: exactly one other seat answered the operation's yes/no (%s)" % (label, [c.name for c in opponent]))
if opponent and opponent[0] not in bitless:
hidden = [ctx for t, d, ctx in prompts_with_context(opponent[0]) if t == MSG_SELECT_YESNO and ctx]
check(len(hidden) == 1 and hidden[0]["has"] == 1 and hidden[0]["code"] == 0 and hidden[0]["index"] == 0xFFFF and hidden[0]["description"] == 0
and hidden[0]["location"] == LOCATION_DECK and hidden[0]["controller"] == player and hidden[0]["phase"] == 3 and hidden[0]["chain"] == 1 and hidden[0]["position"] & 0xA,
"%s: the opponent's yes/no names a hidden card: code 0, index 0xFFFF, description 0, but its controller, the Deck, face-down, phase 3, chain link 1 (%s)" % (label, hidden))
if mode == 2:
answering = {a} | set(opponent)
waiting = [c for c in seated if c not in answering]
check(len(waiting) == 2 and all(not contexts_of(c) for c in waiting),
"%s: the two waiting partners got no PROMPT_CONTEXT (%s)" % (label, [(c.name, len(contexts_of(c))) for c in waiting]))
else:
battle = [ctx for c in seated for t, d, ctx in prompts_with_context(c) if t == MSG_SELECT_BATTLECMD]
if opponent and opponent[0] not in bitless:
check(len(battle) == 1 and battle[0] is not None and is_none_context(battle[0], MSG_SELECT_BATTLECMD),
"%s: the battle prompt's context says no effect (%s)" % (label, battle))
marks = marks_of(seated)
for c in seated:
if (c.seat == 0) if mode != 2 else (c.seat in (0, 1)):
c.send(CTOS_SURRENDER)
ok = pump(seated, lambda: all(match_overs(since(c, marks)) for c in seated), limit=10)
check(ok, "%s: a surrender ended the match for everyone" % label)
for c in clients:
c.close()
stop_dll(dll, thread, label)
return seen
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def prompt_context_suite(dll_path, port):
print()
print("hosting prompt context rooms from %s" % dll_path)
first = prompt_context_room(dll_path, port, "single", 0)
second = prompt_context_room(dll_path, port + 1, "single, second duel, other deck order, opponent without 0x8000", 0, opponent_bit=False, fusion_first=True)
prompt_context_room(dll_path, port + 2, "tag", 2)
expected = [ASK_INDEX] * 3 + [ASK_FUSION_INDEX] + [ASK_INDEX] * 2 + [ASK_TRIGGER_INDEX]
check(first.get("index") == second.get("index") == expected,
"the effect indexes are the same in two duels with a different deck order and seed: %s and %s" % (first.get("index"), second.get("index")))
if __name__ == "__main__":
sys.exit(main())
+22 -21
View File
@@ -179,6 +179,13 @@ bool card::check_card_setcode(uint32_t code, uint32_t value) {
::read_card(code, &dat);
return dat.is_setcode(value);
}
bool card::check_code_setcode(uint32_t code, uint32_t value) const {
if (code == data.code)
return data.is_setcode(value);
if (data.rule_code && code == data.rule_code && data.is_setcode(value))
return true;
return check_card_setcode(code, value);
}
void card::attacker_map::addcard(card* pcard) {
auto fid = pcard ? pcard->fieldid_r : 0;
auto pr = emplace(fid, mapped_type(pcard, 0));
@@ -431,6 +438,9 @@ int32_t card::get_infos(byte* buf, uint32_t query_flag, int32_t use_cache) {
query_flag &= ~QUERY_LINK;
}
}
if(query_flag & QUERY_TAG_MEMBER) {
buffer_write<uint32_t>(p, tag_member);
}
byte* finalize = buf;
buffer_write<int32_t>(finalize, (int32_t)(p - buf));
buffer_write<uint32_t>(finalize, query_flag);
@@ -508,15 +518,8 @@ uint32_t card::get_another_code() {
}
int32_t card::is_set_card(uint32_t set_code) {
uint32_t code1 = get_code();
card_data dat1;
if (code1 == data.code) {
if (data.is_setcode(set_code))
return TRUE;
}
else {
if (check_card_setcode(code1, set_code))
return TRUE;
}
if (check_code_setcode(code1, set_code))
return TRUE;
uint32_t code2 = get_another_code();
if (code2 && check_card_setcode(code2, set_code))
return TRUE;
@@ -541,14 +544,8 @@ int32_t card::is_origin_set_card(uint32_t set_code) {
}
int32_t card::is_pre_set_card(uint32_t set_code) {
uint32_t code = previous.code;
if (code == data.code) {
if (data.is_setcode(set_code))
return TRUE;
}
else {
if (check_card_setcode(code, set_code))
return TRUE;
}
if (check_code_setcode(code, set_code))
return TRUE;
uint32_t code2 = previous.code2;
if (code2 && check_card_setcode(code2, set_code))
return TRUE;
@@ -595,7 +592,7 @@ int32_t card::is_link_set_card(uint32_t set_code) {
}
int32_t card::is_special_summon_set_card(uint32_t set_code) {
uint32_t code = spsummon.code;
if (check_card_setcode(code, set_code))
if (check_code_setcode(code, set_code))
return TRUE;
uint32_t code2 = spsummon.code2;
if (code2 && check_card_setcode(code2, set_code))
@@ -1955,10 +1952,14 @@ int32_t card::add_effect(effect* peffect) {
return 0;
peffect->id = pduel->game_field->infos.field_id++;
peffect->card_type = data.type;
if (get_status(STATUS_INITIALIZING))
if (get_status(STATUS_INITIALIZING)) {
peffect->flag[0] |= EFFECT_FLAG_INITIAL;
else if (get_status(STATUS_COPYING_EFFECT))
peffect->flag[0] |= EFFECT_FLAG_COPY;
peffect->ygol_script_index = (uint16_t)initial_effect.size(); // [YGOL] v1.7.0 prompt context: the script's registration order
} else {
peffect->ygol_script_index = 0xffff;
if (get_status(STATUS_COPYING_EFFECT))
peffect->flag[0] |= EFFECT_FLAG_COPY;
}
if (get_status(STATUS_COPYING_EFFECT)) {
peffect->copy_id = pduel->game_field->infos.copy_id;
peffect->reset_flag |= pduel->game_field->core.copy_reset;
+2
View File
@@ -164,6 +164,7 @@ public:
card_state spsummon;
query_cache q_cache;
uint8_t owner{ PLAYER_NONE };
uint8_t tag_member{ 0 }; // [YGOL] proposal 53: the partner who brought it, 0 from new_card, 1 from new_tag_card
uint8_t summon_player{ PLAYER_NONE };
uint32_t summon_info{};
uint32_t status{};
@@ -228,6 +229,7 @@ public:
~card() = default;
static bool card_operation_sort(card* c1, card* c2);
static bool check_card_setcode(uint32_t code, uint32_t value);
bool check_code_setcode(uint32_t code, uint32_t value) const;
bool is_extra_deck_monster() const { return !!(data.type & TYPES_EXTRA_DECK); }
int32_t get_infos(byte* buf, uint32_t query_flag, int32_t use_cache = TRUE);
+2
View File
@@ -271,6 +271,7 @@ enum LuaParamType : int32_t {
#define QUERY_LSCALE 0x200000
#define QUERY_RSCALE 0x400000
#define QUERY_LINK 0x800000
#define QUERY_TAG_MEMBER 0x1000000 // [YGOL] proposal 53. Never 0x100000: old flags (0xf81fff, 0x181fff, 0xFFFFFF) set it with no value
//Link markers
#define LINK_MARKER_BOTTOM_LEFT 0x001
@@ -452,6 +453,7 @@ enum LuaParamType : int32_t {
#define DUEL_SIMPLE_AI 0x40
#define DUEL_RETURN_DECK_TOP 0x80
#define DUEL_REVEAL_DECK_SEQ 0x100
#define DUEL_TAG_SHARED_EXTRA 0x200 // [YGOL] proposal 53: one Extra Deck per Tag team
//Activity
#define ACTIVITY_SUMMON 1
+1
View File
@@ -65,6 +65,7 @@ public:
int32_t operation{ 0 };
uint8_t cost_checked{ FALSE };
uint8_t is_granted{ 0 };
uint16_t ygol_script_index{ 0xffff }; // [YGOL] v1.7.0 prompt context: registration order in the card's initial_effect, 0xffff = not from it
effect_set required_handorset_effects;
LuaParamType object_type{ PARAM_TYPE_INT };
+14 -13
View File
@@ -649,8 +649,8 @@ uint8_t field::get_fzone_sequence(uint8_t playerid, uint8_t fseq) const {
bool field::is_fzone_zone(uint32_t zone) const {
return zone == (0x1U << 5) || (has_two_fields() && zone == (0x1U << 6));
}
// the slot a Field Spell lands in for playerid: the playing partner's, which it replaces; a card that changes control
// while the playing partner's slot is taken and the other is free takes the free one
// the slot a Field Spell lands in for playerid: the playing partner's, which it replaces; when the playing partner's
// slot is taken and the other is free, it takes the free one
uint8_t field::get_fzone_landing(card* pcard, uint8_t playerid) const {
if(!has_two_fields())
return 5;
@@ -659,8 +659,7 @@ uint8_t field::get_fzone_landing(card* pcard, uint8_t playerid) const {
return pcard->current.sequence;
uint8_t mine = get_fzone_sequence(playerid, 0);
uint8_t other = get_fzone_sequence(playerid, 1);
if(player[playerid].list_szone[mine] && !player[playerid].list_szone[other]
&& pcard->current.location == LOCATION_SZONE && pcard->current.controler != playerid)
if(player[playerid].list_szone[mine] && !player[playerid].list_szone[other])
return other;
return mine;
}
@@ -1243,15 +1242,17 @@ void field::tag_swap(uint8_t playerid) {
pcard->enable_field_effect(true);
}
//extra
for(auto& pcard : player[playerid].list_extra) {
pcard->enable_field_effect(false);
pcard->cancel_field_effect();
}
std::swap(player[playerid].list_extra, player[playerid].tag_list_extra);
std::swap(player[playerid].extra_p_count, player[playerid].tag_extra_p_count);
for(auto& pcard : player[playerid].list_extra) {
pcard->apply_field_effect();
pcard->enable_field_effect(true);
if(!(core.duel_options & DUEL_TAG_SHARED_EXTRA)) { // [YGOL] proposal 53: a shared Extra Deck stays live for both partners
for(auto& pcard : player[playerid].list_extra) {
pcard->enable_field_effect(false);
pcard->cancel_field_effect();
}
std::swap(player[playerid].list_extra, player[playerid].tag_list_extra);
std::swap(player[playerid].extra_p_count, player[playerid].tag_extra_p_count);
for(auto& pcard : player[playerid].list_extra) {
pcard->apply_field_effect();
pcard->enable_field_effect(true);
}
}
player[playerid].tag_partner ^= 1; // [YGOL] proposal 45: the other partner's Field slot is the live one now
pduel->write_buffer8(MSG_TAG_SWAP);
+18
View File
@@ -342,6 +342,16 @@ struct processor {
uint8_t selfdes_disabled{ FALSE };
uint8_t overdraw[2]{};
int32_t check_level{ 0 };
// [YGOL] v1.7.0 prompt context: the effect functions running now (cost / target / operation), innermost last
struct ygol_running_effect {
card* handler{ nullptr };
uint32_t description{ 0 };
uint16_t script_index{ 0xffff };
uint8_t phase{ 0 };
uint8_t chain_link{ 0 };
uint64_t category{ 0 };
};
std::vector<ygol_running_effect> ygol_running;
uint8_t shuffle_check_disabled{ FALSE };
uint8_t shuffle_hand_check[2]{};
uint8_t shuffle_deck_check[2]{};
@@ -864,4 +874,12 @@ public:
//#define PROCESSOR_SWAP_CONTROL_S 145
//#define PROCESSOR_MOVETOFIELD_S 161
// [YGOL] v1.7.0 prompt context (processor.cpp): phases 1 cost, 2 target, 3 operation, 4 the core asks whether to use the effect
constexpr uint8_t YGOL_PHASE_COST = 1;
constexpr uint8_t YGOL_PHASE_TARGET = 2;
constexpr uint8_t YGOL_PHASE_OPERATION = 3;
constexpr uint8_t YGOL_PHASE_ASK = 4;
void ygol_push_running(field* pfield, effect* peffect, uint8_t phase);
void ygol_pop_running(field* pfield);
#endif /* FIELD_H_ */
+57
View File
@@ -109,6 +109,18 @@ OCGCORE_API void start_duel(intptr_t pduel, uint32_t options) {
pd->game_field->core.shuffle_hand_check[1] = FALSE;
pd->game_field->core.shuffle_deck_check[0] = FALSE;
pd->game_field->core.shuffle_deck_check[1] = FALSE;
if((options & DUEL_TAG_MODE) && (options & DUEL_TAG_SHARED_EXTRA)) { // [YGOL] proposal 53: the team has one live Extra Deck
for(uint8_t p = 0; p < 2; ++p) {
auto& team = pd->game_field->player[p];
for(auto& pcard : team.tag_list_extra) {
team.list_extra.push_back(pcard);
pcard->apply_field_effect();
pcard->enable_field_effect(true);
}
team.tag_list_extra.clear();
pd->game_field->reset_sequence(p, LOCATION_EXTRA);
}
}
if(pd->game_field->player[0].start_count > 0)
pd->game_field->draw(0, REASON_RULE, PLAYER_NONE, 0, pd->game_field->player[0].start_count);
if(pd->game_field->player[1].start_count > 0)
@@ -198,6 +210,7 @@ OCGCORE_API void new_tag_card(intptr_t pduel, uint32_t code, uint8_t owner, uint
if(owner > 1 || !(location & (LOCATION_DECK | LOCATION_EXTRA)))
return;
card* pcard = ptduel->new_card(code);
pcard->tag_member = 1; // [YGOL] proposal 53
switch(location) {
case LOCATION_DECK:
ptduel->game_field->player[owner].tag_list_main.push_back(pcard);
@@ -469,6 +482,50 @@ OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8
buffer_write<uint32_t>(ptr, code);
return (int32_t)(ptr - out);
}
// [YGOL] v1.7.0 (prompt context) -- see ocgapi.h. Reads field::core.ygol_running, the cost / target / operation
// functions running now (processor.cpp); the innermost one is the effect that asks.
OCGCORE_API int32_t ygol_query_prompt_context(intptr_t pduel, uint8_t playerid, uint8_t* out) {
duel* pd = (duel*)pduel;
if(!pd || !out || !duel_set.count(pd) || !pd->game_field || !check_playerid(playerid))
return 0;
const auto& running = pd->game_field->core.ygol_running;
card* handler = running.empty() ? nullptr : running.back().handler;
if(handler && !pd->cards.count(handler))
handler = nullptr;
const auto& units = pd->game_field->core.units;
const bool announce = !units.empty() && units.front().type == PROCESSOR_ANNOUNCE_NUMBER;
const bool announce_level = announce && (units.front().arg1 >> 16) == 1; // Duel.AnnounceLevel passes playerid + 0x10000
byte* ptr = out;
buffer_write<uint8_t>(ptr, 1);
if(!handler) {
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint32_t>(ptr, 0);
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint64_t>(ptr, 0);
buffer_write<uint16_t>(ptr, 0xffff);
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint8_t>(ptr, 0);
buffer_write<uint8_t>(ptr, announce_level ? 1 : 0);
return (int32_t)(ptr - out);
}
const auto& top = running.back();
const bool visible = handler->current.controler == playerid || handler->is_position(POS_FACEUP);
buffer_write<uint8_t>(ptr, 1);
buffer_write<uint32_t>(ptr, visible ? handler->get_code() : 0);
buffer_write<uint8_t>(ptr, handler->current.controler);
buffer_write<uint8_t>(ptr, handler->current.location);
buffer_write<uint8_t>(ptr, handler->current.sequence);
buffer_write<uint8_t>(ptr, handler->current.position);
buffer_write<uint64_t>(ptr, visible ? top.description : 0);
buffer_write<uint16_t>(ptr, visible ? top.script_index : 0xffff);
buffer_write<uint8_t>(ptr, top.phase);
buffer_write<uint8_t>(ptr, top.chain_link);
buffer_write<uint8_t>(ptr, announce_level ? 1 : (announce && visible && (top.category & CATEGORY_DICE)) ? 2 : 0);
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;
+10
View File
@@ -87,6 +87,16 @@ OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_
// 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);
// [YGOL] v1.7.0 (prompt context, TICKET-451): which effect asks the prompt the engine is parked on, read only.
// playerid = the answering player. out (23 bytes): version (1), has_effect, uint32 code (the handler's current
// code), controller, location, sequence, position, uint64 description, uint16 effect_index (the order the
// card's script registered the effect in initial_effect; 0xffff unknown), phase (1 cost, 2 target, 3 operation, 4 the core asks whether to use the effect),
// chain link (0 none), announce kind (MSG_ANNOUNCE_NUMBER only: 1 Duel.AnnounceLevel, 2 the effect has
// CATEGORY_DICE and is visible, else 0). has_effect 0 = no effect runs: every other byte 0 but announce kind, effect_index 0xffff. A
// handler playerid does not control and that is not face-up writes code 0, effect_index 0xffff, description 0.
// Returns 23, 0 refused (bad pointer, bad player); a refusal writes nothing.
OCGCORE_API int32_t ygol_query_prompt_context(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);
+4 -4
View File
@@ -665,7 +665,7 @@ int32_t field::pay_lp_cost(uint32_t step, uint8_t playerid, uint32_t cost, uint3
if(core.select_options.size() == 1)
returns.ivalue[0] = 0;
else if(core.select_effects[0] == 0 && core.select_effects.size() == 2)
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_effects[1]->handler, playerid, 218);
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_effects[1], (group*)core.select_effects[1]->handler, playerid, 218); // [YGOL] v1.7.0 prompt context
else
add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, playerid, 0);
return FALSE;
@@ -729,7 +729,7 @@ int32_t field::remove_counter(uint16_t step, uint32_t reason, card* pcard, uint8
if(core.select_options.size() == 1)
returns.ivalue[0] = 0;
else if(core.select_effects[0] == nullptr && core.select_effects.size() == 2)
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_effects[1]->handler, rplayer, 220);
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_effects[1], (group*)core.select_effects[1]->handler, rplayer, 220); // [YGOL] v1.7.0 prompt context
else
add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, rplayer, 0);
return FALSE;
@@ -825,7 +825,7 @@ int32_t field::remove_overlay_card(uint16_t step, uint32_t reason, card* pcard,
if(core.select_options.size() == 1)
returns.ivalue[0] = 0;
else if(core.select_effects[0] == 0 && core.select_effects.size() == 2)
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_effects[1]->handler, rplayer, 219);
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_effects[1], (group*)core.select_effects[1]->handler, rplayer, 219); // [YGOL] v1.7.0 prompt context
else
add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, rplayer, 0);
return FALSE;
@@ -5629,7 +5629,7 @@ int32_t field::select_synchro_material(int16_t step, uint8_t playerid, card* pca
}
if(mfiltered && check_with_sum_limit_m(nsyn_filtered, lv, 0, min, max, 0xffff, mcount)) {
if(mremoved && check_with_sum_limit_m(nsyn_removed, lv, 0, min, max, 0xffff, mcount)) {
add_process(PROCESSOR_SELECT_YESNO, 0, 0, 0, playerid, peffect->description);
add_process(PROCESSOR_SELECT_YESNO, 0, peffect, 0, playerid, peffect->description); // [YGOL] v1.7.0 prompt context
core.units.begin()->step = 9;
return FALSE;
} else
+40 -3
View File
@@ -84,7 +84,11 @@ uint32_t field::process() {
}
}
case PROCESSOR_SELECT_EFFECTYN: {
if (it->step == 0 && it->peffect)
ygol_push_running(this, it->peffect, YGOL_PHASE_ASK); // [YGOL] v1.7.0 prompt context: the core asks whether to use this effect
if (select_effect_yes_no(it->step, it->arg1, it->arg2, (card*)it->ptarget)) {
if (it->peffect)
ygol_pop_running(this);
core.units.pop_front();
return pduel->buffer_size();
} else {
@@ -93,7 +97,11 @@ uint32_t field::process() {
}
}
case PROCESSOR_SELECT_YESNO: {
if (it->step == 0 && it->peffect)
ygol_push_running(this, it->peffect, YGOL_PHASE_ASK); // [YGOL] v1.7.0 prompt context
if (select_yes_no(it->step, it->arg1, it->arg2)) {
if (it->peffect)
ygol_pop_running(this);
core.units.pop_front();
return pduel->buffer_size();
} else {
@@ -727,6 +735,29 @@ uint32_t field::process() {
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// [YGOL] v1.7.0 prompt context: remember which effect function runs, so ygol_query_prompt_context can name it at a prompt
void ygol_push_running(field* pfield, effect* peffect, uint8_t phase) {
processor::ygol_running_effect running;
running.handler = peffect->get_handler();
if(!running.handler)
running.handler = peffect->owner;
running.description = peffect->description;
running.script_index = peffect->ygol_script_index;
running.phase = phase;
running.category = peffect->category;
auto& chain = pfield->core.current_chain;
for(auto it = chain.rbegin(); it != chain.rend(); ++it) {
if(it->triggering_effect == peffect) {
running.chain_link = it->chain_count;
break;
}
}
pfield->core.ygol_running.push_back(running);
}
void ygol_pop_running(field* pfield) {
if(!pfield->core.ygol_running.empty())
pfield->core.ygol_running.pop_back();
}
int32_t field::execute_cost(uint16_t step, effect * triggering_effect, uint8_t triggering_player) {
if(!triggering_effect->cost) {
core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event);
@@ -754,6 +785,7 @@ int32_t field::execute_cost(uint16_t step, effect * triggering_effect, uint8_t t
core.units.begin()->arg2 = core.shuffle_check_disabled;
core.shuffle_check_disabled = FALSE;
++core.check_level;
ygol_push_running(this, triggering_effect, YGOL_PHASE_COST);
}
core.reason_effect = triggering_effect;
core.reason_player = triggering_player;
@@ -765,6 +797,7 @@ int32_t field::execute_cost(uint16_t step, effect * triggering_effect, uint8_t t
core.reason_effect = 0;
core.reason_player = PLAYER_NONE;
--core.check_level;
ygol_pop_running(this);
if(core.check_level == 0) {
if(core.shuffle_hand_check[0])
shuffle(0, LOCATION_HAND);
@@ -806,6 +839,7 @@ int32_t field::execute_operation(uint16_t step, effect * triggering_effect, uint
core.units.begin()->arg2 = core.shuffle_check_disabled;
core.shuffle_check_disabled = FALSE;
++core.check_level;
ygol_push_running(this, triggering_effect, YGOL_PHASE_OPERATION);
}
core.reason_effect = triggering_effect;
core.reason_player = triggering_player;
@@ -817,6 +851,7 @@ int32_t field::execute_operation(uint16_t step, effect * triggering_effect, uint
core.reason_effect = 0;
core.reason_player = PLAYER_NONE;
--core.check_level;
ygol_pop_running(this);
if(core.check_level == 0) {
if(core.shuffle_hand_check[0])
shuffle(0, LOCATION_HAND);
@@ -863,6 +898,7 @@ int32_t field::execute_target(uint16_t step, effect * triggering_effect, uint8_t
core.units.begin()->arg2 = core.shuffle_check_disabled;
core.shuffle_check_disabled = FALSE;
++core.check_level;
ygol_push_running(this, triggering_effect, YGOL_PHASE_TARGET);
}
core.reason_effect = triggering_effect;
core.reason_player = triggering_player;
@@ -874,6 +910,7 @@ int32_t field::execute_target(uint16_t step, effect * triggering_effect, uint8_t
core.reason_effect = 0;
core.reason_player = PLAYER_NONE;
--core.check_level;
ygol_pop_running(this);
if(core.check_level == 0) {
if(core.shuffle_hand_check[0])
shuffle(0, LOCATION_HAND);
@@ -1153,7 +1190,7 @@ int32_t field::process_phase_event(int16_t step, int32_t phase) {
else
pduel->write_buffer32(26);
if(tf_count == 0 && to_count == 1 && fc_count == 0 && cn_count == 0) {
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_chains[0].triggering_effect->get_handler(), check_player, 0);
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_chains[0].triggering_effect, (group*)core.select_chains[0].triggering_effect->get_handler(), check_player, 0); // [YGOL] v1.7.0 prompt context: the asked effect rides in peffect
return FALSE;
} else {
add_process(PROCESSOR_SELECT_CHAIN, 0, 0, 0, check_player, core.spe_effect[check_player]);
@@ -1404,7 +1441,7 @@ int32_t field::process_point_event(int16_t step, int32_t skip_trigger, int32_t s
core.units.begin()->step = 5;
return FALSE;
} else if(core.select_chains.size() == 1 && !core.current_chain.size()) {
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_chains[0].triggering_effect->get_handler(), core.current_player, 221);
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_chains[0].triggering_effect, (group*)core.select_chains[0].triggering_effect->get_handler(), core.current_player, 221); // [YGOL] v1.7.0 prompt context
return FALSE;
} else {
add_process(PROCESSOR_SELECT_CHAIN, 0, 0, 0, core.current_player, 0x7f);
@@ -4225,7 +4262,7 @@ int32_t field::add_chain(uint16_t step) {
returns.ivalue[0] = TRUE;
return FALSE;
}
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)peffect->get_handler(), playerid, 94);
add_process(PROCESSOR_SELECT_EFFECTYN, 0, peffect, (group*)peffect->get_handler(), playerid, 94); // [YGOL] v1.7.0 prompt context
} else
returns.ivalue[0] = FALSE;
return FALSE;
+3 -2
View File
@@ -27,7 +27,8 @@
#endif
#ifndef YGOPRO_MAX_SIDE
#define YGOPRO_MAX_SIDE 15
// [YGOL] TICKET-465: no Side Deck limit, same silent truncation in LoadDeck as the Extra Deck above; SIDEC_MAX (250) is the real bound.
#define YGOPRO_MAX_SIDE 99
#endif
namespace irr {
@@ -129,7 +130,7 @@ extern DeckManager deckManager;
#endif
#ifndef DECKCOUNT_SIDE
#define DECKCOUNT_SIDE 15
#define DECKCOUNT_SIDE 99 // [YGOL] TICKET-465
#endif
#ifndef DECKCOUNT_EXTRA
+6
View File
@@ -800,6 +800,12 @@ int32_t SideBStartLp(int32_t fallback) { // YGOL life points per side
}
return fallback;
}
bool TagSharedExtra() { // YGOL tag shared extra
for(const auto& pair : setup_pairs)
if(pair == "ygol.tag.extra=shared")
return true;
return false;
}
size_t WriteSetupPairsBlock(unsigned char* dst) {
auto pdst = dst;
BufferIO::Write<uint16_t>(pdst, (uint16_t)setup_pairs.size());
+10 -1
View File
@@ -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 = 10; // 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; YGOL tag two fields: 9 -> 10
constexpr uint16_t FEATURE_PROTOCOL = 12; // 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; YGOL tag two fields: 9 -> 10; YGOL tag shared extra: 10 -> 11; YGOL prompt context: 11 -> 12
constexpr uint32_t FEATURE_APPEARANCE = 0x1;
constexpr uint32_t FEATURE_DIALOGUE = 0x2;
constexpr uint16_t FEATURE_SENDER_SERVER = 0xff;
@@ -470,6 +470,13 @@ constexpr int ATTACK_PREVIEW_ANSWER_SIZE = 24; // the ygol_preview_attack answer
constexpr uint32_t FEATURE_TAG_TWO_FIELDS = 0x1000;
// 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
constexpr uint32_t FEATURE_TAG_PARTNER_CARDS = 0x2000;
// YGOL tag shared extra (proposal 53): with the setup pair ygol.tag.extra=shared a Tag team has one Extra Deck (option DUEL_TAG_SHARED_EXTRA)
// and its Extra Deck refreshes carry QUERY_TAG_MEMBER; a Tag room refuses a joiner without the bit (ERRMSG_VERERROR)
constexpr uint32_t FEATURE_TAG_SHARED_EXTRA = 0x4000;
// YGOL prompt context (proposal 55): which card and which effect asks (ygol_query_prompt_context), sent to the answering seat right
// before every relayed prompt but rock-paper-scissors; never to observers, never in a replay; a room does not refuse a joiner without it
constexpr uint32_t FEATURE_PROMPT_CONTEXT = 0x8000;
constexpr int PROMPT_CONTEXT_RECORD_SIZE = 23; // the ygol_query_prompt_context answer; the message adds the prompt's MSG id after it
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];
@@ -479,6 +486,7 @@ void SetBootstrapSecret(const char* token);
bool WatchersAllowed();
bool SpectatorsSeeAll(); // YGOL spectators see all
int32_t SideBStartLp(int32_t fallback); // YGOL life points per side: ygol.side.b.lp, else fallback
bool TagSharedExtra(); // YGOL tag shared extra: ygol.tag.extra=shared
inline bool IsZeroId(const uint8_t* id) {
for(int i = 0; i < 16; ++i)
if(id[i])
@@ -664,6 +672,7 @@ inline bool IsFeatureMessage(unsigned char pktType) {
#define STOC_APPEARANCE 0x41 // uint16_t + CTOS_Appearance
#define STOC_DIALOGUE 0x42 // uint16_t + CTOS_Dialogue
#define STOC_SETUP_PAIRS 0x43 // uint16_t (0xff) + uint16_t count, then per pair uint16_t length + "key=value"
#define STOC_PROMPT_CONTEXT 0x44 // the 23-byte ygol_query_prompt_context record + uint8_t prompt MSG id, no sender stamp, to the answering seat only (YGOL prompt context)
#define STOC_SEAT_PLAN 0x50 // uint16_t (0xff) + STOC_SeatPlan (YGOL host seats)
// YGOL rules restart: uint16_t (0xff) + the struct
#define STOC_ROOM_RESTARTING 0x54 // STOC_RoomRestarting, to each participant with its own seat and token
+28 -1
View File
@@ -95,10 +95,21 @@ void SingleDuel::AttackPreview(DuelPlayer* dp, unsigned char* pdata, int len) {
return;
NetServer::AnswerAttackPreview(dp, pduel, (uint8_t)last_response, preview_attackers, pdata, len);
}
// YGOL prompt context: STOC_PROMPT_CONTEXT 0x44 = the ygol_query_prompt_context record + the prompt's MSG id, to the seat that answers
// the prompt (only when it advertised the bit), right before that prompt; never to observers or the recorders, never in a replay
static void SendPromptContext(intptr_t pduel, DuelPlayer* dp, int player, unsigned char msg) {
if(!pduel || !dp || !dp->has_capability || !(dp->capability.flags & FEATURE_PROMPT_CONTEXT))
return;
unsigned char buf[PROMPT_CONTEXT_RECORD_SIZE + 1];
if(ygol_query_prompt_context(pduel, (uint8_t)player, buf) != PROMPT_CONTEXT_RECORD_SIZE)
return;
buf[PROMPT_CONTEXT_RECORD_SIZE] = msg;
NetServer::SendBufferToPlayer(dp, STOC_PROMPT_CONTEXT, buf, sizeof buf);
}
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 | FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_PARTNER_CARDS; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag two fields + tag partner cards
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_TWO_FIELDS | FEATURE_TAG_PARTNER_CARDS | FEATURE_TAG_SHARED_EXTRA | FEATURE_PROMPT_CONTEXT; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag two fields + tag partner cards + tag shared extra + prompt context
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);
@@ -1620,6 +1631,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
RefreshHand(0);
RefreshHand(1);
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1644,6 +1656,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
RefreshHand(0);
RefreshHand(1);
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1651,6 +1664,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 12;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1658,6 +1672,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 4;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1666,6 +1681,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 4;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1685,6 +1701,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
}
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1713,6 +1730,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
}
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1721,6 +1739,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += 9 + count * 14;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1729,6 +1748,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1736,6 +1756,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1745,6 +1766,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 9;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1757,6 +1779,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 11;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1765,6 +1788,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 7;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -2545,6 +2569,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -2552,6 +2577,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -2561,6 +2587,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += 4 * count;
WaitforResponse(player);
SendPromptContext(pduel, players[player], player, engType);
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
+48 -6
View File
@@ -51,7 +51,8 @@ void TagDuel::Capability(DuelPlayer* dp, unsigned char* pdata, int len) {
std::memcpy(&dp->capability, pdata, sizeof dp->capability);
dp->has_capability = true;
// YGOL tag two fields: a client without the bit shows the second Field slot as a Pendulum Zone, so a Tag room refuses it as out of date
if(!(dp->capability.flags & FEATURE_TAG_TWO_FIELDS)) {
// YGOL tag shared extra: a client without the bit misreads a shared Extra Deck refresh, the same refusal
if((dp->capability.flags & (FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_SHARED_EXTRA)) != (FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_SHARED_EXTRA)) {
STOC_ErrorMsg scem;
scem.msg = ERRMSG_VERERROR;
scem.code = FEATURE_PROTOCOL;
@@ -102,10 +103,21 @@ void TagDuel::AttackPreview(DuelPlayer* dp, unsigned char* pdata, int len) {
return;
NetServer::AnswerAttackPreview(dp, pduel, (uint8_t)last_response, preview_attackers, pdata, len);
}
// YGOL prompt context: STOC_PROMPT_CONTEXT 0x44 = the ygol_query_prompt_context record + the prompt's MSG id, to the seat that answers
// the prompt (only when it advertised the bit), right before that prompt; never to observers or the recorders, never in a replay
static void SendPromptContext(intptr_t pduel, DuelPlayer* dp, int player, unsigned char msg) {
if(!pduel || !dp || !dp->has_capability || !(dp->capability.flags & FEATURE_PROMPT_CONTEXT))
return;
unsigned char buf[PROMPT_CONTEXT_RECORD_SIZE + 1];
if(ygol_query_prompt_context(pduel, (uint8_t)player, buf) != PROMPT_CONTEXT_RECORD_SIZE)
return;
buf[PROMPT_CONTEXT_RECORD_SIZE] = msg;
NetServer::SendBufferToPlayer(dp, STOC_PROMPT_CONTEXT, buf, sizeof buf);
}
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 | FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_PARTNER_CARDS; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag two fields + tag partner cards
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_TWO_FIELDS | FEATURE_TAG_PARTNER_CARDS | FEATURE_TAG_SHARED_EXTRA | FEATURE_PROMPT_CONTEXT; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag two fields + tag partner cards + tag shared extra + prompt context
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);
@@ -1306,6 +1318,9 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
if(host_info.no_shuffle_deck)
opt |= DUEL_PSEUDO_SHUFFLE;
opt |= DUEL_TAG_MODE;
const bool shared_extra = TagSharedExtra(); // YGOL tag shared extra
if(shared_extra)
opt |= DUEL_TAG_SHARED_EXTRA;
last_replay.WriteInt32(host_info.start_lp, false);
last_replay.WriteInt32(host_info.start_hand, false);
last_replay.WriteInt32(host_info.draw_count, false);
@@ -1322,7 +1337,10 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
last_replay.WriteInt32((*cit)->code, false);
}
};
uint16_t merged_extra[2]{}; // YGOL tag shared extra: what start_duel adds to each team's Extra Deck
auto load_tag = [&](const std::vector<const CardDataC*>& deck_container, uint8_t p, uint8_t location) {
if(shared_extra && location == LOCATION_EXTRA)
merged_extra[p] = (uint16_t)deck_container.size();
last_replay.WriteInt32(deck_container.size(), false);
for (auto cit = deck_container.rbegin(); cit != deck_container.rend(); ++cit) {
new_tag_card(pduel, (*cit)->code, p, location);
@@ -1368,9 +1386,9 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
BufferIO::Write<int32_t>(pbuf, player_lp[0]); // YGOL life points per side
BufferIO::Write<int32_t>(pbuf, player_lp[1]);
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_DECK));
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_EXTRA));
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_EXTRA) + merged_extra[0]);
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_DECK));
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_EXTRA));
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_EXTRA) + merged_extra[1]);
NetServer::SendBufferToPlayer(players[0], STOC_GAME_MSG, startbuf, 19);
NetServer::ReSendToPlayer(players[1]);
startbuf[1] = 1;
@@ -1390,9 +1408,15 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
phase = 1;
deck_reversed = false;
#endif
RefreshExtra(0);
RefreshExtra(1);
if(!shared_extra) {
RefreshExtra(0);
RefreshExtra(1);
}
start_duel(pduel, opt);
if(shared_extra) { // YGOL tag shared extra: start_duel merged the lists
RefreshExtra(0);
RefreshExtra(1);
}
tag_cards_known[0] = tag_cards_known[1] = false;
SendTagPartnerCards(0); // YGOL tag partner cards: the waiting members' opening hands
SendTagPartnerCards(1);
@@ -1596,6 +1620,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
RefreshHand(0);
RefreshHand(1);
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1620,6 +1645,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
RefreshHand(0);
RefreshHand(1);
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1627,6 +1653,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 12;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1634,6 +1661,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 4;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1642,6 +1670,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 4;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1661,6 +1690,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
}
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1689,6 +1719,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
}
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1697,6 +1728,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += 9 + count * 14;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1705,6 +1737,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1712,6 +1745,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1721,6 +1755,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 9;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1733,6 +1768,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 11;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -1741,6 +1777,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += count * 7;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -2654,6 +2691,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -2661,6 +2699,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
player = BufferIO::Read<uint8_t>(pbuf);
pbuf += 5;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -2670,6 +2709,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
count = BufferIO::Read<uint8_t>(pbuf);
pbuf += 4 * count;
WaitforResponse(player);
SendPromptContext(pduel, cur_player[player], player, engType);
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
return 1;
}
@@ -3374,6 +3414,8 @@ void TagDuel::RefreshExtra(int player, int flag, int use_cache, DuelPlayer* dp)
void TagDuel::RefreshExtra(int player, int flag, int use_cache)
#endif //YGOPRO_SERVER_MODE
{
if(TagSharedExtra()) // YGOL tag shared extra
flag |= QUERY_TAG_MEMBER;
std::array<unsigned char, SIZE_QUERY_BUFFER> query_buffer;
auto qbuf = query_buffer.data();
auto len = WriteUpdateData(player, LOCATION_EXTRA, flag, qbuf, use_cache);