From f2fcb28f652aa03328c30890626384e91f62840a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 18:08:54 +0200 Subject: [PATCH] Fork the Classic season core into src/modern and add the world layout (M1) - src/modern/game: the season modules as bmh::modern, working on ModernState (a GameState). Data types stay shared with Classic; Modern code calls its season functions qualified (modern::...), so a missing Modern function is a compile error instead of a silent call into Classic. - src/modern/app/modern_session: the session on the Modern core. It still uses the Classic UI projections until the Modern projections exist. - SeasonHooks: the shared match core reaches player statistics and the table prediction of the season core that owns the game (Classic: unchanged). - WorldLayout: team ranges, squad slots and pools of the running world. Shared code and the Modern fork read them; Classic keeps the original numbers. - Transfer list views moved to game/transfer_offer_view.hpp (shared). - tools/modern/check_fork_calls.sh, modern_season_sim and world_layout_tests. Verified: Classic tests and replay regression unchanged; season_sim and modern_season_sim produce identical output with Classic data. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 32 + docs/new_engine/AGENTS.md | 12 + docs/new_engine/README.md | 4 +- src/game/lineup.cpp | 11 +- src/game/match.cpp | 3 +- src/game/match_engine.cpp | 27 +- src/game/rating.cpp | 12 +- src/game/reality_setup.cpp | 3 +- src/game/schedule.cpp | 3 +- src/game/sportschau_awards.cpp | 5 +- src/game/state.cpp | 16 +- src/game/state.hpp | 13 + src/game/transfer_offer_view.hpp | 68 + src/game/weekly.hpp | 58 +- src/game/world_layout.cpp | 57 + src/game/world_layout.hpp | 59 + src/modern/app/modern_session.cpp | 8628 ++++++++++++++++++++++++ src/modern/app/modern_session.hpp | 1090 +++ src/modern/game/balance_plan.cpp | 362 + src/modern/game/balance_plan.hpp | 65 + src/modern/game/bank_credit.cpp | 258 + src/modern/game/bank_credit.hpp | 39 + src/modern/game/career.cpp | 684 ++ src/modern/game/career.hpp | 149 + src/modern/game/club_info.cpp | 90 + src/modern/game/club_info.hpp | 14 + src/modern/game/club_player_detail.cpp | 221 + src/modern/game/club_player_detail.hpp | 49 + src/modern/game/cup.cpp | 783 +++ src/modern/game/cup.hpp | 92 + src/modern/game/desk.cpp | 130 + src/modern/game/desk.hpp | 29 + src/modern/game/desk_actions.cpp | 2250 ++++++ src/modern/game/desk_actions.hpp | 354 + src/modern/game/driver.cpp | 280 + src/modern/game/driver.hpp | 79 + src/modern/game/environment.cpp | 114 + src/modern/game/environment.hpp | 24 + src/modern/game/highscore.cpp | 240 + src/modern/game/highscore.hpp | 37 + src/modern/game/league_pairings.cpp | 548 ++ src/modern/game/league_pairings.hpp | 36 + src/modern/game/matchday.cpp | 794 +++ src/modern/game/matchday.hpp | 106 + src/modern/game/matchday_setup.cpp | 1226 ++++ src/modern/game/matchday_setup.hpp | 149 + src/modern/game/modern_state.cpp | 27 + src/modern/game/modern_state.hpp | 41 + src/modern/game/month.cpp | 990 +++ src/modern/game/month.hpp | 80 + src/modern/game/national.cpp | 234 + src/modern/game/national.hpp | 65 + src/modern/game/other_games.cpp | 396 ++ src/modern/game/other_games.hpp | 41 + src/modern/game/poach.cpp | 176 + src/modern/game/poach.hpp | 46 + src/modern/game/prediction.cpp | 205 + src/modern/game/prediction.hpp | 55 + src/modern/game/reschedule.cpp | 244 + src/modern/game/reschedule.hpp | 62 + src/modern/game/save.cpp | 200 + src/modern/game/save.hpp | 39 + src/modern/game/season.cpp | 1687 +++++ src/modern/game/season.hpp | 146 + src/modern/game/source_tip.cpp | 39 + src/modern/game/source_tip.hpp | 20 + src/modern/game/stadium_blocks.cpp | 168 + src/modern/game/stadium_blocks.hpp | 46 + src/modern/game/table_forecast.cpp | 73 + src/modern/game/table_forecast.hpp | 27 + src/modern/game/turn.cpp | 223 + src/modern/game/turn.hpp | 103 + src/modern/game/turn_driver.cpp | 594 ++ src/modern/game/turn_driver.hpp | 48 + src/modern/game/week.cpp | 395 ++ src/modern/game/week.hpp | 78 + src/modern/game/weekly.cpp | 2987 ++++++++ src/modern/game/weekly.hpp | 118 + tests/modern_season_sim.cpp | 358 + tests/world_layout_tests.cpp | 88 + tools/modern/check_fork_calls.sh | 40 + 81 files changed, 29351 insertions(+), 91 deletions(-) create mode 100644 src/game/transfer_offer_view.hpp create mode 100644 src/game/world_layout.cpp create mode 100644 src/game/world_layout.hpp create mode 100644 src/modern/app/modern_session.cpp create mode 100644 src/modern/app/modern_session.hpp create mode 100644 src/modern/game/balance_plan.cpp create mode 100644 src/modern/game/balance_plan.hpp create mode 100644 src/modern/game/bank_credit.cpp create mode 100644 src/modern/game/bank_credit.hpp create mode 100644 src/modern/game/career.cpp create mode 100644 src/modern/game/career.hpp create mode 100644 src/modern/game/club_info.cpp create mode 100644 src/modern/game/club_info.hpp create mode 100644 src/modern/game/club_player_detail.cpp create mode 100644 src/modern/game/club_player_detail.hpp create mode 100644 src/modern/game/cup.cpp create mode 100644 src/modern/game/cup.hpp create mode 100644 src/modern/game/desk.cpp create mode 100644 src/modern/game/desk.hpp create mode 100644 src/modern/game/desk_actions.cpp create mode 100644 src/modern/game/desk_actions.hpp create mode 100644 src/modern/game/driver.cpp create mode 100644 src/modern/game/driver.hpp create mode 100644 src/modern/game/environment.cpp create mode 100644 src/modern/game/environment.hpp create mode 100644 src/modern/game/highscore.cpp create mode 100644 src/modern/game/highscore.hpp create mode 100644 src/modern/game/league_pairings.cpp create mode 100644 src/modern/game/league_pairings.hpp create mode 100644 src/modern/game/matchday.cpp create mode 100644 src/modern/game/matchday.hpp create mode 100644 src/modern/game/matchday_setup.cpp create mode 100644 src/modern/game/matchday_setup.hpp create mode 100644 src/modern/game/modern_state.cpp create mode 100644 src/modern/game/modern_state.hpp create mode 100644 src/modern/game/month.cpp create mode 100644 src/modern/game/month.hpp create mode 100644 src/modern/game/national.cpp create mode 100644 src/modern/game/national.hpp create mode 100644 src/modern/game/other_games.cpp create mode 100644 src/modern/game/other_games.hpp create mode 100644 src/modern/game/poach.cpp create mode 100644 src/modern/game/poach.hpp create mode 100644 src/modern/game/prediction.cpp create mode 100644 src/modern/game/prediction.hpp create mode 100644 src/modern/game/reschedule.cpp create mode 100644 src/modern/game/reschedule.hpp create mode 100644 src/modern/game/save.cpp create mode 100644 src/modern/game/save.hpp create mode 100644 src/modern/game/season.cpp create mode 100644 src/modern/game/season.hpp create mode 100644 src/modern/game/source_tip.cpp create mode 100644 src/modern/game/source_tip.hpp create mode 100644 src/modern/game/stadium_blocks.cpp create mode 100644 src/modern/game/stadium_blocks.hpp create mode 100644 src/modern/game/table_forecast.cpp create mode 100644 src/modern/game/table_forecast.hpp create mode 100644 src/modern/game/turn.cpp create mode 100644 src/modern/game/turn.hpp create mode 100644 src/modern/game/turn_driver.cpp create mode 100644 src/modern/game/turn_driver.hpp create mode 100644 src/modern/game/week.cpp create mode 100644 src/modern/game/week.hpp create mode 100644 src/modern/game/weekly.cpp create mode 100644 src/modern/game/weekly.hpp create mode 100644 tests/modern_season_sim.cpp create mode 100644 tests/world_layout_tests.cpp create mode 100644 tools/modern/check_fork_calls.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index f3bac51..4ff64f9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -219,6 +219,7 @@ add_library(bmhcore STATIC src/game/source_tip.cpp src/game/table_forecast.cpp src/game/state.cpp + src/game/world_layout.cpp src/game/rating.cpp src/game/match.cpp src/game/match_engine.cpp @@ -273,6 +274,17 @@ else() target_compile_options(bmhcore PRIVATE -Wall -Wextra) endif() +# Modern season core: a fork of the Classic season sources (docs/new_engine) that shares +# formats, GameState and the match core with Classic through bmhcore. +file(GLOB BMH_SEASON_MODERN_SOURCES CONFIGURE_DEPENDS src/modern/game/*.cpp) +add_library(bmh_season_modern STATIC ${BMH_SEASON_MODERN_SOURCES}) +target_link_libraries(bmh_season_modern PUBLIC bmhcore) +if(MSVC) + target_compile_options(bmh_season_modern PRIVATE /W4 /utf-8 /bigobj) +else() + target_compile_options(bmh_season_modern PRIVATE -Wall -Wextra) +endif() + add_executable(openbmh_inspect src/main.cpp) target_link_libraries(openbmh_inspect PRIVATE bmhcore ${BMH_SDL_TARGET}) if(MSVC) @@ -326,6 +338,16 @@ endif() add_subdirectory(src/ui) add_subdirectory(src/import) + +# Modern session: fork of the Classic CareerSession on the Modern season core. It still +# uses the Classic UI projections until the Modern projections exist (docs/new_engine). +add_library(bmh_modern_session STATIC src/modern/app/modern_session.cpp) +target_link_libraries(bmh_modern_session PUBLIC bmh_season_modern bmhui) +if(MSVC) + target_compile_options(bmh_modern_session PRIVATE /W4 /utf-8 /bigobj) +else() + target_compile_options(bmh_modern_session PRIVATE -Wall -Wextra) +endif() option(OPENBMH_BUILD_EDITOR "Build the standalone OBW editor" OFF) if(OPENBMH_BUILD_EDITOR) add_subdirectory(src/editor) @@ -616,6 +638,12 @@ target_link_libraries(season_sim PRIVATE bmhui) if(MSVC) target_compile_options(season_sim PRIVATE /utf-8) endif() +# The Modern fork of season_sim; with Classic data its output must equal season_sim's. +add_executable(modern_season_sim tests/modern_season_sim.cpp) +target_link_libraries(modern_season_sim PRIVATE bmh_modern_session) +if(MSVC) + target_compile_options(modern_season_sim PRIVATE /utf-8) +endif() # Headless terminal/protocol client; owns no game logic and has no SDL dependency. add_executable(openbmh_cli @@ -1111,6 +1139,10 @@ if(MSVC) endif() add_test(NAME quit_confirmation_unit_tests COMMAND quit_confirmation_unit_tests) +add_executable(world_layout_tests tests/world_layout_tests.cpp) +target_link_libraries(world_layout_tests PRIVATE bmhcore) +add_test(NAME world_layout_tests COMMAND world_layout_tests) + add_executable(fixture_table_tests tests/fixture_table_tests.cpp) target_link_libraries(fixture_table_tests PRIVATE bmhcore) add_test(NAME fixture_table_unit_tests COMMAND fixture_table_tests) diff --git a/docs/new_engine/AGENTS.md b/docs/new_engine/AGENTS.md index eba0e4c..6ce6d3d 100644 --- a/docs/new_engine/AGENTS.md +++ b/docs/new_engine/AGENTS.md @@ -10,3 +10,15 @@ - Mit jeder Phase den Status in [README](README.md) und die Details in [Phasen](phasen.md) nachführen. - Private Datensätze, echte Namen, Wappen und Fotos gehören nicht in dieses Repository; Tests nutzen synthetische Welten. - Diese Notizen sind deutsch; Code, Kommentare und Commits englisch. + +## Arbeiten im Abzweig (seit M1) + +- Der Abzweig ist mit Skripten aus Classic erzeugt worden; **seitdem wird `src/modern/` von Hand gepflegt**. Classic-Änderungen werden nicht automatisch übernommen. +- Modern-Saisonfunktionen nehmen `ModernState` (`src/modern/game/modern_state.hpp`), eine Ableitung von `GameState`. Modern-Code ruft sie **qualifiziert** auf: `modern::name(...)`. Ein fehlender Modern-Aufruf wird so zum Übersetzungsfehler statt zum stillen Aufruf der Classic-Version. +- Datentypen sind zwischen Classic und Modern gemeinsam: Ein Modern-Header bindet den Classic-Header für die Typen ein und deklariert nur die Modern-Funktionen. Ein eigener Modern-Typ entsteht erst, wenn Modern ihn ändern muss. +- Gemeinsame Callback-Typen übergeben `GameState&`; in Modern wird dort ausdrücklich nach `ModernState&` gewandelt. +- Feste Classic-Größen (138, 168, 0x165, Pool-Slots) kommen in Modern aus dem `WorldLayout` (`league_clubs()`, `first_foreign_cup()`, `no_team()`, `transfer_list_slot()` …). Offsets im Speicherabbild (etwa `rec + 0xa8`) bleiben. +- Prüfungen nach jeder Änderung: + - `tools/modern/check_fork_calls.sh build` und `LIBRARY=bmh_modern_session tools/modern/check_fork_calls.sh build`: Modern ruft keine Classic-Saisonfunktion. + - `season_sim` und `modern_season_sim` mit Classic-Daten und gleichen Argumenten liefern dieselbe Ausgabe, solange Modern keine Regel bewusst ändert. + - Classic-Tests und Classic-Regression unverändert. diff --git a/docs/new_engine/README.md b/docs/new_engine/README.md index 6fd98b8..b98a26f 100644 --- a/docs/new_engine/README.md +++ b/docs/new_engine/README.md @@ -51,8 +51,8 @@ Für 0.3 gilt außerdem: | Phase | Inhalt | Status | |---|---|---| -| M0 | Classic-Referenz festhalten, Datensatz lokal bereitstellen | offen | -| M1 | `WorldLayout`, Abzweig `src/modern/`, vereinsbezogene Blöcke typisiert | offen | +| M0 | Classic-Referenz festhalten, Datensatz lokal bereitstellen | erledigt (Classic-Regressionen des öffentlichen Codes: Issue #14) | +| M1 | `WorldLayout`, Abzweig `src/modern/` | Abzweig und Layout erledigt; vereinsbezogene Speicherblöcke folgen mit M3 | | M2 | Spielpläne je Liga (Round-Robin), Kalender mit 38 Spieltagen | offen | | M3 | Modern-Weltlader, Namen (Vor-/Nachname, UTF-8), Asset-Schlüssel | offen | | M4 | Trainingslager: 18 Lager, drei Regionen, 6-Sterne-Wirkung | offen | diff --git a/src/game/lineup.cpp b/src/game/lineup.cpp index 1dea703..6e949a4 100644 --- a/src/game/lineup.cpp +++ b/src/game/lineup.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "game/world_layout.hpp" #include "game/lineup.hpp" #include @@ -33,7 +34,7 @@ uint8_t formation_byte(const GameState& g, size_t index) { } bool pitch_context_valid(const GameState& g, int manager, int team) { - if (manager < 0 || manager > 3 || team < 0 || team >= 138 || g.lineups_frozen || + if (manager < 0 || manager > 3 || team < 0 || team >= world_layout().league_teams || g.lineups_frozen || !g.memory.has(::bmh::layout::ActiveManager) || !g.memory.has(::bmh::layout::GameMode) || g.memory.u8(::bmh::layout::ActiveManager) != manager || g.memory.u8(::bmh::layout::GameMode) < 1 || g.memory.u8(::bmh::layout::GameMode) > 3 || size_t(manager) >= g.manager_teams.size() || g.manager_teams[size_t(manager)] != team || @@ -318,7 +319,7 @@ bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_clu } static void auto_lineup_impl(GameState& g, int team, int mode, int manager) { - if (team >= 138 && team != kNoTeam) return; // teams without squads + if (team >= world_layout().league_teams && team != no_team()) return; // teams without squads if (g.lineups_frozen) return; // LineupRuntimeField (the season change) const bool improve_from_reserves = (mode & 0x80) != 0; mode &= 0x7F; @@ -594,12 +595,12 @@ void auto_lineup(GameState& g, int team, int mode) { void auto_lineup_parked_club_source(GameState& g, int team, int mode) { constexpr size_t record = 4*0xb0c+0x290; - if (team<0 || team>=138 || g.manager_teams.size()!=1 || g.manager_teams[0]!=kNoTeam || + if (team<0 || team>=world_layout().league_teams || g.manager_teams.size()!=1 || g.manager_teams[0]!=no_team() || !g.memory.has(::bmh::layout::CoachActive) || g.memory.u8(::bmh::layout::CoachActive)==0 || !g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 || !g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || record+2>g.manager_records.size() || - (int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=kNoTeam || + (int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=no_team() || (int(g.manager_records[record]) | int(g.manager_records[record+1])<<8)!=team || g.tactics.size()<5*0x840) throw std::invalid_argument("auto_lineup: invalid FindManagerForClub parked club context"); @@ -630,7 +631,7 @@ void quicksort_by_key(int16_t* items, uint32_t* keys, int count, bool ascending) } bool substitute(GameState& g, int team, int off, int mode, WatcomRandom& rand) { - if (!(team < 138 || team == kNoTeam)) return false; + if (!(team < world_layout().league_teams || team == no_team())) return false; const int manager = g.manager_of(team); int used = g.team_flags.at(team) >> 5 & 7; // substitutions so far if (mode == 10) { diff --git a/src/game/match.cpp b/src/game/match.cpp index 565449f..946b915 100644 --- a/src/game/match.cpp +++ b/src/game/match.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "game/match.hpp" +#include "game/world_layout.hpp" #include #include @@ -73,7 +74,7 @@ int region_temperature(int region) { return region >= 0 && region < 48 ? kRegion int month_temperature(int month) { return kMonthTemperature[month >= 0 && month <= 12 ? month : 0]; } int team_region(int team) { - if (team == kNoTeam) return 0; + if (team == no_team()) return 0; int t = team; for (int league = 0; league < kLeagueCount; league++) { t -= kLeagueSizes[league]; diff --git a/src/game/match_engine.cpp b/src/game/match_engine.cpp index 806c557..8e01eaa 100644 --- a/src/game/match_engine.cpp +++ b/src/game/match_engine.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "game/world_layout.hpp" #include "game/match_engine.hpp" #include @@ -19,6 +20,14 @@ namespace bmh { namespace { +// PlayerStatistic of the season core that owns the game (SeasonHooks; Classic by default). +void player_statistic_hook(GameState& g, int type, int player, int manager, int slot, int kind, int minute) { + if (g.season_hooks && g.season_hooks->player_statistic) + g.season_hooks->player_statistic(g, type, player, manager, slot, kind, minute); + else + player_statistic(g, type, player, manager, slot, kind, minute); +} + // Goal threshold by chance quality index 5..24 (table at layout field). constexpr uint8_t kChanceTable[25] = {11, 12, 13, 14, 16, 18, 20, 21, 22, 22, 23, 25, 26, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33}; @@ -78,7 +87,7 @@ MinuteReport MatchEngine::minute(int minute, int last_minute, int stoppage) { // Human teams use the places on their tactics board, also for the player's value. int MatchEngine::pick_player(int team, int mode, int exclude, MinuteReport& report, int preset) { mode &= 0x7F; // 0x80 = reuse the squad of the previous call, same team here - if (team >= 138 && team != kNoTeam) return 0xFFF; // clubs without squad: nobody, no draws + if (team >= world_layout().league_teams && team != no_team()) return 0xFFF; // clubs without squad: nobody, no draws SquadRange range = squad_range(team); if (range.count == 0) return 0xFFF; RatingContext ctx{state.chance_rain, state.chance_temperature}; @@ -523,8 +532,8 @@ ForcedMatchEvent MatchEngine::event_impl(MatchGroup& g, int m, int s, int minute // national team (0x165, squad nominated on the national team days) only while manager // slot 0 holds it (CupDraw_FormatError_RuntimeField2 == 0x165: a Bundestrainer's match). if (!(team < 90 || rand.range(0, 1) == 0)) return result; - if (!(team < 138 || team == kNoTeam)) return result; - if (team == kNoTeam && (state.manager_teams.empty() || state.manager_teams[0] != kNoTeam)) return result; + if (!(team < world_layout().league_teams || team == no_team())) return result; + if (team == no_team() && (state.manager_teams.empty() || state.manager_teams[0] != no_team())) return result; const int manager = state.manager_of(team); // FindManagerForClub, local_6c const bool human = manager >= 0; SquadRange range = squad_range(team); // SquadRange4 @@ -944,7 +953,7 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i } // Goalkeeper of the opponent: the player in squad slot 0 if the formation puts it in goal. - if (!reality_played && (opp_team < 168 || opp_team == kNoTeam)) { + if (!reality_played && (opp_team < world_layout().first_foreign_cup() || opp_team == no_team())) { int x = 0, y = 0; state.formation_position(opp_team, 0, x, y); if (x == 0 && y == 4) keeper = state.squad_slots.at(squad_range(opp_team).first) & 0x0FFF; @@ -979,7 +988,7 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i deflected = game.range(0, 5) == 0; } if (kind == 0) { - if (team >= 168 && team != kNoTeam) { + if (team >= world_layout().first_foreign_cup() && team != no_team()) { // clubs without squad: the attack rating (TeamRating, profile 3), drawn RatingContext drawn; drawn.rand = &rand; @@ -989,7 +998,7 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i } } if (keeper == 0xFFF) { - if (opp_team >= 168 && opp_team != kNoTeam) { + if (opp_team >= world_layout().first_foreign_cup() && opp_team != no_team()) { // clubs without squad: the goalkeeping rating (profile 0), drawn RatingContext drawn; drawn.rand = &rand; @@ -1111,9 +1120,9 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i } // PlayerStatistic: goal for the shooter, assist (open play and set pieces of kind 3). const int manager = state.manager_of(team); // MatchEngineRuntimeField16 - if (shooter != 0xFFF) player_statistic(state, g.desc.at(0), shooter, manager, last_shooter_slot, 1, minute); + if (shooter != 0xFFF) player_statistic_hook(state, g.desc.at(0), shooter, manager, last_shooter_slot, 1, minute); if ((kind == 0 || kind == 3) && assistant != 0xFFF) - player_statistic(state, g.desc.at(0), assistant, manager, last_assist_slot, 2, 0x5a); + player_statistic_hook(state, g.desc.at(0), assistant, manager, last_assist_slot, 2, 0x5a); } else if (live == 2 && button(::bmh::layout::MatchEngine_Side_ExecutableField5)) { live = 0; // ticker mode shows misses only if this button is off } @@ -1196,7 +1205,7 @@ void MatchEngine::penalty_shootout(MatchGroup& g, int m, MinuteReport& report) { const int side = order[k]; const int team = pair[side]; int player = 0xFFF; - if (team < 138 || team == kNoTeam) { + if (team < world_layout().league_teams || team == no_team()) { // a player who has not taken a penalty yet (after 100 tries the list restarts) int tries = 0; bool fresh; diff --git a/src/game/rating.cpp b/src/game/rating.cpp index 9e554d0..bb8a3d9 100644 --- a/src/game/rating.cpp +++ b/src/game/rating.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "game/rating.hpp" +#include "game/world_layout.hpp" #include #include @@ -121,7 +122,7 @@ int human_correction(GameState& g, RatingContext& ctx, int manager, int rank, in } // namespace int team_rating(GameState& g, int team, const RatingProfile& profile, RatingContext& ctx, int* keeper) { - if (team >= 168 && team != kNoTeam) { + if (team >= world_layout().first_foreign_cup() && team != no_team()) { // Clubs without squad: per group a random value around the level of the club // (ForeignClubStrength bits 5-7 -> RatingRuntimeField2), +2 if the group's strength bit is set // (bit 3, 3, 2, 1 for goal, defence, midfield, attack: RatingRuntimeField3) and a style @@ -130,7 +131,7 @@ int team_rating(GameState& g, int team, const RatingProfile& profile, RatingCont static const uint8_t kStrongBit[4] = {3, 3, 2, 1}; static const int8_t kStyle[8] = {0, 6, 0, -6, 0, -6, 0, 6}; if (!ctx.rand) throw std::invalid_argument("team_rating: a team without squad needs the Watcom generator"); - const uint8_t s = g.foreign_strength.at(size_t(team - 168)); + const uint8_t s = g.foreign_strength.at(size_t(team - world_layout().first_foreign_cup())); int16_t total = 0; for (int i = 0; i < 4; i++) { const int level = kLevel[s >> 5]; @@ -143,7 +144,7 @@ int team_rating(GameState& g, int team, const RatingProfile& profile, RatingCont // Human managers: the predicted final rank (Void5 in mode 1 before the tenth // round of the manager's league, mode 2 after it) for the expected bonus. Mode 1 may // post the season goal messages. - const int manager = team == kNoTeam ? -1 : g.manager_of(team); // local_5a + const int manager = team == no_team() ? -1 : g.manager_of(team); // local_5a int rank = 0; // local_5e if (manager >= 0) { const size_t rec = size_t(manager) * 0xB0C; @@ -151,7 +152,10 @@ int team_rating(GameState& g, int team, const RatingProfile& profile, RatingCont const int mode = (league < int(g.league_rounds.size()) && g.league_rounds[size_t(league)] > 9) + 1; std::array buf; int size_word = -1; - const int r = table_prediction(g, g.manager_teams.at(size_t(manager)), mode, buf, &size_word); + // TablePrediction of the season core that owns the game (SeasonHooks; Classic by default). + const int r = g.season_hooks && g.season_hooks->table_prediction + ? g.season_hooks->table_prediction(g, g.manager_teams.at(size_t(manager)), mode, buf, &size_word) + : table_prediction(g, g.manager_teams.at(size_t(manager)), mode, buf, &size_word); rank = r == 0 ? 0xB : r + 1; // Void5 (3 arguments) is called from the same frame as the player values // (PlayerValue, 6 arguments): its league size word (local_2c, [ESP+0xfc]) lands in diff --git a/src/game/reality_setup.cpp b/src/game/reality_setup.cpp index 32349d7..55a9c6e 100644 --- a/src/game/reality_setup.cpp +++ b/src/game/reality_setup.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "game/world_layout.hpp" #include "game/reality_setup.hpp" #include @@ -11,7 +12,7 @@ int manager(const GameState& state, int team) { const int found = state.manager_of(team); if (found >= 0) return found; // FindManagerForClub's separate national-manager record is not in manager_teams. - if (!state.manager_teams.empty() && state.manager_teams[0] == kNoTeam && + if (!state.manager_teams.empty() && state.manager_teams[0] == no_team() && state.manager_records.size() >= 4*0xb0c+0x292 && le16(state.manager_records,4*0xb0c+0x290) == team) return 4; return -1; diff --git a/src/game/schedule.cpp b/src/game/schedule.cpp index b56d090..afc15c5 100644 --- a/src/game/schedule.cpp +++ b/src/game/schedule.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "game/schedule.hpp" +#include "game/world_layout.hpp" #include "formats/executable_layout.hpp" #include "formats/le.hpp" @@ -129,7 +130,7 @@ void set_league_sizes(const uint8_t (&sizes)[kLeagueCount]) { int total = 0; for (int l = 0; l < kLeagueCount; l++) total += sizes[l]; const auto has_table = [](int teams) { return teams == 20 || teams == 18 || teams == 16 || teams == 12; }; - if (total != 138 || !has_table(sizes[0]) || !has_table(sizes[5])) + if (total != world_layout().league_teams || !has_table(sizes[0]) || !has_table(sizes[5])) throw std::invalid_argument("league sizes do not describe 138 league teams with fixture tables"); for (int l = 0; l < kLeagueCount; l++) if (sizes[l] < 2 || sizes[l] > (l < 5 ? sizes[0] : sizes[5])) diff --git a/src/game/sportschau_awards.cpp b/src/game/sportschau_awards.cpp index 06e1c36..5537c4a 100644 --- a/src/game/sportschau_awards.cpp +++ b/src/game/sportschau_awards.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "game/world_layout.hpp" #include "game/sportschau_presentation.hpp" #include #include "game/matchday.hpp" @@ -25,7 +26,7 @@ std::optional matchday_intro_view(const GameState& state, if (league >= 9) throw FormatError("matchday intro: invalid Source league"); // LeagueName with TeamStatistics_SourceLeagueName_RuntimeField=1 includes the secondary-league prefix. name = league < 5 ? league_name(state, int(league)) : - message_text(state, ::bmh::layout::SportschauAwards_MatchdayIntroView_TextPointer) + state.club_name(0x165 + int(league) - 4); + message_text(state, ::bmh::layout::SportschauAwards_MatchdayIntroView_TextPointer) + state.club_name(no_team() + int(league) - 4); } else { if (type > 14) throw FormatError("matchday intro: invalid Source competition type"); name = message_text(state, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(type) * 4); @@ -43,7 +44,7 @@ std::string sportschau_competition_title(const GameState& state, const MatchGrou if (id > 20) index = state.memory.u8(id + 0x18) + 9; else if (index >= 9) index = std::min(index + 12, 19); if (index < 5) return league_name(state, index); - if (index < 9) return state.club_name(0x165 + index - 4); + if (index < 9) return state.club_name(no_team() + index - 4); return message_text(state, ::bmh::layout::CupDraw_FormatError_ExecutableField6 + uint32_t(index - 9) * 4); } diff --git a/src/game/state.cpp b/src/game/state.cpp index 7e12be8..07abcd9 100644 --- a/src/game/state.cpp +++ b/src/game/state.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "game/world_layout.hpp" #include "game/state.hpp" #include @@ -10,11 +11,6 @@ namespace bmh { namespace { -// Squad table layout constants of V2.24 (TeamsWithSquads, LargeSquadClubCount, NoTeamSquadStart). -constexpr int kBigSquadTeams = 90; -constexpr size_t kNoTeamSquadStart = 3072; -constexpr int kTeamsWithSquads = 168; - // C-style signed division by 8 as compiled by Watcom (rounds toward zero). int div8(int x) { return x / 8; } @@ -156,14 +152,16 @@ void GameState::formation_position(int team, int slot, int& x, int& y) const { } SquadRange squad_range(int team) { - if (team == kNoTeam) return {kNoTeamSquadStart, 24}; - if (team < kBigSquadTeams) return {size_t(team) * 24, 24}; - if (team < 138) return {size_t(team) * 16 + kBigSquadTeams * 8, 16}; + // WorldLayout: Classic gives the original table (24 slots for the 90 German clubs, 16 for + // the 48 international ones from slot 2160, 24 for kNoTeam at 3072). + const WorldLayout& w = world_layout(); + if (team == w.no_team()) return {w.pool_end, w.no_team_slots}; + if (team >= 0 && team < w.league_teams) return {w.squad_start[size_t(team)], w.squad_size[size_t(team)]}; return {0, 0}; } TeamAverage team_average(const GameState& g, int team, uint16_t flags, WatcomRandom* rand) { - if (team >= kTeamsWithSquads && team != kNoTeam) { + if (team >= world_layout().first_foreign_cup() && team != no_team()) { // TeamRating(team, profile 2 at layout field): a random value around the club's level if (!rand) throw std::invalid_argument("team_average: a team without squad needs the Watcom generator"); RatingContext ctx; diff --git a/src/game/state.hpp b/src/game/state.hpp index 6ea501c..3ced5e1 100644 --- a/src/game/state.hpp +++ b/src/game/state.hpp @@ -24,6 +24,7 @@ namespace bmh { struct TransferOfferListView; struct TransferDecisionEvent; struct HumanBuyerSaleHooks; +struct GameState; // Special team id used by the original for "no club" / the player pool (0x165). constexpr int kNoTeam = 0x165; @@ -35,7 +36,19 @@ constexpr int kNoTeam = 0x165; constexpr uint16_t kEmptySlot = 0x0FFF; constexpr uint16_t kSlotInLineup = 0x8000; +// Season functions the shared match core calls back into. Classic leaves the pointer in +// GameState empty and the core calls its own season functions; the Modern season core +// (src/modern) installs its versions, so one match core serves both season cores. +struct SeasonHooks { + void (*player_statistic)(GameState& g, int competition_type, int player, int manager, int slot, int kind, + int minute) = nullptr; + int (*table_prediction)(GameState& g, int team, int mode, std::array& buf, + int* size_word) = nullptr; +}; + struct GameState { + // Season core callbacks for the shared match core; nullptr = Classic (see SeasonHooks). + const SeasonHooks* season_hooks = nullptr; std::vector squad_slots; // *SquadSlots, all squads back to back (see squad_range) std::vector players; // *PlayerConditionTechniqueForm / *PlayerSkillWords / *PlayerIdentityWords, names not filled std::vector team_morale; // *TeamMorale, per team: bits 0-5 morale / 2, bits 6-7 flags diff --git a/src/game/transfer_offer_view.hpp b/src/game/transfer_offer_view.hpp new file mode 100644 index 0000000..e757c35 --- /dev/null +++ b/src/game/transfer_offer_view.hpp @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Read-only views of the weekly transfer list decision. GameState callbacks refer to them, +// so they are shared by the Classic and the Modern season cores. + +#include +#include + +namespace bmh { + +// Projection passed to the optional original-style seller decision callback +// (TransferListCountdown -> IncomingTransferScreen). Rows retain raw bid slots 0..3; ranking, +// quote RNG, and transaction remain in the synchronous weekly call site. +struct TransferOfferCandidateView { + int bid_index = -1; + bool present = false; + int buyer = -1; + int buyer_manager = -1; + uint32_t fee = 0; + uint32_t monthly_salary = 0; + uint32_t fee_reference = 0; // RateTransferBidSource for this offer's term + uint32_t salary_reference = 0; + uint8_t contract_months = 0; // raw term low 7 bits; high bit is loan + bool loan = false; + std::array bonuses{}; + bool affordable = false; + bool has_squad_room = false; + bool passes_foreign_limit = false; + bool loan_permitted = true; + bool transaction_supported = true; // false for human-involved loans until return lifecycle is ported + bool eligible = false; +}; + +struct TransferOfferListView { + bool valid = false; + int list_entry = -1; + int player = -1; + int seller = -1; + int seller_manager = -1; + int seller_loan_count = -1; // DeskActions_Unsupported_RuntimeField[seller_manager], -1 when unavailable + int preferred_bid_index = -1; + bool preferred_bid_passed_random_check = false; // TransferListCountdown uVar6 < ranking score + int rejected_bid_index = -1; + uint32_t notice_text_address = 0; + uint32_t quoted_fee = 0; + uint32_t quoted_monthly_salary = 0; + uint8_t quoted_years = 0; + uint32_t asking_fee = 0; + uint32_t asking_monthly_salary = 0; + int offer_count = 0; + std::array offers{}; +}; + +// Source-backed read-only events around transfer settlement and countdown +// notices. `offers` owns a snapshot of all four raw bid slots; selected_bid_index +// is the ranked raw row, not a compact row. last_week is the system modal at +// countdown 2 -> 1 and carries result_text_address PendingOffer_TransferLastWeekDialog_ExecutableField. +enum class TransferDecisionEventKind { evaluation, confirmation, last_week }; +struct TransferDecisionEvent { + TransferDecisionEventKind kind = TransferDecisionEventKind::evaluation; + TransferOfferListView offers; + int selected_bid_index = -1; + bool accepted = false; // evaluation: the one W(90,110) result; confirmation: accepted/declined + int viewer_manager = -1; // ActiveManager at evaluation; human seller first, otherwise buyer + uint32_t result_text_address = 0; // evaluation: OK/NEIN; confirmation: PendingOffer_FormatError_ExecutableField2 / PendingOffer_PendingOfferNoticeDialog_ExecutableField +}; + +} // namespace bmh diff --git a/src/game/weekly.hpp b/src/game/weekly.hpp index 937e367..8d1dae9 100644 --- a/src/game/weekly.hpp +++ b/src/game/weekly.hpp @@ -23,6 +23,7 @@ #include "game/random.hpp" #include "game/state.hpp" #include "game/transfer_allocator.hpp" +#include "game/transfer_offer_view.hpp" #include #include @@ -30,63 +31,6 @@ namespace bmh { -// Projection passed to the optional original-style seller decision callback -// (TransferListCountdown -> IncomingTransferScreen). Rows retain raw bid slots 0..3; ranking, -// quote RNG, and transaction remain in the synchronous weekly call site. -struct TransferOfferCandidateView { - int bid_index = -1; - bool present = false; - int buyer = -1; - int buyer_manager = -1; - uint32_t fee = 0; - uint32_t monthly_salary = 0; - uint32_t fee_reference = 0; // RateTransferBidSource for this offer's term - uint32_t salary_reference = 0; - uint8_t contract_months = 0; // raw term low 7 bits; high bit is loan - bool loan = false; - std::array bonuses{}; - bool affordable = false; - bool has_squad_room = false; - bool passes_foreign_limit = false; - bool loan_permitted = true; - bool transaction_supported = true; // false for human-involved loans until return lifecycle is ported - bool eligible = false; -}; - -struct TransferOfferListView { - bool valid = false; - int list_entry = -1; - int player = -1; - int seller = -1; - int seller_manager = -1; - int seller_loan_count = -1; // DeskActions_Unsupported_RuntimeField[seller_manager], -1 when unavailable - int preferred_bid_index = -1; - bool preferred_bid_passed_random_check = false; // TransferListCountdown uVar6 < ranking score - int rejected_bid_index = -1; - uint32_t notice_text_address = 0; - uint32_t quoted_fee = 0; - uint32_t quoted_monthly_salary = 0; - uint8_t quoted_years = 0; - uint32_t asking_fee = 0; - uint32_t asking_monthly_salary = 0; - int offer_count = 0; - std::array offers{}; -}; - -// Source-backed read-only events around transfer settlement and countdown -// notices. `offers` owns a snapshot of all four raw bid slots; selected_bid_index -// is the ranked raw row, not a compact row. last_week is the system modal at -// countdown 2 -> 1 and carries result_text_address PendingOffer_TransferLastWeekDialog_ExecutableField. -enum class TransferDecisionEventKind { evaluation, confirmation, last_week }; -struct TransferDecisionEvent { - TransferDecisionEventKind kind = TransferDecisionEventKind::evaluation; - TransferOfferListView offers; - int selected_bid_index = -1; - bool accepted = false; // evaluation: the one W(90,110) result; confirmation: accepted/declined - int viewer_manager = -1; // ActiveManager at evaluation; human seller first, otherwise buyer - uint32_t result_text_address = 0; // evaluation: OK/NEIN; confirmation: PendingOffer_FormatError_ExecutableField2 / PendingOffer_PendingOfferNoticeDialog_ExecutableField -}; - // Projects the current live rows without mutation or RNG. The selector caller // performs the Source-ranked selection and ProjectTransferOfferList post-selection check. TransferOfferListView project_transfer_offer_list(const GameState& g, int list_entry); diff --git a/src/game/world_layout.cpp b/src/game/world_layout.cpp new file mode 100644 index 0000000..b738732 --- /dev/null +++ b/src/game/world_layout.cpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/world_layout.hpp" + +#include +#include + +namespace bmh { + +namespace { + +WorldLayout& current() { + static WorldLayout layout = classic_world_layout(); + return layout; +} + +} // namespace + +WorldLayout classic_world_layout() { + // Squad table of V2.24 (TeamsWithSquads, LargeSquadClubCount, NoTeamSquadStart): the + // 90 German clubs have 24 slots, the 48 international clubs 16 from slot 90 * 24. + WorldLayout w; + w.squad_start.resize(size_t(w.league_teams)); + w.squad_size.resize(size_t(w.league_teams)); + for (int team = 0; team < w.league_teams; ++team) { + const bool german = team < w.german_teams; + w.squad_start[size_t(team)] = german ? uint32_t(team) * 24 : uint32_t(team) * 16 + uint32_t(w.german_teams) * 8; + w.squad_size[size_t(team)] = german ? 24 : 16; + } + return w; +} + +const WorldLayout& world_layout() { return current(); } + +void set_world_layout(WorldLayout layout) { + const size_t teams = size_t(layout.league_teams); + if (layout.league_teams <= 0 || layout.german_teams < 0 || layout.german_teams > layout.league_teams || + layout.amateur_teams < 0 || layout.foreign_cup_teams < 0 || layout.national_teams < 0 || + layout.squad_start.size() != teams || layout.squad_size.size() != teams) + throw std::invalid_argument("world layout: inconsistent team ranges"); + // Squads lie back to back in id order before the pools; the pools and the no-club + // squad follow in their fixed order. + uint32_t next = 0; + for (size_t team = 0; team < teams; ++team) { + if (layout.squad_start[team] != next || layout.squad_size[team] == 0) + throw std::invalid_argument("world layout: squads must be consecutive"); + next += layout.squad_size[team]; + } + if (layout.transfer_list != next || layout.free_agents != layout.transfer_list + 44 || + layout.foreign_offers != layout.free_agents + 80 || layout.pool_end != layout.foreign_offers + 20 || + layout.total_slots < layout.pool_end + layout.no_team_slots) + throw std::invalid_argument("world layout: pools must follow the squads"); + // Squad slot values hold 12-bit player ids; loans store 10-bit club ids. + if (layout.total_teams() > 1023) throw std::invalid_argument("world layout: too many teams"); + current() = std::move(layout); +} + +} // namespace bmh diff --git a/src/game/world_layout.hpp b/src/game/world_layout.hpp new file mode 100644 index 0000000..c8eb16d --- /dev/null +++ b/src/game/world_layout.hpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The dimensions of a game world: team id ranges and the squad slot table. +// +// The original game (Classic) fixes them: 138 league clubs (90 German with 24 squad +// slots, 48 international with 16), 30 amateur clubs, 189 squadless foreign cup clubs, +// the pseudo team kNoTeam (0x165) for the national team / player pool, and the +// player pools behind the squads. Classic never changes the layout, so every shared +// function below returns exactly the original numbers there. +// +// The Modern season core (docs/new_engine) installs a layout derived from its world +// data, for example 168 league clubs with 24 slots each. One game per process, like +// the league tables of schedule.hpp. + +#include +#include +#include + +namespace bmh { + +struct SquadRange; + +struct WorldLayout { + // Team id ranges, in this order: league clubs, amateur clubs (cup newcomers), + // squadless foreign cup clubs, the pseudo team "no club", national teams. + int league_teams = 138; // ids 0 .. league_teams-1 have squads + int german_teams = 90; // the first league clubs (German leagues) + int amateur_teams = 30; // ids league_teams .. +amateur_teams-1, no squads + int foreign_cup_teams = 189; // squadless foreign clubs (27 nations x 7) + int national_teams = 62; // after no_team + + // Squad slot table: first slot and slot count per league club, then the pools. + std::vector squad_start; // per league club + std::vector squad_size; // per league club + uint32_t transfer_list = 0xB70; // 44 slots: players on the transfer list + uint32_t free_agents = 0xB9C; // 80 slots: players without a club + uint32_t foreign_offers = 0xBEC; // 20 slots: players offered from abroad + uint32_t pool_end = 0xC00; // end of the pools = first slot of no_team + uint32_t no_team_slots = 24; // the national team / no-club squad + uint32_t total_slots = 3150; // including the reserve behind no_team + + int first_amateur() const { return league_teams; } + int first_foreign_cup() const { return league_teams + amateur_teams; } + int no_team() const { return first_foreign_cup() + foreign_cup_teams; } + int total_teams() const { return no_team() + national_teams; } + bool has_squad(int team) const { return (team >= 0 && team < league_teams) || team == no_team(); } +}; + +// The original dimensions (V2.24 and the supported German and English editions). +WorldLayout classic_world_layout(); + +// The layout of the running game (Classic unless a Modern session installed another). +const WorldLayout& world_layout(); +void set_world_layout(WorldLayout layout); + +// Shortcut for the pseudo team "no club" of the running game (Classic: kNoTeam, 0x165). +inline int no_team() { return world_layout().no_team(); } + +} // namespace bmh diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp new file mode 100644 index 0000000..9dc553e --- /dev/null +++ b/src/modern/app/modern_session.cpp @@ -0,0 +1,8628 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/app/modern_session.hpp" +#include "modern/game/balance_plan.hpp" +#include "modern/game/bank_credit.hpp" +#include "modern/game/career.hpp" +#include "modern/game/club_info.hpp" +#include "modern/game/club_player_detail.hpp" +#include "modern/game/cup.hpp" +#include "modern/game/desk.hpp" +#include "modern/game/desk_actions.hpp" +#include "modern/game/driver.hpp" +#include "modern/game/environment.hpp" +#include "modern/game/highscore.hpp" +#include "modern/game/league_pairings.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" +#include "modern/game/month.hpp" +#include "modern/game/national.hpp" +#include "modern/game/other_games.hpp" +#include "modern/game/poach.hpp" +#include "modern/game/prediction.hpp" +#include "modern/game/reschedule.hpp" +#include "modern/game/save.hpp" +#include "modern/game/season.hpp" +#include "modern/game/source_tip.hpp" +#include "modern/game/stadium_blocks.hpp" +#include "modern/game/table_forecast.hpp" +#include "modern/game/turn.hpp" +#include "modern/game/turn_driver.hpp" +#include "modern/game/week.hpp" +#include "modern/game/weekly.hpp" +#include "content/save.hpp" +#include "import/save.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "formats/fbm.hpp" +#include "formats/savestate.hpp" +#include "modern/game/career.hpp" +#include "modern/game/cup.hpp" +#include "modern/game/driver.hpp" +#include "modern/game/desk.hpp" +#include "modern/game/desk_actions.hpp" +#include "game/match.hpp" +#include "game/messages.hpp" +#include "modern/game/prediction.hpp" +#include "game/schedule.hpp" +#include "modern/game/bank_credit.hpp" +#include "modern/game/matchday_setup.hpp" +#include "modern/game/matchday.hpp" +#include "game/lineup.hpp" +#include "modern/game/month.hpp" +#include "modern/game/national.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "modern/game/table_forecast.hpp" +#include "modern/game/save.hpp" +#include "modern/game/season.hpp" +#include "modern/game/turn.hpp" +#include "modern/game/week.hpp" +#include "modern/game/weekly.hpp" +#include "ui/desk_state.hpp" +#include "ui/league_table.hpp" +#include "ui/other_games_state.hpp" +#include "ui/manager.hpp" +#include "ui/pending_offer.hpp" +#include "ui/training.hpp" + +namespace bmh::modern::app { +namespace { +std::atomic next_session_id{1}; + +constexpr uint32_t kSavedCalendar = ::bmh::layout::CompetitionCalendar; +constexpr uint32_t kSavedCompetitionBits = ::bmh::layout::SavedCompetition; +constexpr uint8_t kBlockSeat = 1; +constexpr uint8_t kBlockRoof = 2; +constexpr uint8_t kBlockFeatures = kBlockSeat | kBlockRoof; + +bool is_block_expansion_action(ui::StadiumRequestKind kind) { + return kind == ui::StadiumRequestKind::expansion_select || + kind == ui::StadiumRequestKind::expansion_set_total || + kind == ui::StadiumRequestKind::expansion_toggle_feature || + kind == ui::StadiumRequestKind::expansion_cancel || + kind == ui::StadiumRequestKind::expansion_confirm || + kind == ui::StadiumRequestKind::expansion_answer_tip; +} + +int national_opportunities_rank(const ModernState& game,int team,std::array& ranks) { + ranks.fill(1); + const int rounds=game.league_rounds.empty()?0:int8_t(game.league_rounds.at(0)); + if(rounds<2||rounds>=league_matchdays(0))return 0; + return team>=modern::league_clubs()?9:0; +} + +uint8_t source_runtime_byte(const ModernState& state,const std::map& runtime, + const LeImage& exe,uint32_t address) { + if(state.memory.has(address))return state.memory.u8(address); + const auto found=runtime.find(address);return found==runtime.end()?exe.u8(address):found->second; +} +void source_runtime_set_byte(ModernState& state,std::map& runtime, + uint32_t address,uint8_t value) { + if(state.memory.has(address))state.memory.set8(address,value); + else runtime[address]=value; +} + +uint32_t source_runtime_u32(const ModernState& state,const std::map& runtime, + const LeImage& exe,uint32_t address) { + return uint32_t(source_runtime_byte(state,runtime,exe,address)) | + uint32_t(source_runtime_byte(state,runtime,exe,address+1))<<8 | + uint32_t(source_runtime_byte(state,runtime,exe,address+2))<<16 | + uint32_t(source_runtime_byte(state,runtime,exe,address+3))<<24; +} + +void apply_balance_source_style(ui::BalanceState& page,const ModernState& state, + const std::map& runtime,const LeImage& exe) { + page.decorated=source_runtime_byte(state,runtime,exe,::bmh::layout::PlainBackground)==0; + page.original_panel=source_runtime_byte(state,runtime,exe,::bmh::layout::SolidPanelBackground)==0; + page.gradient=source_runtime_byte(state,runtime,exe,::bmh::layout::TextGradientDisabled)==0 && + source_runtime_byte(state,runtime,exe,::bmh::layout::TextGradientMode)==2; + page.cached_backdrop=source_runtime_u32(state,runtime,exe,::bmh::layout::CareerSession_ApplyBalanceSourceStyle_ExecutableField)!=0; +} + +uint32_t saved_group_u32(const Bytes& bytes, size_t offset) { + return uint32_t(bytes.at(offset)) | (uint32_t(bytes.at(offset + 1)) << 8) | + (uint32_t(bytes.at(offset + 2)) << 16) | (uint32_t(bytes.at(offset + 3)) << 24); +} + +void initialize_saved_match_group(MatchGroup& group, const ModernState& state, size_t index, + int league) { + group.desc = modern::group_descriptor(state, index); + if (group.desc.size() != 0xd0 || group.desc[0] != 0 || + saved_group_u32(group.desc, 0xcc) != uint32_t(league)) + throw std::runtime_error("saved turn cursor: league descriptor does not match the active calendar"); + const int round = state.league_rounds.at(size_t(league)); + const auto fixtures = league_fixtures(league, round + 1); + if (group.desc[2] != fixtures.size()) + throw std::runtime_error("saved turn cursor: league fixture count is incomplete"); + for (const Fixture& fixture : fixtures) { + group.fixtures.push_back(fixture.home); + group.fixtures.push_back(fixture.away); + } + const size_t result_at = size_t(league) * 0x17c + size_t(round) * 10; + if (result_at + fixtures.size() > state.results.size()) + throw std::runtime_error("saved turn cursor: league result block is incomplete"); + group.results.assign(state.results.begin() + long(result_at), + state.results.begin() + long(result_at + fixtures.size())); + // Assign2 and the match loop read exactly one mask bit per descriptor + // match. Before kickoff, a saved desk can retain high bits from the previous + // larger group; those padding bits are not fixture identities and are ignored + // by the original. Keep the saved descriptor intact and validate actual + // fixture count, result range, and active league above. + // These per-match arrays are transient runtime data. kick_off rebuilds them from + // the authoritative saved lineups; no setup/event replay belongs in the loader. + group.records.assign(fixtures.size() * 18, 0); + group.end_minute.assign(fixtures.size(), 0); + group.spectators.assign(fixtures.size(), 0); +} + +void initialize_saved_cup_group(MatchGroup& group, const ModernState& state, size_t index, + int cup_id, int entry_index) { + const StaticMemory& mem = state.memory; + group.desc = modern::group_descriptor(state, index); + const uint32_t guest_entry = saved_group_u32(group.desc, 0xcc); + if (group.desc.size() != 0xd0 || group.desc[0] != cup_id + 1 || + guest_entry < kGuestDataBase || (guest_entry - kGuestDataBase) != modern::cup_entry_address(entry_index)) + throw std::runtime_error("cup descriptor mismatch group=" + std::to_string(index) + + " type=" + std::to_string(group.desc[0]) + + " guest=" + std::to_string(guest_entry) + + " stage=" + std::to_string(entry_index)); + const uint32_t entry = modern::cup_entry_address(entry_index); + // In memory the descriptor stores a guest pointer; MatchGroup carries the data-object + // address, as setup_cup_groups does before store_group_descriptors adds the guest base. + for (int i = 0; i < 4; ++i) group.desc.at(0xcc + size_t(i)) = uint8_t(entry >> (i * 8)); + const uint8_t flags = mem.u8(entry + 0x14); + const bool knockout = (flags & 4) != 0; + const int teams = mem.u8(entry + 0x1a); + if (int16_t(mem.u16(entry + 0x18)) != cup_id || teams < 2 || (teams & 1) || + group.desc[2] == 0 || group.desc[2] > (knockout ? 32 : 18)) + throw std::runtime_error("saved turn cursor: cup descriptor has invalid stage or match count"); + const int round = modern::cup_round(mem, entry_index); + int first = 0; + int expected_matches = 0; + if (knockout) { + if (round < 0 || round >= 8 || (1 << (round + 1)) > teams) + throw std::runtime_error("saved turn cursor: cup knockout round is outside the stage"); + expected_matches = teams / (1 << (round + 1)); + first = uint8_t(modern::cup_round_offset(mem, entry_index, round)); + } else { + if (teams / 2 > 18) throw std::runtime_error("saved turn cursor: cup group is too large"); + expected_matches = teams / 2; + // Group-stage fixtures are stored in descriptor +0x88; KO descriptors do not + // contain fixture IDs there. Their IDs come from the stage's round-indexed list. + first = uint8_t(expected_matches * mem.u8(entry + 0x1d) * 2); + } + if (expected_matches != group.desc[2]) + throw std::runtime_error("saved turn cursor: cup round match count disagrees with its descriptor"); + const size_t fixture_count = size_t(group.desc[2]) * 2; + // As in Assign2, only bits [0, group.desc[2]) are read. The descriptor + // can carry stale high padding bits from the preceding event; preserve them + // in the copy rather than treating them as corrupt fixture references. + const uint32_t list = mem.pointer(entry); + if (list == 0 || (knockout + ? !mem.has(list + uint32_t(first + expected_matches * 2) * 2 - 1) + : !mem.has(list + uint32_t(teams) * 2 - 1))) + throw std::runtime_error("saved turn cursor: cup team list is missing"); + auto valid_team = [&](int team) { + return team >= 0 && size_t(team) < state.team_flags.size(); + }; + std::vector cup_teams; + cup_teams.reserve(size_t(teams)); + for (int i = 0; !knockout && i < teams; ++i) { + const int team = int16_t(mem.u16(list + uint32_t(i) * 2)); + if (!valid_team(team) || + std::find(cup_teams.begin(), cup_teams.end(), team) != cup_teams.end()) + throw std::runtime_error("saved turn cursor: cup team list contains an invalid or duplicate team"); + cup_teams.push_back(team); + } + if (!knockout) { + int table_teams = 0; + switch (mem.pointer(entry + 8)) { + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: table_teams = 4; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: table_teams = 6; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: table_teams = 12; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: table_teams = 16; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: table_teams = 18; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: table_teams = 20; break; + default: throw std::runtime_error("saved turn cursor: cup group has unknown round strings"); + } + const int rounds = mem.u8(entry + 0x1b) / ((flags & 1) + 1); + const std::vector expected = generate_fixtures(table_teams, round + 1, rounds, 0); + if (expected.size() < fixture_count / 2) + throw std::runtime_error("saved turn cursor: cup group round is incomplete"); + std::vector expected_fixture_ids; + expected_fixture_ids.reserve(fixture_count); + for (size_t i = 0; i < fixture_count / 2; ++i) { + if (expected[i].home < 0 || expected[i].home >= teams || + expected[i].away < 0 || expected[i].away >= teams) + throw std::runtime_error("saved turn cursor: cup round exceeds the saved team list"); + const int home = int16_t(mem.u16(list + uint32_t(expected[i].home) * 2)); + const int away = int16_t(mem.u16(list + uint32_t(expected[i].away) * 2)); + if (!valid_team(home) || !valid_team(away) || home == away || + std::find(cup_teams.begin(), cup_teams.end(), home) == cup_teams.end() || + std::find(cup_teams.begin(), cup_teams.end(), away) == cup_teams.end()) + throw std::runtime_error("saved turn cursor: generated cup fixture references an invalid team"); + expected_fixture_ids.push_back(home); + expected_fixture_ids.push_back(away); + } + for (size_t i = 0; i < fixture_count; ++i) { + const size_t at = 0x88 + i * 2; + const int team = int16_t(uint16_t(group.desc.at(at)) | (uint16_t(group.desc.at(at + 1)) << 8)); + if (team != expected_fixture_ids[i]) + throw std::runtime_error("saved turn cursor: cup fixture IDs disagree with the saved round"); + group.fixtures.push_back(team); + } + } else { + // SetupCupGroups derives KO fixtures from the stage team list and + // cup_round_offset; descriptor +0x88 is not populated for KO stages. + std::vector active_teams; + for (int i = 0; i < expected_matches * 2; ++i) { + const int team = int16_t(mem.u16(list + uint32_t(first + i) * 2)); + if (!valid_team(team) || std::find(active_teams.begin(), active_teams.end(), team) != active_teams.end()) + throw std::runtime_error("saved turn cursor: knockout fixture references an invalid team"); + active_teams.push_back(team); + group.fixtures.push_back(team); + } + for (int m = 0; m < expected_matches; ++m) + if (group.fixtures[size_t(m) * 2] == group.fixtures[size_t(m) * 2 + 1]) + throw std::runtime_error("saved turn cursor: knockout fixture contains the same team twice"); + } + + for (int leg = 0; leg < 2; ++leg) { + if (leg == 1 && !(flags & 1)) break; + const uint32_t address = mem.pointer(entry + 0x0c + uint32_t(leg) * 4); + // setup_cup_groups leaves the corresponding result vector empty when this stage + // has no result-array pointer; the match engine initializes its runtime scores. + if (address == 0) continue; + const uint32_t result_at = address + uint32_t(first / 2) * 2; + if (!mem.has(result_at + uint32_t(group.matches()) * 2 - 1)) + throw std::runtime_error("saved turn cursor: cup result array is missing"); + if (leg == 0) group.cup_result_address[0] = result_at; + else group.cup_result_address[1] = result_at; + std::vector& results = leg == 0 ? group.cup_results : group.cup_other_leg; + for (int m = 0; m < group.matches(); ++m) + results.push_back(mem.u16(result_at + uint32_t(m) * 2)); + } + group.records.assign(fixture_count * 9, 0); + group.end_minute.assign(size_t(group.matches()), 0); + group.spectators.assign(size_t(group.matches()), 0); +} + +int current_cup_stage(const StaticMemory& mem, int cup_id) { + int entry = modern::find_cup(mem, cup_id); + if (entry < 0) return -1; + for (int guard = 0; guard < kCupEntries; ++guard) { + const uint32_t address = modern::cup_entry_address(entry); + if (modern::cup_round(mem, entry) < mem.u8(address + 0x1b)) return entry; + const int next = int8_t(mem.u8(address + 0x16)); + if (next < 0 || next >= kCupEntries) return -1; + entry = next; + } + return -1; +} + +void initialize_saved_replay_group(MatchGroup& group, ModernState& state, size_t index, + int entry_index, int day) { + constexpr uint32_t kPostponed = ::bmh::layout::Postponed; + constexpr uint32_t kReplayFixtures = ::bmh::layout::ReplayFixtures; + constexpr uint32_t kReplayResults = ::bmh::layout::ReplayResults; + constexpr uint8_t kPostponedMark = 0xcd; + constexpr int kMaxReplayMatches = 9; // AddBlock clears 0x12 result bytes. + StaticMemory& mem = state.memory; + const uint32_t entry = modern::cup_entry_address(entry_index); + group.desc = modern::group_descriptor(state, index); + const uint32_t saved_entry = saved_group_u32(group.desc, 0xcc); + const uint8_t flags = mem.u8(entry + 0x14); + if (group.desc.size() != 0xd0 || group.desc[0] != 10 || + saved_entry != kGuestDataBase + entry || group.desc[1] != flags || + int16_t(mem.u16(entry + 0x18)) != 9 || flags != 6 || + mem.u8(entry + 0x1d) != 0 || (mem.u8(entry + 0x1e) & 0x0f) != 1 || + mem.pointer(entry) != kReplayFixtures || mem.pointer(entry + 0x0c) != kReplayResults || + mem.pointer(entry + 0x10) != 0) + throw std::runtime_error("saved replay descriptor or stage is inconsistent"); + + std::vector replay_fixtures; + std::vector replay_keys; + replay_fixtures.reserve(kMaxReplayMatches); + for (int i = 0; i < 0x28; ++i) { + const uint32_t record = kPostponed + uint32_t(i) * 6; + if (mem.u16(record) != day) continue; + const int round = mem.u8(record + 2); + const int league = mem.u8(record + 3); + const int match = mem.u8(record + 4); + if (league < 0 || league >= kLeagueCount || round < 0 || + round >= league_matchdays(league) || + match >= int(kLeagueSizes[league] / 2)) + throw std::runtime_error("saved replay record is outside the league schedule"); + const std::vector fixtures = generate_fixtures( + league_table_teams(league), round + 1, league_matchdays(league) / 2, + league_first_team(league)); + if (match >= int(fixtures.size())) + throw std::runtime_error("saved replay record has no corresponding fixture"); + const size_t result = size_t(league) * 0x17c + size_t(round) * 10 + size_t(match); + if (result >= state.results.size() || state.results[result] != kPostponedMark) + throw std::runtime_error("saved replay record has no postponed result marker"); + const uint32_t key = (uint32_t(league) << 16) | (uint32_t(round) << 8) | uint32_t(match); + if (std::find(replay_keys.begin(), replay_keys.end(), key) != replay_keys.end()) + throw std::runtime_error("saved replay records contain a duplicate schedule key"); + const Fixture fixture = fixtures[size_t(match)]; + replay_keys.push_back(key); + replay_fixtures.push_back(fixture); + if (replay_fixtures.size() > kMaxReplayMatches) + throw std::runtime_error("saved replay day exceeds its result buffer"); + } + if (replay_fixtures.empty() || group.desc[2] != replay_fixtures.size() || + mem.u8(entry + 0x1a) != replay_fixtures.size() * 2) + throw std::runtime_error("saved replay match count disagrees with its records"); + // Neither transient address is in SaveState's serialized block layout; a loaded + // ModernState therefore has no valid prior runtime buffer to reuse. + if (mem.has(kReplayFixtures) || mem.has(kReplayResults)) + throw std::runtime_error("saved replay transient blocks are unexpectedly present"); + + // The original rebuilds these two non-savegame buffers in AddBlock. Recreate + // only their current values, leaving the saved replay records/stage counters intact. + mem.add_block(kReplayFixtures, 0x50); + mem.add_block(kReplayResults, 0x12); + for (int i = 0; i < kMaxReplayMatches; ++i) + mem.set16(kReplayResults + uint32_t(i) * 2, 0xcccc); + for (size_t i = 0; i < replay_fixtures.size(); ++i) { + mem.set16(kReplayFixtures + uint32_t(i) * 4, uint16_t(replay_fixtures[i].home)); + mem.set16(kReplayFixtures + uint32_t(i) * 4 + 2, uint16_t(replay_fixtures[i].away)); + group.fixtures.push_back(replay_fixtures[i].home); + group.fixtures.push_back(replay_fixtures[i].away); + group.cup_results.push_back(0xcccc); + } + group.cup_result_address[0] = kReplayResults; + for (int i = 0; i < 4; ++i) group.desc.at(0xcc + size_t(i)) = uint8_t(entry >> (i * 8)); + group.records.assign(replay_fixtures.size() * 18, 0); + group.end_minute.assign(replay_fixtures.size(), 0); + group.spectators.assign(replay_fixtures.size(), 0); +} + +void restore_saved_turn_cursor(TurnDriver& driver, ModernState& state, const Database& db, + uint64_t session_id, uint64_t revision, + std::string& unsupported_continuation) { + // Original DailyInterest's resume path skips new-event preparation. Rebind its saved + // desk position and event data directly; replaying prepare_event here would draw RNG, + // reshuffle managers, and rewrite saved team state. + if (revision == 0 || session_id == 0 || state.manager_teams.empty()) + throw std::runtime_error("saved turn cursor: invalid session identity or manager roster"); + const int manager_count = int(state.manager_teams.size()); + if (manager_count > 4 || !state.memory.has(::bmh::layout::ActiveManager) || !state.memory.has(::bmh::layout::DeskPosition)) + throw std::runtime_error("saved turn cursor: manager continuation fields are missing"); + const int position = int(state.memory.u8(::bmh::layout::DeskPosition)); + const int active = int(state.memory.u8(::bmh::layout::ActiveManager)); + if (position < 0 || position >= manager_count) + throw std::runtime_error("saved turn cursor: manager position is outside the saved roster"); + if (manager_count == 1) { + if (position != 0 || active != 0) + throw std::runtime_error("saved turn cursor: single-manager slot does not match the saved desk"); + } else { + if (!state.memory.has(::bmh::layout::NextDeskManager + uint32_t(manager_count) * 2 - 1)) + throw std::runtime_error("saved turn cursor: manager order is missing"); + std::vector seen(size_t(manager_count), false); + for (int i = 0; i < manager_count; ++i) { + const int slot = int(state.memory.u16(::bmh::layout::NextDeskManager + uint32_t(i) * 2)); + if (slot < 0 || slot >= manager_count || seen[size_t(slot)]) + throw std::runtime_error("saved turn cursor: manager order is sparse or duplicated"); + seen[size_t(slot)] = true; + } + if (active != int(state.memory.u16(::bmh::layout::NextDeskManager + uint32_t(position) * 2))) + throw std::runtime_error("saved turn cursor: active manager disagrees with saved order"); + } + + if (state.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && state.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) { + driver.stage = TurnDriver::Stage::SeasonEndDesk; + driver.loaded_matchday_resume = true; + driver.manager_position = position; + driver.revision = revision; + driver.session_id = session_id; + driver.referee_source = db.raw_referee_properties; + driver.referees = driver.referee_source; + return; + } + const int day = state.season_day(); + if (day < 0 || day >= 0x16d || !state.memory.has(kSavedCalendar + uint32_t(day) * 2 + 1) || + !state.memory.has(kSavedCompetitionBits + 3)) + throw std::runtime_error("saved turn cursor: current calendar entry is missing"); + const uint16_t entry = state.memory.u16(kSavedCalendar + uint32_t(day) * 2); + const uint32_t calendar_competitions = modern::day_competitions(state, entry); + const uint32_t saved_competitions = state.memory.u32(kSavedCompetitionBits); + // AdvanceTurn maps the national-team-only marker national-only flag to saved + // SavedCompetition=0 before it creates the no-fixture desk. Resume must compare + // against that canonical saved value, not treat the calendar marker as a cup. + const uint32_t competitions = calendar_competitions == 0x800000 && saved_competitions == 0 + ? 0 : calendar_competitions; + if (competitions != saved_competitions) + throw std::runtime_error("saved turn cursor: current calendar and saved competition flags disagree"); + if (competitions & ~0x7ffffu) + unsupported_continuation = "Dieser Spieltag kann mit den verfügbaren Wettbewerbsdaten derzeit nicht fortgesetzt werden."; + if (!unsupported_continuation.empty()) return; + + std::vector active_leagues; + // Expand the selected edition's groups. Only the German third divisions + // share bit 2; the English divisions each have their own calendar group. + // Stale descriptors beyond the active group count are ignored. + for (int bit = 0; bit < 5; ++bit) { + if (!((competitions >> bit) & 1u)) continue; + const int first = bit, last = bit < 4 ? bit + 1 : 8; + for (int k = first; k < last; ++k) + for (int league = kGroupLeague[k]; league < kGroupLeague[k] + kGroupLeagues[k]; ++league) + active_leagues.push_back(league); + } + if (active_leagues.size() > 6) + throw std::runtime_error("saved turn cursor: too many league fixtures are active"); + + std::vector groups; + groups.reserve(active_leagues.size()); + for (size_t i = 0; i < active_leagues.size(); ++i) { + MatchGroup group; + initialize_saved_match_group(group, state, i, active_leagues[i]); + groups.push_back(std::move(group)); + } + // Rebind saved cup descriptors and their current stage fixtures/results. Group-stage + // IDs live at descriptor +0x88; KO IDs live in the stage list. Replays reconstruct + // only missing transient buffers. Calling setup_cup_groups would replay event work. + bool has_empty_cup = false; + try { + for (int bit = 5; bit < 0x13; ++bit) { + if (!((competitions >> bit) & 1u)) continue; + const int cup_id = bit - 5; + int entry = current_cup_stage(state.memory, cup_id); + if (entry < 0) throw std::runtime_error("cup stage is missing"); + const uint32_t first_entry = modern::cup_entry_address(entry); + const int type = int16_t(state.memory.u16(first_entry + 0x18)); + // Type 9's daily fixtures can be reconstructed from the saved postponed-match + // records. Other special competitions need preparation hooks and stay guarded. + if (type < 0 || (type > 9 && type != 10 && type != 11 && type != 13)) + throw std::runtime_error("this cup type requires event preparation"); + // SetupCupGroups creates a group only inside its per-stage `teams != 0` + // branch. A validated type-8 stage with zero teams is therefore a valid + // no-group cup day. On FBM load, competition_pointers() rebinds the native + // null list pointer to its runtime address; the team-count gate is the + // stable Source behavior across both representations. + if (type == 8 && state.memory.u8(first_entry + 0x1a) == 0) { + has_empty_cup = true; + continue; + } + // SetupCupGroups sets CareerSessionRuntimeField while projecting competition 11. + // This runtime-only mode is absent from the saved byte stream, so infer + // it from the authoritative active cup while rebuilding its MatchGroup. + if (type == 11) state.indoor = true; + const int parallel = state.memory.u8(first_entry + 0x1e) & 0x0f; + if (parallel == 0) throw std::runtime_error("cup stage has no saved parallel groups"); + const size_t groups_before_cup = groups.size(); + for (int k = 0; k < parallel; ++k, ++entry) { + if (entry < 0 || entry >= kCupEntries) + throw std::runtime_error("cup stage points outside the saved cup table"); + if (state.memory.u8(modern::cup_entry_address(entry) + 0x1a) == 0) continue; + if (groups.size() >= 6) + throw std::runtime_error("too many saved match groups"); + MatchGroup group; + if (type == 9) + initialize_saved_replay_group(group, state, groups.size(), entry, day); + else + initialize_saved_cup_group(group, state, groups.size(), cup_id, entry); + groups.push_back(std::move(group)); + } + if (groups.size() == groups_before_cup) + throw std::runtime_error("cup stage has no saved fixture group"); + } + if (competitions != 0 && groups.empty() && !has_empty_cup) + throw std::runtime_error("active matchday has no saved fixture groups"); + } catch (const std::exception& e) { + (void)e; // Do not expose internal parser/descriptor details to the player. + unsupported_continuation = "Der Pokalspieltag kann mit den gespeicherten Paarungen nicht sicher fortgesetzt werden."; + return; + } + if (!groups.empty() && db.raw_referee_properties.empty()) + throw std::runtime_error("saved turn cursor: referee source is missing"); + std::vector referees = db.raw_referee_properties; + for (uint8_t& ref : referees) ref &= 0x7f; + for (const MatchGroup& group : groups) + for (int m = 0; m < group.matches(); ++m) { + const uint8_t ref = group.desc.at(0x10 + size_t(m)); + if (ref > 0 && ref < referees.size()) referees[ref] |= 0x80; + } + std::string error; + if (!modern::begin_turn_driver(driver, state, std::move(groups), entry, db.raw_referee_properties, + session_id, revision, error)) + throw std::runtime_error("saved turn cursor: " + error); + driver.referees = std::move(referees); + // Runtime provenance belongs to this successfully restored Native desk loop. + // It is not inferred from a nonzero cursor, and does not select a policy. + driver.loaded_matchday_resume = true; +} +} + +// The league structure of the loaded game (schedule.hpp): sizes LeagueSizes (German +// 18 18 18 18 18 12 12 12 12, English 20 20 20 20 10 12 12 12 12) and calendar groups. +static void install_league_sizes(const LeImage& exe) { + uint8_t sizes[kLeagueCount]; + for (int l = 0; l < kLeagueCount; ++l) sizes[l] = exe.u8(::bmh::layout::LeagueSizes + uint32_t(l)); + set_league_sizes(sizes); + install_fixture_tables(exe); + kEnglishCompetitions = sizes[0] == 20; + // the calendar groups (CalendarFirstLeague first league, CalendarLeagueCounts league count per bit) + uint8_t first[8], count[8]; + for (uint32_t b = 0; b < 8; ++b) first[b] = exe.u8(::bmh::layout::CalendarFirstLeague + b), count[b] = exe.u8(::bmh::layout::CalendarLeagueCounts + b); + set_league_groups(first, count); + // the promotion ladder (schedule.hpp) + for (uint32_t l = 0; l < uint32_t(kLeagueCount); ++l) { + kLeagueRelegation[l] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField2 + l); + kLeagueEurope[l] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField + l); + kLeagueSuffix[l] = char(l < 5 ? exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField3 + l * 2) : 0); + } + for (uint32_t g = 0; g < 8; ++g) kGroupBelow[g] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField5 + g), kGroupBelowCount[g] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField4 + g); + kNewcomerFirst = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField); + kNewcomerCount = exe.u16(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField6); + // EXE strings the engine posts (messages.hpp) + kContractEndsSoonText = exe.cstring(kEnglishCompetitions ? ::bmh::layout::EnglishContractExpiryWarningText : ::bmh::layout::ContractExpiryWarningText); + kMastersQualificationText = kEnglishCompetitions ? "Masters entry confirmed. Your participation bonus has been credited." : exe.cstring(::bmh::layout::MastersQualificationText); + kMastersWinnerText = kEnglishCompetitions ? "Masters title won. Your prize money has been credited." : exe.cstring(::bmh::layout::MastersWinnerText); + kIndoorInvitationText = kEnglishCompetitions ? "Indoor event entry bonus credited for " : exe.cstring(::bmh::layout::IndoorInvitationText); + kChampionshipBonusText = kEnglishCompetitions ? "League title bonus credited." : exe.cstring(::bmh::layout::ChampionshipBonusText); + kFriendlyPayerPrefixText = kEnglishCompetitions ? "Your share: " : exe.cstring(::bmh::layout::NationalFriendlyPayerPrefixText); +} + +ModernSession::ModernSession(const std::filesystem::path& data, uint32_t watcom_seed) + : data_directory_(data), exe_(load_le(data / "BMH.exe")), + db_(load_database(data / "M3D.MAN")), + texts_(load_textd(data / "TEXTD.BLK")), + rand_(watcom_seed) { + install_league_sizes(exe_); + turn_driver_.alternate_match_event_roll = exe_.u8(::bmh::layout::AlternateEventRoll) != 0; + turn_driver_.disable_match_events = exe_.u8(::bmh::layout::MatchEventsDisabled) != 0; + turn_driver_.transfer_allocator_context = exe_.u8(::bmh::layout::MatchEventsDisabled) == 0 + ? TransferAllocatorContext::zero : TransferAllocatorContext::blocked; + session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed); + initialize_club_modal_runtime(); + g_ = modern::startup_state(exe_, db_, read_file(data / "M3.MEN"), read_file(data / "M3.DAT")); + if (const auto resource = content::find(data)) { + g_.display_start_year = resource->content->start_year; + content::set_display_start_year(data, g_.display_start_year); + exe_.set_display_start_year(g_.display_start_year); + } + g_.texts = &texts_; + g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText + modern::configure_training_camp_data(g_, exe_); + for (size_t i = 0; i < g_.credit_rate_table.size(); ++i) g_.credit_rate_table[i] = exe_.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i)); + g_.credit_divisor = std::bit_cast(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32); + g_.credit_rate_table_available = true; + install_default_hooks(); + if (content::find(data)) + turn_driver_.desk_autosave = [this](const ModernState &state, WatcomRandom &random) { + write_desk_autosave(state, random); + }; + modern::startup_players(g_, game_, rand_); // CareerFirstSteps2 + MinuteReport report; + if (!modern::new_career_before_dialog(g_, game_, rand_, report)) // InitializeCareer up to the dialog + throw std::runtime_error("career start: " + report.reason); +} + +ModernSession::ModernSession(const std::filesystem::path &data, uint32_t watcom_seed, + const std::filesystem::path &save_path, bool importing_legacy) + : data_directory_(data), exe_(load_le(data / "BMH.exe")), db_(load_database(data / "M3D.MAN")), + texts_(load_textd(data / "TEXTD.BLK")), rand_(watcom_seed) { + install_league_sizes(exe_); + turn_driver_.alternate_match_event_roll = exe_.u8(::bmh::layout::AlternateEventRoll) != 0; + turn_driver_.disable_match_events = exe_.u8(::bmh::layout::MatchEventsDisabled) != 0; + turn_driver_.transfer_allocator_context = exe_.u8(::bmh::layout::MatchEventsDisabled) == 0 + ? TransferAllocatorContext::zero : TransferAllocatorContext::blocked; + session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed); + initialize_club_modal_runtime(); + bool original_english_save = false; + std::optional native; + if (const auto resource = content::find(data); resource && !importing_legacy) { + if (content::key(save_path.extension()) != ".obs") + throw FormatError("0.2 loads native OBS saves; use Add to migrate legacy games"); + native = content::load_career(save_path, *resource->content); + g_ = std::move(native->state); + rand_ = native->random; + game_ = native->game; + } else { + const Savegame file = load_savegame(save_path); + original_english_save = file.version == "V2.20"; + if (!file.checksum_ok || + (file.version != "V2.24" && !(importing_legacy && kEnglishCompetitions && original_english_save))) + throw FormatError("savegame: unsupported or damaged FBM"); + const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField), + exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3), + exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2), + exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)}; + const auto stream = original_english_save ? obw::normalize_english_save(file, counts) : file.stream; + const SaveState save(stream, counts); + const auto manager_count = save.data(::bmh::layout::ManagerCount)[0]; + if (manager_count < 1 || manager_count > 4) + throw FormatError("Invalid legacy manager count"); + if (importing_legacy) { + size_t english_blocks = 0; + for (const auto &[address, size] : kEnglishCompetitionBlocks) + for (const auto &block : save.extension()) + if (block.address == address && block.bytes.size() == size) + ++english_blocks; + if ((kEnglishCompetitions && english_blocks != std::size(kEnglishCompetitionBlocks)) || + (!kEnglishCompetitions && english_blocks != 0)) + throw FormatError( + "Spielstand und Mod-Ausgabe passen nicht zusammen oder englische Pokaldaten fehlen."); + } + g_ = GameState::from_save(save, counts); + if (importing_legacy && file.plain_header.size() >= 11) { + const std::string year(file.plain_header.begin() + 7, file.plain_header.begin() + 11); + if (std::all_of(year.begin(), year.end(), [](unsigned char c) { return std::isdigit(c); })) { + const int elapsed = ui::desk_date(g_.date, exe_).year - exe_.display_start_year(); + const int origin = std::stoi(year) - elapsed; + if (origin >= 1900 && origin <= 9998) + g_.display_start_year = origin; + } + } + } + if (content::find(data)) { + content::set_display_start_year(data, g_.display_start_year); + exe_.set_display_start_year(g_.display_start_year); + } + // CompetitionPointers2, after DeskDate2: these are process statics, not FBM fields. + // Resuming within this month must not count it as a newly elapsed month. + if (!native) { + g_.autosave_months = 0; + g_.autosave_month = modern::month_code(g_.date); + } + // Original CompetitionPointers2 calls CompetitionPointers after loading the stream. This + // rebinds pointer fields in the saved competition table before any resume + // path dereferences them (the serialized values may point into the old process). + modern::competition_pointers(g_.memory, exe_); + g_.texts = &texts_; + g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText + modern::configure_training_camp_data(g_, exe_); + for (size_t i = 0; i < g_.credit_rate_table.size(); ++i) g_.credit_rate_table[i] = exe_.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i)); + g_.credit_divisor = std::bit_cast(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32); + g_.credit_rate_table_available = true; + install_default_hooks(); + if (content::find(data)) + turn_driver_.desk_autosave = [this](const ModernState &state, WatcomRandom &random) { + write_desk_autosave(state, random); + }; + if (!native) + modern::national_coach_after_load( + g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again) + if (!native && g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField)) + game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField))); + if (native) { + content::restore_driver(turn_driver_, native->driver); + restore_native_session_context(native->session); + turn_driver_.session_id = session_id_; + turn_driver_.revision = 1; + exe_.set_display_start_year(g_.display_start_year); + } else if (original_english_save && + !g_.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) { + // V2.20 never stored transient match descriptors. Like its original loader, + // rebuild the current groups without replaying daily/financial progression + // or shuffling the saved manager order. + const int day = g_.season_day(); + if (day < 0 || day >= 365) + throw FormatError("V2.20 calendar day is invalid"); + const auto entry = g_.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(day) * 2); + const auto competitions = g_.memory.u32(::bmh::layout::SavedCompetition); + std::vector referees = db_.raw_referee_properties; + for (auto &referee : referees) + referee &= 0x7f; + MatchdayContext context; + context.month = modern::month_code(g_.date); + context.season_day = day; + context.weekday = ui::desk_date(g_.date, exe_).weekday; + context.referees = &referees; + MinuteReport report; + auto groups = modern::setup_matchday(g_, competitions, context, game_, rand_, report); + if (report.unsupported) + throw FormatError("V2.20 continuation: " + report.reason); + std::string error; + if (!modern::begin_turn_driver(turn_driver_, g_, std::move(groups), entry, db_.raw_referee_properties, + session_id_, 1, error)) + throw FormatError(error); + turn_driver_.referees = std::move(referees); + turn_driver_.loaded_matchday_resume = true; + } else + restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_); + if (importing_legacy && !saved_turn_error_.empty()) + throw FormatError(saved_turn_error_); + if (!native) + capture_source_desk_callargs(); +} + +int ModernSession::runtime_club(int master) const { return runtime_club(g_, master); } + +int ModernSession::runtime_club(const ModernState& state, int master) const { + // ClubsChangePlaces moves a club together with its name: the club whose name offset is the + // master entry's is the one the manager chose + const uint16_t offset = uint16_t(db_.raw_club_name_offsets.at(size_t(master) * 2) | db_.raw_club_name_offsets.at(size_t(master) * 2 + 1) << 8); + for (size_t t = 0; t < state.club_ids.size(); t++) + if (state.club_ids[t] == offset) return int(t); + return -1; +} + +ui::SelectionContext ModernSession::selection_context(uint64_t revision) const { return selection_context_for(g_, revision); } + +ui::SelectionContext ModernSession::selection_context_for(const ModernState& state, uint64_t revision) const { + ui::SelectionContext c; + c.revision = revision; + c.source = "engine"; + for (size_t t = 0; t < state.club_ids.size(); t++) { + int master = int(t); + for (size_t m = 0; m * 2 + 1 < db_.raw_club_name_offsets.size(); m++) + if (uint16_t(db_.raw_club_name_offsets[m * 2] | db_.raw_club_name_offsets[m * 2 + 1] << 8) == state.club_ids[t]) { + master = int(m); + break; + } + c.club_order.push_back(master); + } + return c; +} + +std::vector ModernSession::manager_choices(uint64_t revision) const { + const auto context = selection_context(revision); + std::vector choices; + for (size_t slot = 0; slot < g_.manager_teams.size(); ++slot) { + const int team = g_.manager_teams[slot]; + if (team < 0 || size_t(team) >= context.club_order.size()) throw FormatError("join: invalid existing club"); + ui::ManagerChoice c; + c.slot = int(slot); c.selection_club = team; c.master_club = context.club_order[size_t(team)]; + c.roster_revision = revision; + const size_t at = slot * 0xb0c; + for (size_t i = 0; i < 25 && g_.manager_records.at(at + 0xa8 + i); ++i) + c.name.push_back(char(g_.manager_records[at + 0xa8 + i])); + c.start_league = g_.manager_records.at(at + 0x210); + c.portrait = g_.manager_records.at(at + 0x221); + choices.push_back(std::move(c)); + } + return choices; +} + +bool ModernSession::begin_manager_join(const ui::DeskRequest& origin, const ui::SetupOptions& options, + uint64_t revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + try { + const auto desk = desktop_projection(revision); + const auto& current = desk.options; + if (manager_join_ || origin.kind != ui::DeskRequestKind::open_menu || origin.menu_kind != 29 || + origin.revision != revision || origin.manager_slot != desk.manager_slot || desk.national_team || + revision > std::numeric_limits::max() - 4 || + options.managers < current.managers || options.managers > 4 || + options.difficulty < 0 || options.difficulty > 9 || + (current.difficulty == 0 && options.difficulty != 0) || + options.duration != current.duration || options.mode != current.mode || + options.league != current.league || options.world != current.world) + throw FormatError("join: options or origin no longer match the running career"); + ManagerJoinDraft draft; + draft.state = g_; draft.rand = rand_; draft.game = game_; + draft.options = options; draft.origin = origin; draft.choices = manager_choices(revision); + draft.original_stream = modern::save_stream(g_); draft.original_rand_seed = rand_.seed(); + draft.original_game_seed = game_.seed(); draft.original_rand_calls = rand_.calls(); + draft.original_game_calls = game_.calls(); draft.context_revision = revision; + auto& mem = draft.state.memory; + mem.set8(::bmh::layout::Difficulty, uint8_t(options.difficulty)); draft.state.level = options.difficulty; + mem.set8(::bmh::layout::ManagerCount, uint8_t(options.managers)); + const uint16_t signature = uint16_t(options.mode + options.duration * 4 + options.difficulty * 0x40); + mem.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField7, 2); + mem.set16(::bmh::layout::CareerSession_FormatError_RuntimeField7, mem.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) == signature ? signature : 0); + mem.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); mem.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + if (mem.u32(::bmh::layout::CompetitionSelection) == 1) + for (int slot = current.managers; slot < options.managers; ++slot) + draft.state.manager_options.at(size_t(slot) * 5 + 4) = 1; + modern::career_managers_begin(draft.state, true); + manager_join_ = std::move(draft); + return true; + } catch (const std::exception& e) { error = e.what(); return false; } +} + +ui::SelectionContext ModernSession::manager_join_context() const { + if (!manager_join_) throw FormatError("join: no draft"); + return selection_context_for(manager_join_->state, manager_join_->context_revision); +} + +bool ModernSession::manager_join_complete() const { + return manager_join_ && manager_join_->choices.size() == size_t(manager_join_->options.managers); +} + +bool ModernSession::confirm_manager_join(const ui::ManagerChoice& choice, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (!manager_join_ || manager_join_complete()) { error = "join: no pending manager"; return false; } + auto before = *manager_join_; + try { + auto& draft = *manager_join_; + const auto context = manager_join_context(); + if (choice.slot != int(draft.choices.size()) || choice.roster_revision != context.revision || + choice.name.empty() || choice.name.size() > 24 || choice.name.find('\0') != std::string::npos || + choice.start_league < 0 || choice.start_league > 4 || choice.strength < 0 || choice.strength > 2 || + choice.portrait < 0 || choice.portrait > 11 || choice.selection_club < 0 || + size_t(choice.selection_club) >= context.club_order.size() || + context.club_order[size_t(choice.selection_club)] != choice.master_club || + std::any_of(draft.choices.begin(), draft.choices.end(), [&](const auto& old) { + return old.master_club == choice.master_club || old.portrait == choice.portrait; + })) throw FormatError("join: invalid or stale manager choice"); + CareerManager selected; + selected.name = choice.name; selected.team = runtime_club(draft.state, choice.master_club); + selected.league = choice.start_league; selected.strength = choice.strength; selected.portrait = choice.portrait; + if (selected.team < 0) throw FormatError("join: club not found"); + MinuteReport report; + if (!modern::career_add_manager(draft.state, exe_, choice.slot, selected, true, draft.game, draft.rand, report)) + throw FormatError(report.reason); + draft.choices.push_back(choice); ++draft.context_revision; + return true; + } catch (const std::exception& e) { manager_join_ = std::move(before); error = e.what(); return false; } +} + +bool ModernSession::commit_manager_join(ui::CareerInitializationResult& result, uint64_t& revision, + std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (!manager_join_complete()) { error = "join: selection incomplete"; return false; } + auto before = manager_join_checkpoint(); + const auto previous_revision = revision; + try { + const auto& draft = *manager_join_; + if (draft.origin.revision != revision || modern::save_stream(g_) != draft.original_stream || + rand_.seed() != draft.original_rand_seed || game_.seed() != draft.original_game_seed || + rand_.calls() != draft.original_rand_calls || game_.calls() != draft.original_game_calls) + throw FormatError("join: career changed during selection"); + g_ = draft.state; rand_ = draft.rand; game_ = draft.game; + modern::career_managers_end(g_, true); + managers_.clear(); + for (const auto& c : draft.choices) + managers_.push_back({c.slot, c.master_club, g_.manager_teams.at(size_t(c.slot))}); + // ConfirmManager retains the current desk/cursor. Weiter performs the later handoff. + const auto next_revision = revision + 1; + turn_driver_.revision = next_revision; + ui::CareerInitializationResult next; + next.desktop = desktop_projection(next_revision); next.managers = managers_; + next.preparation = preparation_projection(next_revision); + ui::validate_preparation_context(next.preparation); + result = std::move(next); revision = next_revision; manager_join_.reset(); + return true; + } catch (const std::exception& e) { + restore_manager_join_checkpoint(std::move(before)); revision = previous_revision; + error = e.what(); return false; + } +} + +void ModernSession::apply_options(const ui::SetupOptions& o) { + // SetupScreen2 takes the four numbers over when the options dialog is left + StaticMemory& mem = g_.memory; + mem.set8(::bmh::layout::CareerDuration, uint8_t(o.duration)); + mem.set8(::bmh::layout::Difficulty, uint8_t(o.difficulty)); + g_.level = o.difficulty; // (the typed copy) + mem.set8(::bmh::layout::ManagerCount, uint8_t(o.managers)); + mem.set8(::bmh::layout::GameMode, uint8_t(o.mode)); + mem.set32(::bmh::layout::CompetitionSelection, (o.league ? 1u : 0u) | (o.world ? 2u : 0u)); + // The end of SetupScreen2 at a new game (param_1 = 0, the first manager): + // - a one-manager game flags its manager as Bundestrainer (record +0x21c, CareerSessionRuntimeField2); + // - without the league game every calendar day (CompetitionCalendar, 0x16e words) except the + // World Cup finals (0x4006) loses its low byte and keeps only the international bits + // 0x1e of its high byte; + // - without the World Cup game the international bits go: the high byte keeps 0x61 only. + // So the national team plays (and its manager takes over, SwapManagerSlots2 on 0x1e00 + // days) only when the World Cup mode is on, as the manual says (Handbuch 2, p. 11); + // - the league-only game sets option byte 4 (CareerSessionRuntimeField3) of every manager. + if (managers_.empty() && o.managers == 1 && g_.manager_records.size() >= 0xb0c) + g_.manager_records.at(0x21c) = 1; + if (mem.has(kSavedCalendar + 0x16e * 2 - 1)) + for (uint32_t day = 0; day < 0x16e; ++day) { + const uint32_t at = kSavedCalendar + day * 2; + uint16_t word = mem.u16(at); + if (!o.league && word != 0x4006) word = uint16_t(word & 0x1e00); + if (!o.world) word = uint16_t(word & 0x61ff); + mem.set16(at, word); + } + if (o.league && !o.world) + for (int m = 0; m < o.managers && size_t(m) * 5 + 4 < g_.manager_options.size(); ++m) + g_.manager_options.at(size_t(m) * 5 + 4) = 1; + modern::career_managers_begin(g_); + options_applied_ = true; +} + +bool ModernSession::confirm_manager(const ui::SetupOptions& options, const ui::ManagerChoice& choice, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (!options_applied_) apply_options(options); + const int m = int(managers_.size()); + if (m >= options.managers) { + error = "more managers than chosen in the options"; + return false; + } + CareerManager c; + c.name = choice.name; + c.team = runtime_club(choice.master_club); + c.league = choice.start_league; + c.strength = choice.strength; + c.portrait = choice.portrait; + if (c.team < 0) { + error = "club not found"; + return false; + } + MinuteReport report; + if (!modern::career_add_manager(g_, exe_, m, c, false, game_, rand_, report)) { + error = report.reason; + return false; + } + managers_.push_back({choice.slot, choice.master_club, g_.manager_teams.at(size_t(m))}); + return true; +} + +std::optional ModernSession::enter_club_information(int team, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + try { return modern::prepare_club_info_entry(g_, team); } + catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } +} + +std::optional ModernSession::change_club_information_category(int team, int requested, + std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + try { return modern::set_club_info_category(g_, team, requested); } + catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } +} + +std::optional ModernSession::redraw_club_player_detail( + const ClubPlayerDetailSelection& selection, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + auto next_game = game_; + auto next_rand = rand_; + try { + auto redraw = modern::club_player_detail_redraw(g_, selection, exe_, next_game, next_rand); + game_ = next_game; + rand_ = next_rand; + return redraw; + } catch (const std::invalid_argument& e) { + error = e.what(); + return std::nullopt; + } +} + +std::optional ModernSession::dispatch_club_player_national_action( + const ClubPlayerDetailSelection& selection, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + auto next_state = g_; + auto next_rand = rand_; + MinuteReport report; + try { + const bool applied = modern::club_player_detail_national_action(next_state, selection, next_rand, report); + if (!report.reason.empty()) { error = report.reason; return std::nullopt; } + g_ = std::move(next_state); + rand_ = next_rand; + return applied; // Source still refreshes the lineup when an add finds a full squad. + } catch (const std::invalid_argument& e) { + error = e.what(); + return std::nullopt; + } +} + +std::optional ModernSession::dispatch_club_player_pending_offers( + const ClubPlayerDetailSelection& selection, uint64_t expected_revision, + const PendingOfferHooks& hooks, uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (expected_revision != revision || pending_offer_dispatch_active_ || market_dispatch_active_ || + revision == std::numeric_limits::max()) { + error = "pending offer: stale or nested player-card action"; + return std::nullopt; + } + auto next_state = g_; + auto next_game = game_; + auto next_rand = rand_; + pending_offer_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{pending_offer_dispatch_active_}; + MinuteReport report; + try { + const auto result = modern::process_player_card_pending_offers( + next_state, selection, next_game, next_rand, pending_hooks_for_dispatch(hooks), report); + if (report.unsupported || !result.completed) { + error = report.reason.empty() ? "pending offer: manual decision incomplete" : report.reason; + return std::nullopt; + } + if (result.processed != 0) { + g_ = std::move(next_state); + game_ = next_game; + rand_ = next_rand; + // A nested cup modal belongs to the current calendar transaction; + // its outer driver publishes that revision when advancement returns. + if (!calendar_advance_active_) ++revision; + } + return result; + } catch (const std::exception& e) { + error = e.what(); + return std::nullopt; + } +} + +void ModernSession::initialize_club_modal_runtime() { + // LE object4 has bb cdd/de/e1 in its zero-initialized virtual tail; + // CareerSession_InitializeClubModalRuntime_ExecutableField is file-backed zero. These are explicit process-start values, + // carried by this runtime owner across modal entry/return, not FBM bytes. + for(uint32_t address:{::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableFieldUnsigned,::bmh::layout::CareerSession_DispatchPoachUi_ExecutableFieldUnsigned,::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2Unsigned,::bmh::layout::CareerSession_InitializeClubModalRuntime_ExecutableFieldUnsigned}) + club_modal_runtime_.emplace(address,exe_.u8(address)); +} + +SportschauSourceOptions ModernSession::sportschau_source_options() const { + return {source_runtime_byte(g_, club_modal_runtime_, exe_, ::bmh::layout::CareerSession_SportschauSourceOptions_ExecutableField), + source_runtime_byte(g_, club_modal_runtime_, exe_, ::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2), exe_.u16(::bmh::layout::TeamsWithSquads), + sportschau_rating_tables(exe_)}; +} + +ClubModalServices ModernSession::staged_club_modal_services(ModernState& state, + GameRandom& game,WatcomRandom& rand,std::map& runtime) { + ClubModalServices services; + auto* g=&state; auto* gr=&game; auto* wr=&rand; auto* bytes=&runtime; + services.state=[g]() -> ModernState& { return *g; }; + services.enter_club=[g](int team) { return modern::prepare_club_info_entry(*g,team); }; + services.change_category=[g](int team,int category) { return modern::set_club_info_category(*g,team,category); }; + services.redraw_player=[this,g,gr,wr](const ClubPlayerDetailSelection& selection) { + auto next_game=*gr; auto next_rand=*wr; + auto result=modern::club_player_detail_redraw(*g,selection,exe_,next_game,next_rand); + *gr=next_game; *wr=next_rand; return result; + }; + services.national_action=[g,wr](const ClubPlayerDetailSelection& selection) { + auto next=*g; auto next_rand=*wr; MinuteReport report; + const bool applied=modern::club_player_detail_national_action(next,selection,next_rand,report); + if(!report.reason.empty())throw FormatError(report.reason); + *g=std::move(next); *wr=next_rand; return applied; + }; + services.pending_offers=[this,g,gr,wr](const ClubPlayerDetailSelection& selection,const PendingOfferHooks& hooks) { + auto next=*g; auto next_game=*gr; auto next_rand=*wr; MinuteReport report; + auto result=modern::process_player_card_pending_offers(next,selection,next_game,next_rand, + pending_hooks_for_dispatch(hooks),report); + if(report.unsupported||!result.completed) + throw FormatError(report.reason.empty()?"TeamInfo: nested pending decision incomplete":report.reason); + *g=std::move(next); *gr=next_game; *wr=next_rand; return result; + }; + services.runtime_byte=[this,g,bytes](uint32_t address) { + if(g->memory.has(address))return g->memory.u8(address); + if(const auto at=bytes->find(address);at!=bytes->end())return at->second; + // Explicit original initialization supplies the transient input owner. + // Never serialize an absent BSS byte or infer Native absence as zero. + return exe_.u8(address); + }; + services.set_runtime_byte=[g,bytes](uint32_t address,uint8_t value) { + if(g->memory.has(address))g->memory.set8(address,value); + else (*bytes)[address]=value; + }; + return services; +} + +ClubModalServices ModernSession::live_club_modal_services(uint64_t& revision) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) throw FormatError("strengths_active"); + auto services=staged_club_modal_services(g_,game_,rand_,club_modal_runtime_); + services.transactional=false; + // Existing cup/club caller keeps its separately owned pending transaction. + services.pending_offers=[this,&revision](const ClubPlayerDetailSelection& selection,const PendingOfferHooks& hooks) { + std::string error; + auto result=dispatch_club_player_pending_offers(selection,revision,hooks,revision,error); + if(!result)throw FormatError(error); + return *result; + }; + return services; +} + +namespace { +void pairings_runtime_draw(ModernState& g,std::map& runtime, + const ui::LeaguePairingsState& page,const LeImage& exe) { + const auto put=[&](uint32_t at,uint8_t v) { + if(g.memory.has(at))g.memory.set8(at,v);else runtime[at]=v; + }; + const uint32_t tip_preference=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(page.identity.manager); + const bool computer_tip=page.source.owner.computer_tip_active; + if(computer_tip)put(tip_preference,uint8_t(g.memory.u8(tip_preference)|0x10)); + // Actual5147b entry/input globals; these are process bytes, not invented FBM blocks. + put(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2,uint8_t(page.identity.league));put(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField,page.source.owner.league_group); + put(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField,0);put(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0); + const auto date=[&](uint32_t counter) { + if(counter==0xffff)return; //21258's Wettbewerb-gesperrt branch changes no date scratch. + const auto d=ui::desk_date(counter,exe); + int cycle=3;uint32_t n=counter; + while(n>uint32_t(364+(cycle==4))) {if(cycle==4){cycle=0;--n;}n-=365;++cycle;} + put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField,uint8_t(28+(cycle==4))); + put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField4,uint8_t(d.day));put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField5,uint8_t(d.month));put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField6,uint8_t(d.weekday)); + put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField2,uint8_t(d.year));put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField3,uint8_t(d.year>>8)); + }; + const bool selected_filter=page.source.owner.filter_active&&page.source.owner.filter_team>=0; + if(!selected_filter&&!page.source.owner.postponed_active) + date(page.source.match_date); //333f3 is absent in selected Mode4 and Mode8. + for(const auto& row:page.source.rows) { + if(row.scheduled_date)date(*row.scheduled_date); + else if(row.postponed_date)date(*row.postponed_date); + const uint8_t displayed=row.computer_tip_result.value_or(row.raw_result); + // In local28's referee phase, exact CC rows skip both 68164 calls. + // Preserve prior scratch when every row takes that branch; a mixed + // page leaves the last ordinary away-row value, in Source draw order. + if(page.source.owner.active_phase&&displayed==0xcc)continue; + //68164's final17295 call on the away team leaves Source CareerSession_FormatError_ExecutableField3. + const auto strength=team_average(g,row.away.runtime_team,0x1ff); + put(::bmh::layout::CareerSession_FormatError_ExecutableField3,uint8_t(strength.best_half_sum));put(::bmh::layout::CareerSession_FormatError_ExecutableField4,uint8_t(strength.best_half_sum>>8)); + } + // Move clears its one-redraw local38 bit after the forecast has + // been projected. The returned page retains the pressed Original button. + if(computer_tip)put(tip_preference,uint8_t(g.memory.u8(tip_preference)&0xef)); +} + +bool other_games_source_manager_owned(const ModernState& g,int team) { + if(team<0||!g.memory.has(::bmh::layout::ManagerCount)) + throw FormatError("other games: missing Source manager count for club detail redraw"); + const size_t count=g.memory.u8(::bmh::layout::ManagerCount); + if(count>4||count>g.manager_teams.size()) + throw FormatError("other games: invalid Source manager count for club detail redraw"); + for(size_t manager=0;manager=national_record+2) + return int(uint16_t(g.manager_records[national_record]| + uint16_t(g.manager_records[national_record+1])<<8))==team; + return false; +} + +void other_games_source_redraw_effects(ModernState& g,WatcomRandom& rand, + std::map& runtime,const OtherGamesProjection& projection, + const LeImage& exe) { + const auto put=[&](uint32_t address,uint8_t value) { + if(g.memory.has(address))g.memory.set8(address,value); + else runtime[address]=value; + }; + constexpr std::array source_flags{0x0f1,0x0f2,0x0f4,0x0f8,0x0ff}; + for(const auto& row:projection.rows) { + for(const int team:{row.home_team,row.away_team}) { + // Void6 emits a fixed foreign-strength label without calling QuoteNationalFriendlyMatch + // for a non-manager international club. All other displayed rows make + // five ordered Source average calls; overseas manager clubs use W there. + if(team>=exe.u16(::bmh::layout::NoTeamSquadStart)&& + !other_games_source_manager_owned(g,team))continue; + for(const uint16_t flags:source_flags) { + const auto value=team_average(g,team,flags,&rand); + // QuoteNationalFriendlyMatch resets/updates CareerSession_FormatError_ExecutableField3 only on the squad-backed branch; + // TeamRating's foreign-rating branch leaves the previous scratch intact. + if(team>8)); + } + } + } + } +} + +bool same_other_games_live_baseline(const ModernSession::OtherGamesCheckpoint& before, + const ModernSession::OtherGamesCheckpoint& after) { + if(modern::save_stream(before.state)!=modern::save_stream(after.state)|| + before.game.seed()!=after.game.seed()||before.game.calls()!=after.game.calls()|| + before.rand.seed()!=after.rand.seed()||before.rand.calls()!=after.rand.calls()|| + before.runtime!=after.runtime|| + before.selection.competition!=after.selection.competition|| + before.selection.linked_page!=after.selection.linked_page|| + before.next_scope!=after.next_scope||before.owner.has_value()!=after.owner.has_value()) + return false; + if(!before.owner)return true; + const auto& a=*before.owner;const auto& b=*after.owner; + return a.page.identity==b.page.identity&&a.desk_owner==b.desk_owner&& + a.round==b.round&&a.participant_offset==b.participant_offset&& + a.display_mode==b.display_mode&&a.native==b.native&&a.runtime==b.runtime&& + a.rand_seed==b.rand_seed&&a.game_seed==b.game_seed&& + a.rand_calls==b.rand_calls&&a.game_calls==b.game_calls&& + a.page.source_participant_offset==b.page.source_participant_offset&& + a.page.projection.competition==b.page.projection.competition&& + a.page.projection.entry_index==b.page.projection.entry_index&& + a.page.projection.linked_page==b.page.projection.linked_page&& + a.page.projection.round==b.page.projection.round&& + a.page.projection.display_mode==b.page.projection.display_mode; +} + +bool same_strengths_runtime_state(const ModernState& a,const ModernState& b) { + const auto same_callback=[](const auto& lhs,const auto& rhs) { + return bool(lhs)==bool(rhs)&&(!lhs||lhs.target_type()==rhs.target_type()); + }; + return a.indoor==b.indoor&&a.currency_suffix==b.currency_suffix&&a.level==b.level&& + a.chance_rain==b.chance_rain&&a.chance_temperature==b.chance_temperature&& + a.last_shooter==b.last_shooter&&a.last_pick_quality==b.last_pick_quality&& + a.live_scene==b.live_scene&&a.reality==b.reality&&a.live_matches==b.live_matches&&a.list_toggle==b.list_toggle&& + a.lineups_frozen==b.lineups_frozen&&a.texts==b.texts&&a.date==b.date&& + a.season_start==b.season_start&&a.development_balance==b.development_balance&& + a.trend_rotation==b.trend_rotation&&a.season==b.season&&a.transfer_notice_suppressed==b.transfer_notice_suppressed&& + a.offer_answer==b.offer_answer&&a.pools_open==b.pools_open&&a.autosave_months==b.autosave_months&& + a.autosave_month==b.autosave_month&&same_callback(a.contract_screen,b.contract_screen)&& + same_callback(a.loan_return_screen,b.loan_return_screen)&& + same_callback(a.loan_return_offer_screen,b.loan_return_offer_screen)&& + same_callback(a.transfer_decision,b.transfer_decision)&& + same_callback(a.transfer_offer_selector,b.transfer_offer_selector)&& + same_callback(a.transfer_decision_observer,b.transfer_decision_observer); +} + +int8_t source_byte(int value) { return static_cast(uint8_t(value)); } + +std::string source_table_range_label(const TextDb& texts,int first,int end) { + // DE50860 patches offsets 4/7 of its nine-byte TEXTD82 buffer. EN1e83f + // patches 0/3 of the full " 0-34 only" string instead (the final y is live). + const auto fixed=texts.raw(82,9); + auto raw=kEnglishCompetitions ? texts[82] : std::string(fixed.begin(),fixed.end()); + const size_t start=kEnglishCompetitions ? 0 : 4; + const size_t finish=kEnglishCompetitions ? 3 : 7; + if(raw.size()=int(game.league_rounds.size())) + throw FormatError("league table: missing Source round byte"); + const int8_t raw_end=source_byte(table.end_round); + const int8_t raw_first=source_byte(table.first_round); + const uint8_t raw_round=game.league_rounds[size_t(league)]; + const int max_round=bmh::league_matchdays(league); + if(max_round3||id.league<0||id.league>=bmh::kLeagueCount|| + !game.memory.has(::bmh::layout::ActiveManager)||game.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| + size_t(id.manager)>=game.manager_teams.size()||game.manager_teams[size_t(id.manager)]!=id.runtime_club|| + game.date!=id.day_counter||id.runtime_club<0||size_t(id.runtime_club)>=game.club_ids.size()|| + int(game.club_ids[size_t(id.runtime_club)])!=id.club_identity|| + id.league_group>1) return false; + const size_t record=size_t(id.manager)*0xb0c; + if(record+0x212>game.manager_records.size()|| + id.manager_default_league!=int(game.manager_records[record+0x210])) return false; + const uint32_t settings=::bmh::layout::ManagerSettings+uint32_t(id.manager)*2; + const uint32_t family=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + return game.memory.has(settings+1)&&game.memory.has(family+1)&& + game.memory.u16(settings)==id.expected_settings_word&& + game.memory.u16(family)==id.expected_family_word; +} + +bool canonical_table_envelope(const ui::LeagueFamilyRequest& request,int control_index=-1, + bool allow_selector_league=false) { + return request.target_child==0&&request.runtime_team==-1&&request.expected_club_identity==-1&& + request.table_row_index==-1&&(allow_selector_league||request.league_id==-1)&& + request.control_index==control_index&& + !request.table_dialog_reply; +} + +void source_table_apply_entry_flags(ModernSession::LeagueFamilyOwner::TableOwner& table,uint16_t word) { + if((word&4)==0)table.aggregation_flags=uint8_t(table.aggregation_flags|1); + if((word&2)==0)table.aggregation_flags=uint8_t(table.aggregation_flags|2); +} + +ui::LeagueTableProjectionContext source_table_context( + const ModernSession::LeagueFamilyOwner::TableOwner& table,uint16_t display_word, + std::optional accepted={},bool forecast=false) { + ui::LeagueTableProjectionContext context; + context.first_round=table.first_round;context.end_round=table.end_round; + context.aggregation_flags=table.aggregation_flags;context.normal_mode=table.normal_mode; + context.display_word_override=display_word; + context.retained_range_label_source_bytes=table.retained_range_label_source_bytes; + if(accepted) {context.accepted_engine_league=accepted->league;context.accepted_engine_table=std::move(accepted);} + context.forecast=forecast;return context; +} +} + +std::optional ModernSession::strengths_open_request(uint64_t revision) const { + if(!g_.memory.has(::bmh::layout::ActiveManager))return {}; + const int manager=g_.memory.u8(::bmh::layout::ActiveManager); + if(manager<0||manager>3||size_t(manager)>=g_.manager_teams.size())return {}; + const int club=g_.manager_teams[size_t(manager)]; + const uint32_t setting=::bmh::layout::ManagerSettings+uint32_t(manager)*2,family=::bmh::layout::LeagueTableDisplayModes+uint32_t(manager)*2; + if(club<0||size_t(club)>=g_.club_ids.size()||!g_.memory.has(setting+1)||!g_.memory.has(family+1))return {}; + ui::StrengthsRequest request; + request.identity={manager,club,int(g_.club_ids[size_t(club)]),club>356?0:team_league(club),g_.date, + revision,0,0,g_.memory.u16(setting),g_.memory.u16(family)}; + request.identity.league_group=uint8_t(request.identity.league>=5); + const size_t record=size_t(manager)*0xb0c; + if(record+0x212<=g_.manager_records.size()) + request.identity.manager_default_league=int(g_.manager_records[record+0x210]); + else return {}; + return request; +} + +std::optional ModernSession::begin_league_family( + ui::StrengthsIdentity identity,uint8_t child,uint64_t revision,std::string& error) { + error.clear(); + if(league_family_teaminfo_active_||league_family_owner_||child<1||child>3||revision==UINT64_MAX||identity.revision!=revision|| + (identity.source_param2!=0&&!live_source_identity(identity))||identity.family_id||identity.manager<0||identity.manager>3|| + identity.league<0||identity.league>8||!g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=identity.manager|| + size_t(identity.manager)>=g_.manager_teams.size()||g_.manager_teams[size_t(identity.manager)]!=identity.runtime_club|| + identity.day_counter!=g_.date||identity.runtime_club<0||size_t(identity.runtime_club)>=g_.club_ids.size()|| + int(g_.club_ids[size_t(identity.runtime_club)])!=identity.club_identity||next_league_family_id_==UINT64_MAX) { + error="league family: invalid or nested family entry";return {}; + } + if(child==1&&(strengths_owner_||league_pairings_draft_)) { + error="league family: Table entry has another child owner";return {}; + } + if(child==2&&(!league_pairings_draft_||strengths_owner_|| + league_pairings_draft_->owner.manager!=identity.manager|| + league_pairings_draft_->owner.runtime_club!=identity.runtime_club|| + league_pairings_draft_->owner.club_identity!=identity.club_identity)) { + error="league family: Pairings entry has no matching child owner";return {}; + } + if(child==3&&(!strengths_owner_||strengths_owner_->page.identity.manager!=identity.manager|| + strengths_owner_->page.identity.runtime_club!=identity.runtime_club|| + strengths_owner_->page.identity.revision!=revision)) { + error="league family: Strengths entry has no matching child owner";return {}; + } + identity.family_id=next_league_family_id_++; + if(child==3) { + identity=strengths_owner_->page.identity; + identity.family_id=next_league_family_id_-1; + strengths_owner_->page.identity=identity; + strengths_owner_->native=modern::save_stream(g_); + } + LeagueFamilyOwner owner;owner.identity=identity;owner.child=child;owner.native=modern::save_stream(g_); + owner.rand_seed=rand_.seed();owner.game_seed=game_.seed();owner.rand_calls=rand_.calls(); + owner.game_calls=game_.calls();owner.runtime=club_modal_runtime_; + if(child==1) { + LeagueFamilyOwner::TableOwner table;table.end_round=int(g_.league_rounds.at(size_t(identity.league))); + uint16_t word=uint16_t(g_.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2)&0xff7f); + g_.memory.set16(::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2,word); + identity.expected_family_word=word;owner.identity=identity; + table.display_word_override=word; + source_table_apply_entry_flags(table,word); + table.normal_mode=source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField)&1; + table.runtime_font_id=exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + 1); + source_table_normalize_range(table,g_,identity.league,texts_); + table.page=ui::league_table_from_game(g_,identity.manager,identity.league, + source_table_context(table,table.display_word_override)); + owner.table=std::move(table); + } + owner.identity=identity;owner.native=modern::save_stream(g_);owner.runtime=club_modal_runtime_; + owner.rand_seed=rand_.seed();owner.game_seed=game_.seed();owner.rand_calls=rand_.calls();owner.game_calls=game_.calls(); + league_family_owner_=std::move(owner); + return identity; +} + +std::optional ModernSession::begin_friendly_opponent_table( + uint64_t revision,std::string& error) { + error.clear(); + const auto request=strengths_open_request(revision); + if(!request||request->identity.runtime_club>=modern::first_foreign_cup()||request->identity.source_param2|| + league_family_owner_||strengths_owner_||league_pairings_draft_) { + error="friendly table: unavailable club entry";return {}; + } + const auto checkpoint=league_family_checkpoint(); + try { + auto identity=request->identity; + // Desktop case6 initializes these before its direct FriendlyMatchScreen(2,0). + const uint32_t word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2; + const auto mode=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(identity.league)); + uint16_t word=uint16_t((g_.memory.u16(word_at)&0xfc0f)|0x0170); + if(mode)word|=0x80; + g_.memory.set16(word_at,word); + club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2]=uint8_t(identity.league); + club_modal_runtime_[::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField]=0;identity.league_group=0; + club_modal_runtime_[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=mode;club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField]=0; + club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0; + identity.expected_family_word=word; + const auto bound=begin_league_family(identity,1,revision,error); + if(!bound)throw FormatError(error.empty()?"friendly table: owner entry rejected":error); + league_family_owner_->friendly_opponent=true; + return bound; + } catch(const std::exception& e) { + restore_league_family_checkpoint(checkpoint);error=e.what();return {}; + } +} + +std::optional ModernSession::resolve_friendly_table_opponent( + const ui::LeagueFamilyRequest& request,uint64_t revision,std::string& error) const { + error.clear(); + if(!league_family_owner_||!league_family_owner_->friendly_opponent|| + league_family_owner_->identity!=request.identity||request.identity.revision!=revision|| + request.kind!=ui::LeagueFamilyRequestKind::select_opponent||request.from_child!=1|| + request.target_child||request.control_index!=-1||request.league_id!=-1||request.table_dialog_reply) { + error="friendly table: stale opponent selection";return {}; + } + const auto dispatch=current_league_table_dispatch(error); + if(!dispatch||dispatch->phase!=TableDispatchPhase::ready)return {}; + const auto& table=*league_family_owner_->table; + const int row=request.table_row_index; + if(row<0||size_t(row)>=dispatch->page.rows.size()||size_t(row)>=table.page.rows.size()) { + error="friendly table: opponent row outside the owned page";return {}; + } + const auto& visible=dispatch->page.rows[size_t(row)]; + const auto& normal=table.page.rows[size_t(row)]; + if(visible.runtime_team_id!=request.runtime_team||visible.club_identity_key!=request.expected_club_identity|| + visible.runtime_team_id<0||size_t(visible.runtime_team_id)>=g_.club_ids.size()|| + visible.club_identity_key!=int(g_.club_ids[size_t(visible.runtime_team_id)])|| + normal.rank!=row+1||normal.runtime_team_id<0||normal.runtime_team_id>=modern::first_foreign_cup()|| + size_t(normal.runtime_team_id)>=g_.club_ids.size()|| + normal.club_identity_key!=int(g_.club_ids[size_t(normal.runtime_team_id)])) { + error="friendly table: opponent row identity changed";return {}; + } + // After a forecast Present FriendlyMatchScreen resolves TableRuntimeField6's restored normal ranks. + return normal.runtime_team_id; +} + +std::optional ModernSession::acknowledge_friendly_own_club( + const ui::LeagueFamilyRequest& request,uint64_t revision,std::string& error) { + const auto team=resolve_friendly_table_opponent(request,revision,error); + if(!team||*team!=request.identity.runtime_club||request.identity.family_sequence==UINT64_MAX) { + if(error.empty())error="friendly table: invalid own-club return"; + return {}; + } + auto& owner=*league_family_owner_;auto next=owner.identity; + uint16_t word=uint16_t((next.expected_family_word&0x0f7f)|(owner.table->normal_mode?0x80:0)); + auto state=g_;state.memory.set16(::bmh::layout::LeagueTableDisplayModes+uint32_t(next.manager)*2,word); + auto native=modern::save_stream(state); + ++next.family_sequence;next.expected_family_word=word; + g_=std::move(state);owner.native=std::move(native);owner.identity=next; + // Keep the visible forecast/body and normal ranks: this is the inner loop. + return next; +} + +std::optional ModernSession::finish_friendly_opponent_table( + const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { + error.clear(); + if(!league_family_owner_||!league_family_owner_->friendly_opponent|| + request.identity!=league_family_owner_->identity||request.identity.revision!=revision|| + revision==UINT64_MAX||request.from_child!=1||request.target_child) { + error="friendly table: stale return";return {}; + } + if(request.kind==ui::LeagueFamilyRequestKind::select_opponent) { + const auto team=resolve_friendly_table_opponent(request,revision,error); + if(!team||*team==request.identity.runtime_club) { + if(error.empty())error="friendly table: own club keeps the picker open"; + return {}; + } + } else if(request.kind!=ui::LeagueFamilyRequestKind::close||!canonical_table_envelope(request,-1)) { + error="friendly table: invalid return envelope";return {}; + } + const auto dispatch=current_league_table_dispatch(error); + if(!dispatch||dispatch->phase!=TableDispatchPhase::ready)return {}; + const auto checkpoint=league_family_checkpoint(); + try { + const uint32_t word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(request.identity.manager)*2; + uint16_t word=uint16_t(g_.memory.u16(word_at)&0x0f7f); + if(league_family_owner_->table->normal_mode)word|=0x80; + g_.memory.set16(word_at,word); + auto preparation=preparation_projection(revision+1); + ui::validate_preparation_context(preparation); + ui::DesktopScreen validate(data_directory_,preparation.desktop); + // Direct table return: no LeagueScreenShown family teardown / stir_random. + league_family_owner_.reset();++revision; + return preparation; + } catch(const std::exception& e) { + restore_league_family_checkpoint(checkpoint);error=e.what();return {}; + } +} + +bool ModernSession::advance_league_family(const ui::LeagueFamilyRequest& request, + ui::StrengthsIdentity next,uint8_t target,uint64_t revision,std::string& error) { + error.clear(); + if(league_family_teaminfo_active_||!league_family_owner_||league_family_owner_->friendly_opponent||league_family_owner_->child!=request.from_child|| + league_family_owner_->identity!=request.identity||request.identity.family_id==0|| + request.kind!=ui::LeagueFamilyRequestKind::navigate||target<1||target>3||target!=request.target_child|| + revision1u|| + next.revision!=revision||next.family_id!=request.identity.family_id|| + next.manager!=request.identity.manager||next.runtime_club!=request.identity.runtime_club|| + next.club_identity!=request.identity.club_identity||next.day_counter!=request.identity.day_counter|| + next.source_param2!=request.identity.source_param2||next.manager_default_league!=request.identity.manager_default_league|| + request.identity.family_sequence==UINT64_MAX||next.family_sequence!=request.identity.family_sequence+1|| + next.league<0||next.league>8|| + (request.from_child==1&&league_family_owner_->table&& + league_family_owner_->table->phase!=TableDispatchPhase::ready)) { + error="league family: stale or mismatched child transition";return false; + } + auto owner=*league_family_owner_;owner.identity=next;owner.child=target;owner.native=modern::save_stream(g_); + owner.rand_seed=rand_.seed();owner.game_seed=game_.seed();owner.rand_calls=rand_.calls(); + owner.game_calls=game_.calls();owner.runtime=club_modal_runtime_; + owner.table.reset(); + if(target==1) { + LeagueFamilyOwner::TableOwner table;table.end_round=int(g_.league_rounds.at(size_t(next.league))); + uint16_t word=uint16_t(g_.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(next.manager)*2)&0xff7f); + g_.memory.set16(::bmh::layout::LeagueTableDisplayModes+uint32_t(next.manager)*2,word); + next.expected_family_word=word;owner.identity=next; + table.display_word_override=word; + source_table_apply_entry_flags(table,word); + table.normal_mode=source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField)&1; + table.runtime_font_id=exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + 1); + source_table_normalize_range(table,g_,next.league,texts_); + table.page=ui::league_table_from_game(g_,next.manager,next.league, + source_table_context(table,table.display_word_override)); + owner.table=std::move(table); + } + owner.identity=next;owner.native=modern::save_stream(g_);owner.runtime=club_modal_runtime_; + owner.rand_seed=rand_.seed();owner.game_seed=game_.seed();owner.rand_calls=rand_.calls();owner.game_calls=game_.calls(); + league_family_owner_=std::move(owner);return true; +} + +bool ModernSession::live_source_identity(const ui::StrengthsIdentity& id) const { + return live_overview_owner_ && + live_overview_owner_->kind != LiveOverviewKind::cup_other_games && + live_overview_owner_->request.manager_slot == id.manager && + live_overview_owner_->request.runtime_team == id.runtime_club && + live_overview_owner_->request.minute >= 0 && live_overview_owner_->request.minute <= 255 && + id.source_param2 == uint8_t(live_overview_owner_->request.minute) && + id.day_counter == uint32_t(g_.date) && + (live_overview_owner_->request.group_index == 0 || + (live_overview_owner_->phase_result && phase_result_request_ && + live_overview_owner_->request.group_index == int(phase_result_request_->group_index))); +} + +std::optional ModernSession::close_league_family( + const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { + error.clear();const auto& id=request.identity; + if(league_family_teaminfo_active_||request.kind!=ui::LeagueFamilyRequestKind::close||request.target_child!=0|| + request.from_child<1||request.from_child>3||revision==UINT64_MAX||id.revision!=revision|| + id.manager<0||id.manager>3||!g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| + size_t(id.manager)>=g_.manager_teams.size()||id.runtime_club!=g_.manager_teams[size_t(id.manager)]|| + id.day_counter!=g_.date||id.runtime_club<0||size_t(id.runtime_club)>=g_.club_ids.size()|| + id.club_identity!=int(g_.club_ids[size_t(id.runtime_club)])|| + (id.source_param2!=0&&!live_source_identity(id))|| + !league_family_owner_||league_family_owner_->friendly_opponent||league_family_owner_->child!=request.from_child|| + league_family_owner_->identity!=id|| + strengths_dispatch_active_||league_pairings_dispatch_active_|| + (request.from_child==1&&(strengths_owner_||league_pairings_draft_))|| + (request.from_child==2&&(!league_pairings_draft_||strengths_owner_|| + modern::save_stream(g_)!=league_pairings_draft_->original_stream|| + rand_.seed()!=league_pairings_draft_->original_rand_seed||game_.seed()!=league_pairings_draft_->original_game_seed|| + rand_.calls()!=league_pairings_draft_->original_rand_calls||game_.calls()!=league_pairings_draft_->original_game_calls|| + club_modal_runtime_!=league_pairings_draft_->original_runtime))|| + (request.from_child==3&&(!strengths_owner_||league_pairings_draft_|| + strengths_owner_->page.identity!=id||modern::save_stream(g_)!=strengths_owner_->native|| + rand_.seed()!=strengths_owner_->rand_seed||game_.seed()!=strengths_owner_->game_seed|| + rand_.calls()!=strengths_owner_->rand_calls||game_.calls()!=strengths_owner_->game_calls|| + club_modal_runtime_!=strengths_owner_->runtime))|| + (request.from_child==1&&(modern::save_stream(g_)!=league_family_owner_->native|| + rand_.seed()!=league_family_owner_->rand_seed||game_.seed()!=league_family_owner_->game_seed|| + rand_.calls()!=league_family_owner_->rand_calls||game_.calls()!=league_family_owner_->game_calls|| + club_modal_runtime_!=league_family_owner_->runtime||!league_family_owner_->table|| + league_family_owner_->table->phase!=TableDispatchPhase::ready))) { + error="league family: stale or unavailable final close";return {}; + } + try { + ModernState next_state=g_;GameRandom next_game=game_;WatcomRandom next_rand=rand_; + auto next_runtime=club_modal_runtime_; + auto next_pairings=league_pairings_draft_; + if(request.from_child==2) { + next_state=std::move(next_pairings->state);next_game=next_pairings->game; + next_rand=next_pairings->rand;next_runtime=std::move(next_pairings->runtime); + const uint32_t pairings_word=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(id.manager); + if(!next_state.memory.has(pairings_word))throw FormatError("league family: missing Pairings return word"); + next_state.memory.set8(pairings_word,uint8_t((next_state.memory.u8(pairings_word)&0xf0)|1)); + } + // Phase viewers return to the pending engine ACK, which owns this draw. + // Keyboard/desk family callers still leave through their existing draw. + if(!live_overview_owner_ || !live_overview_owner_->phase_result) + modern::stir_random(next_game,next_rand); + auto preparation=preparation_projection(next_state,revision+1); + ui::validate_preparation_context(preparation); + ui::DesktopScreen validate(data_directory_,preparation.desktop); + g_=std::move(next_state);game_=next_game;rand_=next_rand; + club_modal_runtime_=std::move(next_runtime); + if(request.from_child==2)league_pairings_draft_.reset(); + if(request.from_child==3)strengths_owner_.reset(); + league_family_owner_.reset(); + ++revision;return preparation; + } catch(const std::exception& e) {error=e.what();return {};} +} + +bool ModernSession::suspend_strengths_for_family(const ui::LeagueFamilyRequest& request, + uint64_t revision,std::string& error) { + error.clear();const auto& id=request.identity; + if(league_family_teaminfo_active_||request.kind!=ui::LeagueFamilyRequestKind::navigate||request.from_child!=3|| + (request.target_child!=1&&request.target_child!=2)||!strengths_owner_||strengths_dispatch_active_|| + id.revision!=revision||strengths_owner_->page.identity!=id||modern::save_stream(g_)!=strengths_owner_->native|| + rand_.seed()!=strengths_owner_->rand_seed||rand_.calls()!=strengths_owner_->rand_calls|| + game_.seed()!=strengths_owner_->game_seed||game_.calls()!=strengths_owner_->game_calls|| + !league_family_owner_||league_family_owner_->child!=3||league_family_owner_->identity!=id) { + error="league family: stale Strengths child transition";return false; + } + // A nonzero Reset2 selector returns to LeagueScreenShown without a child close. + strengths_owner_.reset();return true; +} + +bool ModernSession::suspend_pairings_for_family(const ui::LeagueFamilyRequest& request, + uint64_t revision,std::string& error) { + error.clear();const auto& id=request.identity; + if(league_family_teaminfo_active_||request.kind!=ui::LeagueFamilyRequestKind::navigate||request.from_child!=2|| + (request.target_child!=1&&request.target_child!=3)||!league_pairings_draft_|| + league_pairings_dispatch_active_||strengths_owner_||id.revision!=revision|| + id.manager!=league_pairings_draft_->owner.manager|| + id.runtime_club!=league_pairings_draft_->owner.runtime_club|| + id.club_identity!=league_pairings_draft_->owner.club_identity|| + (id.source_param2!=0&&!live_source_identity(id))|| + modern::save_stream(g_)!=league_pairings_draft_->original_stream|| + rand_.seed()!=league_pairings_draft_->original_rand_seed||game_.seed()!=league_pairings_draft_->original_game_seed|| + rand_.calls()!=league_pairings_draft_->original_rand_calls||game_.calls()!=league_pairings_draft_->original_game_calls|| + club_modal_runtime_!=league_pairings_draft_->original_runtime||!league_family_owner_|| + league_family_owner_->child!=2||league_family_owner_->identity!=id) { + error="league family: stale Pairings child transition";return false; + } + // A nonzero Move selector returns to LeagueScreenShown. Commit only its staged + // page/redraw changes; never invoke edit_league_pairings_source(close). + ModernState next_state=std::move(league_pairings_draft_->state); + const uint32_t pairings_word=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(id.manager); + if(!next_state.memory.has(pairings_word)) {error="league family: missing Pairings return word";return false;} + next_state.memory.set8(pairings_word,uint8_t((next_state.memory.u8(pairings_word)&0xf0)|1)); + g_=std::move(next_state);game_=league_pairings_draft_->game; + rand_=league_pairings_draft_->rand;club_modal_runtime_=std::move(league_pairings_draft_->runtime); + league_pairings_draft_.reset();return true; +} + +bool ModernSession::prepare_league_family_child(const ui::StrengthsIdentity& id,uint8_t child, + uint64_t revision,std::string& error) { + error.clear(); + if(league_family_teaminfo_active_||(league_family_owner_&&league_family_owner_->friendly_opponent)||child<1||child>3||revision==UINT64_MAX||id.revision!=revision|| + (id.source_param2!=0&&!live_source_identity(id))|| + id.manager<0||id.manager>3||id.league<0||id.league>8||!g_.memory.has(::bmh::layout::ActiveManager)|| + g_.memory.u8(::bmh::layout::ActiveManager)!=id.manager||size_t(id.manager)>=g_.manager_teams.size()|| + g_.manager_teams[size_t(id.manager)]!=id.runtime_club||g_.date!=id.day_counter|| + id.runtime_club<0||size_t(id.runtime_club)>=g_.club_ids.size()|| + int(g_.club_ids[size_t(id.runtime_club)])!=id.club_identity||strengths_dispatch_active_|| + league_pairings_dispatch_active_||strengths_owner_||league_pairings_draft_) { + error="league family: stale child entry";return false; + } + if((id.family_id==0&&league_family_owner_)|| + (id.family_id!=0&&(!league_family_owner_||league_family_owner_->identity.family_id!=id.family_id|| + league_family_owner_->identity.manager!=id.manager||league_family_owner_->identity.runtime_club!=id.runtime_club|| + league_family_owner_->identity.club_identity!=id.club_identity||league_family_owner_->identity.day_counter!=id.day_counter|| + league_family_owner_->identity.source_param2!=id.source_param2|| + league_family_owner_->identity.family_sequence==UINT64_MAX|| + league_family_owner_->identity.family_sequence+1!=id.family_sequence))) { + error="league family: missing owner binding for child entry";return false; + } + const size_t record=size_t(id.manager)*0xb0c; + if(record+0x212>g_.manager_records.size()||id.manager_default_league!=int(g_.manager_records[record+0x210])) { + error="league family: stale manager default league";return false; + } + const uint32_t word=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + if(!g_.memory.has(word+1)) {error="league family: missing manager mode word";return false;} + g_.memory.set16(word,ui::strengths_family_word_source(g_.memory.u16(word),exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(id.league)))); + club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2]=uint8_t(id.league); + club_modal_runtime_[::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField]=id.league_group; + club_modal_runtime_[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(id.league)); + // Uint8T2's selector is child-specific: Table/Pairings use 0, Strengths 1. + // This is presentation context only; it must not be inferred from the prior page. + club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField]=uint8_t(child==3);club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0; + return true; +} + +void ModernSession::set_phase_results(decltype(TurnDriver::phase_results) hook) { + if (!hook) { turn_driver_.phase_results = {}; return; } + turn_driver_.phase_results = [this, hook=std::move(hook)](const PhaseResultRequest& request, + const std::vector& groups, const ModernState& state) { + if (phase_result_request_ || &groups != &turn_driver_.groups || &state != &g_ || + request.group_index >= groups.size()) + throw FormatError("phase results: invalid synchronous Source boundary"); + phase_result_request_ = &request; + struct Reset { const PhaseResultRequest*& request; ~Reset() { request = nullptr; } } reset{phase_result_request_}; + hook(request, groups, state); + if (live_overview_owner_ && live_overview_owner_->phase_result) + throw FormatError("phase results: viewer must close before the engine ACK"); + }; +} + +std::optional ModernSession::open_phase_results( + uint64_t& revision, const Image& underlay, std::string& error) { + error.clear(); + if (!phase_result_request_ || !calendar_advance_active_ || live_overview_owner_ || + phase_result_request_->group_index >= turn_driver_.groups.size()) { + error = "phase results: no current Source request or viewer already active"; return {}; + } + try { + // Native result arrays and process descriptors share pointers in the + // Original. The Port owns separate vectors; publish their actual scores + // at this viewer boundary, without simulation or random draws. This also + // makes Source search/filter/forecast/TeamInfo read the current results. + ModernState entered = g_; + for (const auto& group : turn_driver_.groups) { + const uint32_t id = le32(group.desc, 0xcc); + if (id < 0x15) { + const size_t at = size_t(id)*0x17c + size_t(entered.league_rounds.at(id))*10; + for (size_t m = 0; m < group.results.size(); ++m) + entered.results.at(at+m) = group.results[m]; + } else modern::store_cup_results(entered, group); + } + const int manager = entered.memory.u8(::bmh::layout::ActiveManager); + if (manager < 0 || size_t(manager) >= entered.manager_teams.size()) + throw FormatError("phase results: unavailable active Source manager"); + LiveOverviewRequest request; + request.key_slot = 1; request.minute = phase_result_request_->phase_end_minute; + request.group_index = int(phase_result_request_->group_index); + request.manager_slot = manager; request.runtime_team = entered.manager_teams[size_t(manager)]; + request.revision = revision; request.sequence = next_live_overview_scope_; + const auto checkpoint = g_; + g_ = std::move(entered); + MatchEngine context{g_, turn_driver_.groups, game_, rand_, turn_driver_.referees}; + auto page = open_running_overview(request, context, revision, underlay, error, true); + if (!page) g_ = checkpoint; + return page; + } catch (const std::exception& e) { error = e.what(); return {}; } +} + +std::optional ModernSession::dispatch_phase_results( + const LiveOverviewAction& action, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info) { + if (!phase_result_request_ || !live_overview_owner_ || !live_overview_owner_->phase_result || + live_overview_owner_->request.group_index != int(phase_result_request_->group_index)) { + error = "phase results: stale or unavailable Source viewer"; return {}; + } + MatchEngine context{g_, turn_driver_.groups, game_, rand_, turn_driver_.referees}; + return dispatch_live_overview(action, context, revision, error, team_info); +} + +std::optional ModernSession::open_live_overview( + const LiveOverviewRequest& request, MatchEngine& engine, uint64_t& revision, + const Image& underlay, std::string& error) { + return open_running_overview(request, engine, revision, underlay, error, false); +} + +std::optional ModernSession::open_running_overview( + const LiveOverviewRequest& request, MatchEngine& engine, uint64_t& revision, + const Image& underlay, std::string& error, bool phase_result) { + error.clear(); + if (!calendar_advance_active_ || live_overview_owner_ || request.key_slot < 0 || request.key_slot > 1 || + request.minute < 0 || request.minute > 255 || request.group_index < 0 || + size_t(request.group_index) >= engine.groups.size() || + (phase_result ? (!phase_result_request_ || request.group_index != int(phase_result_request_->group_index) || + request.minute != phase_result_request_->phase_end_minute || request.key_slot != 1) + : request.group_index != 0) || engine.groups.empty() || + engine.groups.size() != turn_driver_.groups.size() || turn_driver_.groups.empty() || + request.manager_slot < 0 || request.manager_slot >= int(g_.manager_teams.size()) || + request.revision != revision || revision == UINT64_MAX || + next_live_overview_scope_ == UINT64_MAX || &engine.state != &g_ || &engine.game != &game_ || + &engine.rand != &rand_ || !g_.memory.has(::bmh::layout::ActiveManager) || + g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || request.runtime_team < 0 || + size_t(request.runtime_team) >= g_.team_flags.size() || + g_.manager_teams[size_t(request.manager_slot)] != request.runtime_team || + g_.manager_of(request.runtime_team) != request.manager_slot || + engine.groups.front().desc != turn_driver_.groups.front().desc || + engine.groups.front().fixtures != turn_driver_.groups.front().fixtures || + strengths_owner_ || strengths_dispatch_active_ || league_family_owner_ || league_pairings_draft_ || + league_pairings_dispatch_active_ || other_games_owner_ || other_games_dispatch_active_ || + live_intervention_ || balance_draft_ || balance_dispatch_active_ || top_scorers_owner_ || + top_scorers_dispatch_active_ || pending_offer_dispatch_active_ || market_dispatch_active_ || + transfer_offer_editor_ || manager_join_ || contract_quote_ || + stadium_.investment || stadium_.tip || stadium_.periphery_quote || stadium_.block_expansion) { + error = "live overview: stale, nested or unauthenticated Source key request"; + return {}; + } + const MatchGroup& active = engine.groups[size_t(request.group_index)]; + if (active.desc.size() < 0xd0 || active.matches() <= 0 || + (!phase_result && active.void_mask() == ((uint32_t(1) << active.matches()) - 1))) { + error = "live overview: missing active Source match descriptor"; + return {}; + } + + + struct LiveBoundaryFamilyScope { + bool& active; + bool previous; + explicit LiveBoundaryFamilyScope(bool& value) : active(value), previous(value) { active = false; } + ~LiveBoundaryFamilyScope() { active = previous; } + } family_scope(calendar_advance_active_); + const uint64_t next_revision = revision + 1; + const auto family_checkpoint = league_family_checkpoint(); + const auto pairings_checkpoint = league_pairings_checkpoint(); + const auto other_checkpoint = other_games_checkpoint(); + const auto scope_checkpoint = next_live_overview_scope_; + try { + LiveOverviewProjection result; + source_runtime_set_byte(g_,club_modal_runtime_,::bmh::layout::CareerSession_LiveBoundaryFamilyScope_ExecutableField,0); + result.owner = request; + result.owner.revision = next_revision; + result.owner.sequence = next_live_overview_scope_; + const uint32_t competition = le32(active.desc, 0xcc); + LiveOverviewOwner live; + live.phase_result = phase_result; + live.request = result.owner; + live.source_competition = int(competition); + live.original_native = modern::save_stream(g_); + live.original_rand_seed = rand_.seed(); live.original_game_seed = game_.seed(); + live.original_rand_calls = rand_.calls(); live.original_game_calls = game_.calls(); + for (const auto& group : engine.groups) live.active_groups.emplace_back(group.desc, group.fixtures); + live.referees = engine.referees; + live_overview_owner_ = live; + + if (active.desc[0] == 0) { + if (competition > 8) + throw FormatError("live overview: active Source descriptor is not a league"); + result.kind = request.key_slot == 0 ? LiveOverviewKind::league_table : LiveOverviewKind::league_pairings; + auto strengths = strengths_open_request(next_revision); + if (!strengths) throw FormatError("live overview: active manager has no Source league identity"); + strengths->identity.league = int(competition); + strengths->identity.league_group = uint8_t(competition >= 5); + strengths->identity.sequence = next_live_overview_scope_; + strengths->identity.source_param2 = uint8_t(request.minute); + if (request.key_slot == 0) { + auto family = begin_league_family(strengths->identity, 1, next_revision, error); + if (!family) throw FormatError(error.empty() ? "live overview: Source Table family entry rejected" : error); + result.family_identity = *family; + live.family_identity = *family; + auto table = current_league_table_dispatch(error); + if (!table) throw FormatError(error.empty() ? "live overview: Source Table projection unavailable" : error); + result.table = table->page; + } else { + LeaguePairingsDraft draft{g_,game_,rand_,club_modal_runtime_,club_modal_runtime_,{}, {}, + modern::save_stream(g_),rand_.seed(),game_.seed(),rand_.calls(),game_.calls()}; + for (const auto& group : engine.groups) draft.original_active_groups.emplace_back(group.desc,group.fixtures); + draft.original_referee_profiles = engine.referees; + draft.owner = modern::open_league_pairings_source(draft.state,request.manager_slot,ui::league_pairings_constants(exe_)); + if (draft.owner.league != int(competition)) { + draft.owner.league=int(competition); + draft.owner.round=std::min(draft.state.league_rounds.at(size_t(competition)), + league_matchdays(int(competition))-1); + draft.owner.title_round=draft.state.league_rounds.at(size_t(competition)); + if(draft.owner.round>=league_matchdays(int(competition))) + throw FormatError("live overview: Source Pairings round is outside its league schedule"); + } + draft.active_packet = validate_normal_pairings_group(draft.state,draft.owner,draft.runtime); + const uint64_t child_scope = ++league_pairings_scope_; + auto page = ui::league_pairings_from_game(draft.state,draft.owner,exe_,next_revision,child_scope,next_live_overview_scope_,draft.active_packet); + draft.identity = page.identity; + draft.runtime[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField] = exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField + uint32_t(draft.owner.league)); + pairings_runtime_draw(draft.state,draft.runtime,page,exe_); + league_pairings_draft_ = std::move(draft); + auto family = begin_league_family(strengths->identity,2,next_revision,error); + if (!family) throw FormatError(error.empty() ? "live overview: Source Pairings family entry rejected" : error); + result.family_identity = *family; + live.family_identity = *family; + result.pairings = std::move(page); + } + } else { + if (request.key_slot != 0 && request.key_slot != 1) + throw FormatError("live overview: invalid cup overview key slot"); + const int entry_index = modern::cup_entry_index(competition); + // CupGroupOverviewEffects owns this unsaved traversal cursor even in a freshly + // loaded career. Its absence in an FBM is not an invalid cup entry. + if (phase_result && !g_.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField8)) g_.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField8, 1); + if (entry_index < 0 || entry_index >= kCupEntries || !g_.memory.has(modern::cup_entry_address(entry_index)+0x1e) || + !g_.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField8) || !g_.memory.has(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(request.manager_slot))) + throw FormatError("live overview: active cup descriptor is outside the Source linked table"); + // CupGroupOverviewEffects receives the cup-entry ID at entry+18. Match descriptor + // +6 is part of its end-minute pointer, not a competition selector. + const int selector = int16_t(g_.memory.u16(competition + 0x18)); + const uint8_t old_view = g_.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(request.manager_slot)); + if (!phase_result) { + g_.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField3,uint8_t(7-(uint16_t(g_.season)%4))); + g_.memory.set8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(request.manager_slot),uint8_t(old_view|0x80)); + } + // CupGroupOverviewEffects resolves this exact active descriptor through FindCup(selector, ordinal). + const int competition_id = int16_t(g_.memory.u16(modern::cup_entry_address(entry_index)+0x18)); + int stable_team = request.runtime_team; + if (stable_team > 0x164) { + const size_t backup = 4 * 0xb0c + 0x290; + if (request.manager_slot != 0 || backup + 2 > g_.manager_records.size()) + throw FormatError("live overview: unsupported national cup owner"); + stable_team = int(uint16_t(g_.manager_records[backup] | uint16_t(g_.manager_records[backup+1])<<8)); + } + if (stable_team < 0 || stable_team >= modern::league_clubs() || size_t(stable_team) >= g_.club_ids.size()) + throw FormatError("live overview: missing stable cup owner identity"); + ui::OtherGamesIdentity identity; + identity.manager_slot=request.manager_slot; identity.runtime_team=request.runtime_team; + identity.club_identity=int(g_.club_ids[size_t(stable_team)]); identity.day_counter=uint32_t(g_.date); + identity.revision=next_revision; identity.scope=next_live_overview_scope_; identity.sequence=next_live_overview_scope_; + identity.expected_view_byte=g_.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(request.manager_slot)); + std::optional page; + int linked_page=-1; + for(int ordinal=0;ordinalsource_participant_offset=int(g_.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(request.manager_slot))&0x7f); + OtherGamesOwner owner; + owner.page=*page; owner.round=page->projection.round; owner.participant_offset=page->source_participant_offset; + owner.display_mode=page->projection.display_mode; owner.native=modern::save_stream(g_); owner.runtime=club_modal_runtime_; + owner.rand_seed=rand_.seed(); owner.game_seed=game_.seed(); owner.rand_calls=rand_.calls(); owner.game_calls=game_.calls(); + owner.desk_owner.kind=ui::DeskRequestKind::open_menu; owner.desk_owner.menu_kind=5; + owner.desk_owner.manager_slot=request.manager_slot; owner.desk_owner.revision=next_revision; + other_games_owner_=std::move(owner); + other_games_selection_={selector,linked_page}; + result.kind=LiveOverviewKind::cup_other_games; result.cup=std::move(*page); + } + live.kind=result.kind; + live.original_native=modern::save_stream(g_); live.original_rand_seed=rand_.seed(); live.original_game_seed=game_.seed(); + live.original_rand_calls=rand_.calls(); live.original_game_calls=game_.calls(); + live_overview_owner_->kind=live.kind; + live_overview_owner_->family_identity=live.family_identity; + live_overview_owner_->request.revision=next_revision; + ++next_live_overview_scope_; + revision=next_revision; + return result; + } catch(const std::exception& e) { + restore_league_family_checkpoint(family_checkpoint); + restore_league_pairings_checkpoint(pairings_checkpoint); + restore_other_games_checkpoint(other_checkpoint); + live_overview_owner_.reset(); + next_live_overview_scope_=scope_checkpoint; + error=e.what(); + return {}; + } +} + +std::optional ModernSession::current_league_table_dispatch( + std::string& error) const { + error.clear(); + if(!league_family_owner_||league_family_owner_->child!=1||!league_family_owner_->table|| + !source_table_identity_is_live(g_,league_family_owner_->identity)|| + strengths_owner_||league_pairings_draft_) { + error="league table: no active Source family table owner";return {}; + } + try { + const auto& owner=*league_family_owner_;const auto& table=*owner.table; + const uint32_t settings_at=::bmh::layout::ManagerSettings+uint32_t(owner.identity.manager)*2; + const uint32_t family_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(owner.identity.manager)*2; + if(modern::save_stream(g_)!=owner.native||rand_.seed()!=owner.rand_seed||rand_.calls()!=owner.rand_calls|| + game_.seed()!=owner.game_seed||game_.calls()!=owner.game_calls||club_modal_runtime_!=owner.runtime|| + !g_.memory.has(settings_at+1)||!g_.memory.has(family_at+1)|| + g_.memory.u16(settings_at)!=owner.identity.expected_settings_word|| + g_.memory.u16(family_at)!=owner.identity.expected_family_word) { + error="league table: owned Source state changed before projection";return {}; + } + const uint16_t word=table.display_word_override; + LeagueTableDispatch result; + result.identity=owner.identity;result.phase=table.phase; + if(table.phase==TableDispatchPhase::range_start||table.phase==TableDispatchPhase::range_end) { + const int league=owner.identity.league,maximum=bmh::league_matchdays(league); + ui::TableRangeDialogProfile profile; + profile.title_textd_address=table.phase==TableDispatchPhase::range_start?::bmh::layout::CareerSession_CurrentLeagueTableDispatch_ExecutableField: ::bmh::layout::CareerSession_CurrentLeagueTableDispatch_ExecutableField2; + profile.minimum=table.phase==TableDispatchPhase::range_start?1:uint32_t(source_byte(table.pending_start_round)+1); + profile.maximum=uint32_t(maximum); + profile.default_value=table.phase==TableDispatchPhase::range_start?1: + std::max(1,std::min(uint32_t(g_.league_rounds.at(size_t(league))),profile.maximum)); + const bool gradient=source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::TextGradientDisabled)==0&& + table.runtime_font_id==3; + profile.text_mode=gradient?ui::TableRangeTextMode::source_gradient:ui::TableRangeTextMode::flat; + profile.x=table.dialog_x;profile.y=table.dialog_y;result.dialog=profile; + } + result.page=table.forecast_page?*table.forecast_page:table.page; + if(result.page.manager_slot!=owner.identity.manager||result.page.league_id!=owner.identity.league|| + result.page.rows.empty()) + throw FormatError("league table: owned active page is missing or mismatched"); + return result; + } catch(const std::exception& e) {error=e.what();return {};} +} + +std::optional ModernSession::dispatch_league_table_control( + const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { + error.clear();const auto& id=request.identity; + if(league_family_teaminfo_active_||request.kind!=ui::LeagueFamilyRequestKind::control|| + request.from_child!=1||!canonical_table_envelope(request,request.control_index)|| + id.revision!=revision||request.control_index<0||request.control_index>9|| + !source_table_identity_is_live(g_,id)|| + !league_family_owner_||league_family_owner_->child!=1||league_family_owner_->identity!=id|| + !league_family_owner_->table||league_family_owner_->table->phase!=TableDispatchPhase::ready|| + strengths_owner_||league_pairings_draft_|| + (id.source_param2!=0&&!live_source_identity(id))||id.family_sequence==UINT64_MAX||revision==UINT64_MAX|| + modern::save_stream(g_)!=league_family_owner_->native||rand_.seed()!=league_family_owner_->rand_seed|| + rand_.calls()!=league_family_owner_->rand_calls||game_.seed()!=league_family_owner_->game_seed|| + game_.calls()!=league_family_owner_->game_calls||club_modal_runtime_!=league_family_owner_->runtime|| + strengths_owner_||league_pairings_draft_) { + error="league table: stale or unavailable control request";return {}; + } + const auto checkpoint=league_family_checkpoint(); + const uint64_t old_revision=revision; + try { + auto& family=*league_family_owner_;auto& table=*family.table; + const uint32_t word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + if(!g_.memory.has(word_at+1))throw FormatError("league table: manager display word is unavailable"); + uint16_t word=g_.memory.u16(word_at); + const int league=id.league,matchdays=bmh::league_matchdays(league); + const auto update_page=[&](std::optional engine={},bool forecast=false) { + table.display_word_override=word; + const auto context=source_table_context(table,word,std::move(engine),forecast); + table.page=ui::league_table_from_game(g_,id.manager,league,context); + }; + switch(request.control_index) { + case 0: table.aggregation_flags=7;word=uint16_t((word&0x0ff0)|1);break; + case 1: table.aggregation_flags=1;word=uint16_t((word&0x0ff0)|2);break; + case 2: table.aggregation_flags=2;word=uint16_t((word&0x0ff0)|4);break; + case 3: { + if((word&8)==0) { + const int sort_extra=0x0e - int((word>>3)&0x0e); + std::array gap{}; + for(size_t i=0;i ModernSession::dispatch_league_table_range_reply( + const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { + error.clear();const auto& id=request.identity; + if(league_family_teaminfo_active_||request.kind!=ui::LeagueFamilyRequestKind::table_range_result|| + request.from_child!=1||request.target_child!=0||request.control_index!=9|| + request.runtime_team!=-1||request.expected_club_identity!=-1||request.table_row_index!=-1|| + request.league_id!=-1||id.revision!=revision||id.family_sequence==UINT64_MAX||revision==UINT64_MAX|| + !source_table_identity_is_live(g_,id)|| + !request.table_dialog_reply||!league_family_owner_||league_family_owner_->child!=1|| + league_family_owner_->identity!=id||!league_family_owner_->table|| + (league_family_owner_->table->phase!=TableDispatchPhase::range_start&& + league_family_owner_->table->phase!=TableDispatchPhase::range_end)|| + modern::save_stream(g_)!=league_family_owner_->native||rand_.seed()!=league_family_owner_->rand_seed|| + rand_.calls()!=league_family_owner_->rand_calls||game_.seed()!=league_family_owner_->game_seed|| + game_.calls()!=league_family_owner_->game_calls||club_modal_runtime_!=league_family_owner_->runtime) { + error="league table: stale or unavailable range reply";return {}; + } + const auto checkpoint=league_family_checkpoint(); + const uint64_t old_revision=revision; + try { + auto& family=*league_family_owner_;auto& table=*family.table; + const auto& reply=*request.table_dialog_reply; + const auto phase=table.phase; + const auto expected=phase==TableDispatchPhase::range_start?ui::TableDialogStage::start:ui::TableDialogStage::end; + if((reply.outcome!=ui::TableDialogOutcome::accept&&reply.outcome!=ui::TableDialogOutcome::cancel)|| + reply.stage!=expected||reply.x<0||reply.x>207||reply.y<0||reply.y>104) + throw FormatError("league table: wrong dialog stage or Source position"); + const int maximum=bmh::league_matchdays(id.league); + if(reply.outcome==ui::TableDialogOutcome::accept) { + const int minimum=phase==TableDispatchPhase::range_start?1:int(source_byte(table.pending_start_round))+1; + if(reply.valuemaximum) + throw FormatError("league table: accepted range value is outside Source bounds"); + } + table.dialog_x=reply.x;table.dialog_y=reply.y; + uint16_t word=g_.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2); + if(phase==TableDispatchPhase::range_start) { + if(reply.outcome==ui::TableDialogOutcome::accept) { + table.pending_start_round=reply.value-1;table.phase=TableDispatchPhase::range_end; + } else table.phase=TableDispatchPhase::ready; + } else { + if(reply.outcome==ui::TableDialogOutcome::accept) { + table.first_round=table.pending_start_round;table.end_round=reply.value; + } else { + table.first_round=table.previous_start_round;table.end_round=table.previous_end_round; + } + word=uint16_t((word&0x0cff)|0x0200); + source_table_apply_entry_flags(table,word); + source_table_normalize_range(table,g_,id.league,texts_); + table.phase=TableDispatchPhase::ready; + } + if(table.phase==TableDispatchPhase::ready) { + word=uint16_t(word&0x0f7f); + g_.memory.set16(::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2,word); + table.display_word_override=word;table.forecast_page.reset();table.forecast_game_after.reset(); + table.page=ui::league_table_from_game(g_,id.manager,id.league,source_table_context(table,word)); + } + auto next=id;next.revision=revision+1;next.family_sequence=id.family_sequence+1; + next.expected_settings_word=g_.memory.u16(::bmh::layout::ManagerSettings+uint32_t(id.manager)*2); + next.expected_family_word=g_.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2); + family.identity=next;family.native=modern::save_stream(g_);family.rand_seed=rand_.seed(); + family.game_seed=game_.seed();family.rand_calls=rand_.calls();family.game_calls=game_.calls(); + family.runtime=club_modal_runtime_;revision++; + auto result=current_league_table_dispatch(error); + if(!result)throw FormatError(error.empty()?"league table: range projection failed":error); + return result; + } catch(const std::exception& e) {restore_league_family_checkpoint(checkpoint);revision=old_revision;error=e.what();return {};} +} + +std::optional ModernSession::acknowledge_league_forecast_present( + const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { + error.clear();const auto& id=request.identity; + if(league_family_teaminfo_active_||request.kind!=ui::LeagueFamilyRequestKind::table_forecast_presented|| + request.from_child!=1||request.target_child!=0||request.control_index!=3|| + request.runtime_team!=-1||request.expected_club_identity!=-1||request.table_row_index!=-1|| + request.league_id!=-1||request.table_dialog_reply|| + id.revision!=revision||id.family_sequence==UINT64_MAX||revision==UINT64_MAX|| + !source_table_identity_is_live(g_,id)|| + !league_family_owner_||league_family_owner_->child!=1||league_family_owner_->identity!=id|| + !league_family_owner_->table||league_family_owner_->table->phase!=TableDispatchPhase::forecast_pending_present|| + !league_family_owner_->table->forecast_present_pending||!league_family_owner_->table->forecast_game_after|| + modern::save_stream(g_)!=league_family_owner_->native||rand_.seed()!=league_family_owner_->rand_seed|| + rand_.calls()!=league_family_owner_->rand_calls||game_.seed()!=league_family_owner_->game_seed|| + game_.calls()!=league_family_owner_->game_calls||club_modal_runtime_!=league_family_owner_->runtime) { + error="league table: stale or unavailable forecast-present acknowledgement";return {}; + } + const auto checkpoint=league_family_checkpoint(); + const uint64_t old_revision=revision; + try { + auto& family=*league_family_owner_;auto& table=*family.table; + game_=*table.forecast_game_after; + const uint32_t word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + uint16_t word=uint16_t(table.display_word_override&0x0ff7); + g_.memory.set16(word_at,word); + table.display_word_override=word;table.forecast_present_pending=false; + table.forecast_game_after.reset();table.phase=TableDispatchPhase::ready; + const int sort_extra=0x0e - int((word>>3)&0x0e); + const auto normal=bmh::compute_league_table(g_,id.league,0,table.end_round, + table.aggregation_flags,table.normal_mode+sort_extra); + table.page=ui::league_table_from_game(g_,id.manager,id.league, + source_table_context(table,word,normal,false)); + auto next=id;next.revision=revision+1;next.family_sequence=id.family_sequence+1; + next.expected_settings_word=g_.memory.u16(::bmh::layout::ManagerSettings+uint32_t(id.manager)*2); + next.expected_family_word=word; + family.identity=next;family.native=modern::save_stream(g_);family.rand_seed=rand_.seed(); + family.game_seed=game_.seed();family.rand_calls=rand_.calls();family.game_calls=game_.calls(); + family.runtime=club_modal_runtime_;revision++; + auto result=current_league_table_dispatch(error); + if(!result)throw FormatError(error.empty()?"league table: forecast ACK projection failed":error); + return result; + } catch(const std::exception& e) {restore_league_family_checkpoint(checkpoint);revision=old_revision;error=e.what();return {};} +} + +bool ModernSession::select_league_family_page(const ui::LeagueFamilyRequest& request, + uint64_t revision,std::string& error) { + error.clear();const auto& id=request.identity; + const bool map_select=request.kind==ui::LeagueFamilyRequestKind::select_league; + const bool toggle=request.kind==ui::LeagueFamilyRequestKind::toggle_league_group; + if(league_family_teaminfo_active_||(!map_select&&!toggle)||request.from_child!=1|| + !canonical_table_envelope(request,-1,true)||id.revision!=revision||request.league_id<0||request.league_id>8|| + !source_table_identity_is_live(g_,id)||strengths_owner_||league_pairings_draft_|| + !league_family_owner_||league_family_owner_->child!=1||league_family_owner_->identity!=id|| + !league_family_owner_->table||league_family_owner_->table->phase!=TableDispatchPhase::ready|| + modern::save_stream(g_)!=league_family_owner_->native||rand_.seed()!=league_family_owner_->rand_seed|| + rand_.calls()!=league_family_owner_->rand_calls||game_.seed()!=league_family_owner_->game_seed|| + game_.calls()!=league_family_owner_->game_calls||club_modal_runtime_!=league_family_owner_->runtime|| + id.family_sequence==UINT64_MAX) { + error="league family: stale Table league selector";return false; + } + const uint8_t old_group=id.league_group; + const uint8_t next_group=toggle?uint8_t(old_group^1):old_group; + const size_t record=size_t(id.manager)*0xb0c; + const auto checkpoint=league_family_checkpoint(); + try { + if(toggle) { + if(!g_.memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField2)||g_.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2)!=0|| + request.league_id!=(next_group?int(exe_.u8(::bmh::layout::CareerSession_FormatError_RuntimeField4)):int(g_.manager_records[record+0x210]))) + throw FormatError("league family: group toggle target or Source availability is invalid"); + } else { + bool listed=false; + for(int row=0;row<4;++row) { + const int count=exe_.u8(::bmh::layout::CalendarLeagueCounts+uint32_t(old_group*4+row)); + const int first=old_group?int(exe_.u8(::bmh::layout::CareerSession_FormatError_RuntimeField4))+row: + int(exe_.u8(::bmh::layout::CalendarFirstLeague+uint32_t(row))); + if(first+count>int(bmh::kLeagueCount)) + throw FormatError("league family: Source map row exceeds the league table"); + for(int cell=0;cell ModernSession::dispatch_family_table_team_info( + const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error, + const TransferOfferTeamInfoPresenter& presenter, + const std::optional* poach_selection) { + error.clear();const auto& id=request.identity; + if((poach_selection&&!poach_table_selection_)||(league_family_owner_&&league_family_owner_->friendly_opponent)||league_family_teaminfo_active_||!presenter||request.kind!=ui::LeagueFamilyRequestKind::team_info||request.from_child!=1|| + request.target_child!=0||request.control_index!=-1||request.league_id!=-1||request.table_dialog_reply|| + id.revision!=revision||id.family_sequence==UINT64_MAX||!source_table_identity_is_live(g_,id)|| + !league_family_owner_||league_family_owner_->child!=1||league_family_owner_->identity!=id|| + !league_family_owner_->table||league_family_owner_->table->phase!=TableDispatchPhase::ready|| + strengths_owner_||league_pairings_draft_|| + modern::save_stream(g_)!=league_family_owner_->native||rand_.seed()!=league_family_owner_->rand_seed|| + game_.seed()!=league_family_owner_->game_seed||rand_.calls()!=league_family_owner_->rand_calls|| + game_.calls()!=league_family_owner_->game_calls||club_modal_runtime_!=league_family_owner_->runtime|| + revision==UINT64_MAX) { + error="league family: stale Table TeamInfo request";return {}; + } + const auto checkpoint=league_family_checkpoint(); + const uint64_t old_revision=revision; + try { + const auto& table_owner=*league_family_owner_->table; + const ui::LeagueTableState& visible=table_owner.forecast_page?*table_owner.forecast_page:table_owner.page; + if(request.table_row_index<0||size_t(request.table_row_index)>=visible.rows.size()) + throw FormatError("league family: Table TeamInfo row index is outside the visible page"); + const auto& visible_row=visible.rows[size_t(request.table_row_index)]; + if(visible_row.runtime_team_id!=request.runtime_team|| + visible_row.club_identity_key!=request.expected_club_identity|| + request.runtime_team<0||size_t(request.runtime_team)>=g_.club_ids.size()|| + int(g_.club_ids[size_t(request.runtime_team)])!=request.expected_club_identity) + throw FormatError("league family: Table TeamInfo visible row identity is stale"); + if(size_t(request.table_row_index)>=table_owner.page.rows.size()|| + table_owner.page.rows[size_t(request.table_row_index)].rank!=request.table_row_index+1) + throw FormatError("league family: normal working rank is unavailable for Table TeamInfo"); + const auto& selected_row=table_owner.page.rows[size_t(request.table_row_index)]; + const int selected_team=selected_row.runtime_team_id; + if(selected_team<0||size_t(selected_team)>=g_.club_ids.size()|| + selected_row.club_identity_key!=int(g_.club_ids[size_t(selected_team)])) + throw FormatError("league family: normal working rank has a stale club identity"); + const auto& before=checkpoint; + ModernState next=g_;GameRandom next_game=game_;WatcomRandom next_rand=rand_; + auto next_runtime=club_modal_runtime_; + auto tables=ui::league_tables_from_game(g_,id.manager); + if(size_t(id.league)>=tables.size()||visible.manager_slot!=id.manager||visible.league_id!=id.league) + throw FormatError("league family: visible Table backdrop does not match the active owner"); + tables[size_t(id.league)]=visible; + const Image backdrop=ui::LeagueTableScreen(data_directory_,tables,id.league, + ui::LeagueTableScreen::FamilyMode{id,uint8_t(poach_selection!=nullptr)}).render(); + if(poach_selection) { + const uint32_t word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + uint16_t word=uint16_t(next.memory.u16(word_at)&0x0f7f); + if(source_runtime_byte(next,next_runtime,exe_,::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField)!=0)word|=0x80; + next.memory.set16(word_at,word); + } + auto services=staged_club_modal_services(next,next_game,next_rand,next_runtime); + const auto enter=services.enter_club;int entry_calls=0; + services.enter_club=[enter,&entry_calls,selected=selected_team](int team) { + if(team!=selected)throw FormatError("league family: TeamInfo entered a different club"); + ++entry_calls;return enter(team); + }; + league_family_teaminfo_active_=true; + struct Reset { bool& active;~Reset(){active=false;} } reset{league_family_teaminfo_active_}; + const bool accepted=presenter(services,selected_team,backdrop); + const auto after=league_family_checkpoint(); + const bool live_unchanged=same_strengths_runtime_state(before.state,after.state)&& + modern::save_stream(before.state)==modern::save_stream(after.state)&&before.runtime==after.runtime&& + before.game.seed()==after.game.seed()&&before.game.calls()==after.game.calls()&& + before.rand.seed()==after.rand.seed()&&before.rand.calls()==after.rand.calls()&& + before.family==after.family&&before.next_family_id==after.next_family_id&& + before.next_strengths_scope==after.next_strengths_scope&& + !before.strengths&&!after.strengths&&!before.pairings&&!after.pairings; + if(!live_unchanged||!accepted||(poach_selection?entry_calls<1:entry_calls!=1)) + throw FormatError("league family: TeamInfo presenter changed owner or did not enter the selected club"); + const size_t record=size_t(id.manager)*0xb0c; + if(next.date!=g_.date||next.manager_teams!=g_.manager_teams|| + !next.memory.has(::bmh::layout::ActiveManager)||next.memory.u8(::bmh::layout::ActiveManager)!=id.manager||record+0x292>next.manager_records.size()|| + (int(next.manager_records[record+0x290])|int(next.manager_records[record+0x291])<<8)!=id.runtime_club|| + size_t(id.runtime_club)>=next.club_ids.size()||int(next.club_ids[size_t(id.runtime_club)])!=id.club_identity|| + record+0x212>next.manager_records.size()|| + int(next.manager_records[record+0x210])!=id.manager_default_league) + throw FormatError("league family: TeamInfo changed active manager or date"); + auto refreshed=id;refreshed.revision=revision+1;refreshed.family_sequence=id.family_sequence+1; + refreshed.expected_settings_word=next.memory.u16(::bmh::layout::ManagerSettings+uint32_t(id.manager)*2); + const uint32_t family_word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + if(poach_selection && *poach_selection) { + const auto chosen=modern::club_player_detail_context(next,**poach_selection); + if(chosen.selection.runtime_team!=selected_team || chosen.source_slot<0 || + chosen.source_slot>=int(modern::transfer_list_slot()) || chosen.human_loan) + throw FormatError("poach: card returned a different ordinary squad player"); + refreshed.expected_family_word=next.memory.u16(family_word_at); + // A successful param1=1 selection leaves50775 here. Its common + // low80 write survives; there is no next outer Table redraw. + g_=std::move(next);game_=next_game;rand_=next_rand;club_modal_runtime_=std::move(next_runtime); + league_family_owner_->identity=refreshed;league_family_owner_->native=modern::save_stream(g_); + league_family_owner_->rand_seed=rand_.seed();league_family_owner_->game_seed=game_.seed(); + league_family_owner_->rand_calls=rand_.calls();league_family_owner_->game_calls=game_.calls(); + league_family_owner_->runtime=club_modal_runtime_;++revision;return refreshed; + } + const uint16_t drawn_word=uint16_t(next.memory.u16(family_word_at)&0xff7f); + next.memory.set16(family_word_at,drawn_word); + refreshed.expected_family_word=drawn_word; + auto next_table_owner=*league_family_owner_->table; + source_table_apply_entry_flags(next_table_owner,next.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2)); + source_table_normalize_range(next_table_owner,next,refreshed.league,texts_); + next_table_owner.forecast_page.reset();next_table_owner.forecast_game_after.reset(); + next_table_owner.forecast_present_pending=false;next_table_owner.phase=TableDispatchPhase::ready; + next_table_owner.display_word_override=refreshed.expected_family_word; + auto next_tables=ui::league_tables_from_game(next,id.manager); + next_tables[size_t(refreshed.league)]=ui::league_table_from_game(next,id.manager,refreshed.league, + source_table_context(next_table_owner,next_table_owner.display_word_override)); + ui::LeagueTableScreen validate(data_directory_,std::move(next_tables),refreshed.league, + ui::LeagueTableScreen::FamilyMode{refreshed}); + next_table_owner.page=validate.state(); + auto preparation=preparation_projection(next,revision+1); + ui::validate_preparation_context(preparation);ui::DesktopScreen desk(data_directory_,preparation.desktop); + g_=std::move(next);game_=next_game;rand_=next_rand;club_modal_runtime_=std::move(next_runtime); + league_family_owner_->identity=refreshed;league_family_owner_->native=modern::save_stream(g_); + league_family_owner_->table=std::move(next_table_owner); + league_family_owner_->rand_seed=rand_.seed();league_family_owner_->game_seed=game_.seed(); + league_family_owner_->rand_calls=rand_.calls();league_family_owner_->game_calls=game_.calls(); + league_family_owner_->runtime=club_modal_runtime_;++revision;return refreshed; + } catch(const std::exception& e) {restore_league_family_checkpoint(checkpoint);revision=old_revision;error=e.what();return {};} +} + +bool ModernSession::refresh_family_after_child(const ui::StrengthsIdentity& prior,uint8_t child, + ui::StrengthsIdentity next,uint64_t revision,std::string& error) { + error.clear(); + if(league_family_teaminfo_active_||child<1||child>3||!league_family_owner_||league_family_owner_->child!=child|| + league_family_owner_->identity!=prior||prior.family_id==0||next.family_id!=prior.family_id|| + next.family_sequence!=prior.family_sequence||next.revision!=revision||revision1|| + next.manager!=prior.manager||next.runtime_club!=prior.runtime_club||next.club_identity!=prior.club_identity|| + next.day_counter!=prior.day_counter||next.source_param2!=prior.source_param2|| + next.manager_default_league!=prior.manager_default_league||next.league<0||next.league>8|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=next.manager||g_.date!=next.day_counter|| + size_t(next.manager)>=g_.manager_teams.size()||g_.manager_teams[size_t(next.manager)]!=next.runtime_club|| + next.runtime_club<0||size_t(next.runtime_club)>=g_.club_ids.size()|| + int(g_.club_ids[size_t(next.runtime_club)])!=next.club_identity) { + error="league family: child acknowledgement identity is stale";return false; + } + next.expected_settings_word=g_.memory.u16(::bmh::layout::ManagerSettings+uint32_t(next.manager)*2); + next.expected_family_word=g_.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(next.manager)*2); + if(child==3&&(!strengths_owner_||strengths_owner_->page.identity!=next)) { + error="league family: Strengths child acknowledgement lost its owner";return false; + } + if(child==2&&(!league_pairings_draft_||league_pairings_draft_->identity.manager!=next.manager|| + league_pairings_draft_->identity.runtime_club!=next.runtime_club||league_pairings_draft_->identity.league!=next.league)) { + error="league family: Pairings child acknowledgement lost its owner";return false; + } + league_family_owner_->identity=next;league_family_owner_->native=modern::save_stream(g_); + league_family_owner_->rand_seed=rand_.seed();league_family_owner_->game_seed=game_.seed(); + league_family_owner_->rand_calls=rand_.calls();league_family_owner_->game_calls=game_.calls(); + league_family_owner_->runtime=club_modal_runtime_;return true; +} + +std::optional ModernSession::dispatch_strengths( + const ui::StrengthsRequest& request,uint64_t& revision,std::string& error, + const TransferOfferTeamInfoPresenter& team_info,bool family_transition) { + error.clear();const auto& id=request.identity;const bool opening=request.kind==ui::StrengthsAction::open; + if(league_family_teaminfo_active_||strengths_dispatch_active_||revision==UINT64_MAX||id.revision!=revision||id.sequence==UINT64_MAX|| + id.manager<0||id.manager>3||!g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| + size_t(id.manager)>=g_.manager_teams.size()||id.runtime_club!=g_.manager_teams[size_t(id.manager)]|| + id.runtime_club<0||size_t(id.runtime_club)>=g_.club_ids.size()|| + id.club_identity!=int(g_.club_ids[size_t(id.runtime_club)])||id.day_counter!=g_.date|| + id.league<0||id.league>8||career_complete()|| + (turn_driver_.stage!=TurnDriver::Stage::MatchdayDesks&&turn_driver_.stage!=TurnDriver::Stage::SeasonEndDesk)|| + pending_offer_dispatch_active_||market_dispatch_active_||calendar_advance_active_||league_pairings_draft_|| + league_pairings_dispatch_active_||transfer_offer_editor_||manager_join_||contract_quote_|| + stadium_.investment||stadium_.tip||stadium_.periphery_quote||top_scorers_owner_||top_scorers_dispatch_active_ || stadium_.block_expansion||other_games_owner_||other_games_dispatch_active_) { + error="strengths: stale or unavailable owner";return {}; + } + const size_t rec=size_t(id.manager)*0xb0c; + const uint32_t setting=::bmh::layout::ManagerSettings+uint32_t(id.manager)*2,family=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + if(rec+0xb0c>g_.manager_records.size()|| + (int(g_.manager_records[rec+0x290])|int(g_.manager_records[rec+0x291])<<8)!=id.runtime_club|| + !g_.memory.has(setting+1)||!g_.memory.has(family+1)|| + id.expected_settings_word!=g_.memory.u16(setting)||id.expected_family_word!=g_.memory.u16(family)) { + error="strengths: inconsistent manager or saved settings";return {}; + } + if(opening) { + const int initial=id.runtime_club>356?0:team_league(id.runtime_club); + if(strengths_owner_||id.scope||id.sequence||(!family_transition&&id.league!=initial)|| + (family_transition&&((id.source_param2!=0&&!live_source_identity(id))||id.league_group>1||id.manager_default_league<0||id.manager_default_league>8))|| + next_strengths_scope_==UINT64_MAX|| + request.value!=-1||request.control!=ui::StrengthsControl::condition) { + error="strengths: invalid entry";return {}; + } + } else if(!strengths_owner_||id!=strengths_owner_->page.identity|| + modern::save_stream(g_)!=strengths_owner_->native|| + rand_.seed()!=strengths_owner_->rand_seed||rand_.calls()!=strengths_owner_->rand_calls|| + game_.seed()!=strengths_owner_->game_seed||game_.calls()!=strengths_owner_->game_calls) { + error="strengths: stale modal snapshot";return {}; + } + // The process timer's automatic Source event8 belongs to an unported modal + // context. Ordinary desk entry initializes this runtime timer to zero. + const auto byte=[&](uint32_t at) {if(g_.memory.has(at))return g_.memory.u8(at); + const auto found=club_modal_runtime_.find(at);return found==club_modal_runtime_.end()?uint8_t(0):found->second;}; + const uint32_t start=uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2))|uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField3))<<8| + uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField4))<<16|uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField5))<<24; + if(opening&&start!=0&&byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField)<200) { + error="strengths: active process-timer context unsupported";return {}; + } + if(request.kind==ui::StrengthsAction::pairings||request.kind==ui::StrengthsAction::table) { + error="strengths: navigation target not implemented";return {}; + } + if(request.kind==ui::StrengthsAction::team_info&&!team_info) { + error="strengths: TeamInfo presenter unavailable";return {}; + } + strengths_dispatch_active_=true; + struct Reset { bool& active; ~Reset(){active=false;} } reset{strengths_dispatch_active_}; + try { + StrengthsDispatch result; + if(request.kind==ui::StrengthsAction::team_info) { + if(request.control!=ui::StrengthsControl::condition||request.value<0) + throw FormatError("strengths: malformed TeamInfo target"); + // Keep an owned value copy across the external callback; callbacks + // can re-enter the public API and replace/reset modal ownership. + const auto current=strengths_owner_->page; + const auto target=std::find_if(current.projection.rows.begin(),current.projection.rows.end(), + [&](const auto& row){return row.runtime_team==request.value;}); + if(target==current.projection.rows.end()) + throw FormatError("strengths: TeamInfo target is not a visible team"); + + // Reset2 opens ClubInfoFromGame from the selected runtime row and + // resumes this same Strengths loop after the nested modal returns. + // Stage the presenter against the live page, then commit only if it + // did not re-enter or mutate the retained Strengths owner. + ModernState next=g_;GameRandom next_game=game_;WatcomRandom next_rand=rand_; + auto next_runtime=club_modal_runtime_; + const auto live_before=strengths_checkpoint();const auto old_revision=revision; + const auto owner_identity=current.identity; + const auto same_strengths_checkpoint=[&](const StrengthsCheckpoint& before, + const StrengthsCheckpoint& after) { + const bool owner_matches=before.owner.has_value()==after.owner.has_value()&& + (!before.owner||(before.owner->page==after.owner->page&& + before.owner->native==after.owner->native&& + before.owner->rand_seed==after.owner->rand_seed&& + before.owner->game_seed==after.owner->game_seed&& + before.owner->rand_calls==after.owner->rand_calls&& + before.owner->game_calls==after.owner->game_calls)); + return modern::save_stream(before.state)==modern::save_stream(after.state)&& + same_strengths_runtime_state(before.state,after.state)&& + before.game.seed()==after.game.seed()&&before.game.calls()==after.game.calls()&& + before.rand.seed()==after.rand.seed()&&before.rand.calls()==after.rand.calls()&& + before.runtime==after.runtime&&before.next_scope==after.next_scope&&owner_matches&& + before.family==after.family&&before.next_family_id==after.next_family_id; + }; + const Image backdrop=ui::StrengthsScreen(data_directory_,current).render(); + auto services=staged_club_modal_services(next,next_game,next_rand,next_runtime); + const bool accepted=team_info(services,request.value,backdrop); + const auto live_after=strengths_checkpoint(); + if(revision!=old_revision||!same_strengths_checkpoint(live_before,live_after)|| + !live_after.owner||live_after.owner->page.identity!=owner_identity) + throw FormatError("strengths: live owner changed during TeamInfo presenter"); + if(!accepted)throw FormatError("strengths: TeamInfo presenter stopped"); + if(next.date!=g_.date||next.manager_teams!=g_.manager_teams|| + !next.memory.has(::bmh::layout::ActiveManager)||next.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| + next.memory.u16(setting)!=g_.memory.u16(setting)||next.memory.u16(family)!=g_.memory.u16(family)|| + rec+0x292>next.manager_records.size()|| + (int(next.manager_records[rec+0x290])|int(next.manager_records[rec+0x291])<<8)!=id.runtime_club) + throw FormatError("strengths: TeamInfo changed the retained desk or family owner"); + // Reset2 retains local_68 across a nested ClubInfoFromGame and + // redraws the same league. The accepted club-entry injury cleanup + // can change lineup bits, so do not recompute this same-instance cache. + ui::StrengthsProjectionContext context; + context.cached_age=current.projection.age_scratch; + context.retain_validated_owner_age=true; + auto projection=ui::strengths_from_game(next,id.manager,id.league,context); + if(projection.rows.empty())throw FormatError("strengths: empty TeamInfo return projection"); + if(current.projection.age_scratch.league!=id.league|| + current.projection.age_scratch.tenths.size()!=projection.rows.size()) + throw FormatError("strengths: retained TeamInfo age scratch does not match its owner"); + next.memory.set16(setting,projection.words.post_draw_settings_word); + result.page=current; + result.page.identity.revision=revision+1; + result.page.identity.sequence=id.sequence+1; + result.page.identity.expected_settings_word=next.memory.u16(setting); + result.page.identity.expected_family_word=next.memory.u16(family); + result.page.projection=std::move(projection); + ui::StrengthsScreen validate(data_directory_,result.page); + result.preparation=preparation_projection(next,revision+1); + next_runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2]=uint8_t(id.league); + next_runtime[::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField]=uint8_t(current.league_group); + next_runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField]=1;next_runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0; + next_runtime[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(id.league)); + const auto last=team_average(next,result.page.projection.rows.back().runtime_team, + result.page.projection.words.effective_average_flags); + next_runtime[::bmh::layout::CareerSession_FormatError_ExecutableField3]=uint8_t(last.best_half_sum); + next_runtime[::bmh::layout::CareerSession_FormatError_ExecutableField4]=uint8_t(last.best_half_sum>>8); + StrengthsOwner owner{result.page,modern::save_stream(next),next_rand.seed(),next_game.seed(), + next_rand.calls(),next_game.calls(),next_runtime}; + g_=std::move(next);game_=next_game;rand_=next_rand; + club_modal_runtime_=std::move(next_runtime);strengths_owner_=std::move(owner); + ++revision;return result; + } + if(request.kind==ui::StrengthsAction::close) { + if(request.value!=-1||request.control!=ui::StrengthsControl::condition) + throw FormatError("strengths: malformed close"); + result.closed=true;result.page=strengths_owner_->page; + ++result.page.identity.revision;++result.page.identity.sequence; + result.preparation=preparation_projection(g_,revision+1); + strengths_owner_.reset();++revision;return result; + } + ModernState next=g_;auto runtime=club_modal_runtime_;ui::StrengthsProjectionContext context; + int league=id.league,group=opening?(family_transition?id.league_group:0):strengths_owner_->page.league_group; + if(opening)next.memory.set16(family,ui::strengths_family_word_source(next.memory.u16(family),exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(league)))); + else if(request.kind==ui::StrengthsAction::control) { + if(request.value!=-1)throw FormatError("strengths: malformed control"); + const auto word=ui::strengths_control_word_source(id.expected_settings_word,request.control); + if(!word||*word==id.expected_settings_word)throw FormatError("strengths: unavailable or unchanged control"); + next.memory.set16(setting,*word); + if(request.control==ui::StrengthsControl::lineup)context.recompute_age_as=ui::StrengthsAgeBasis::header_toggle_bit15; + else context.cached_age=strengths_owner_->page.projection.age_scratch; + } else if(request.kind==ui::StrengthsAction::select_league) { + if(request.control!=ui::StrengthsControl::condition||request.value<0||request.value>8||request.value==league) + throw FormatError("strengths: invalid league selection"); + league=request.value; + } else if(request.kind==ui::StrengthsAction::toggle_group) { + if(request.value!=-1||request.control!=ui::StrengthsControl::condition||g_.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2)!=0) + throw FormatError("strengths: unavailable group selection"); + group^=1;league=group?int(exe_.u8(::bmh::layout::CareerSession_FormatError_RuntimeField4)):int(g_.manager_records[rec+0x210]); + if(league<0||league>8)throw FormatError("strengths: invalid manager league"); + if(league==id.league)context.cached_age=strengths_owner_->page.projection.age_scratch; + } else if(!opening)throw FormatError("strengths: unknown action"); + auto projection=ui::strengths_from_game(next,id.manager,league,context); + next.memory.set16(setting,projection.words.post_draw_settings_word); + result.page.identity={id.manager,id.runtime_club,id.club_identity,league,id.day_counter,revision+1, + opening?next_strengths_scope_:id.scope,opening?0:id.sequence+1, + next.memory.u16(setting),next.memory.u16(family)}; + result.page.identity.source_param2=id.source_param2; + result.page.identity.league_group=uint8_t(group); + result.page.identity.manager_default_league=id.manager_default_league; + result.page.identity.family_id=id.family_id; + result.page.identity.family_sequence=id.family_sequence; + result.page.projection=std::move(projection);result.page.league_group=group; + result.page.decorated=g_.memory.u8(::bmh::layout::PlainBackground)==0;result.page.original_panel=g_.memory.u8(::bmh::layout::SolidPanelBackground)==0; + result.page.gradient=g_.memory.u8(::bmh::layout::TextGradientDisabled)==0&&exe_.u8(::bmh::layout::TextGradientMode)==2; + result.page.secondary_leagues=g_.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2)==0; + result.page.title=message_text(next,::bmh::layout::CareerSession_FormatError_TextPointer5)+ui::utf8_to_original(result.page.projection.league_name); + const uint8_t raw_round=next.league_rounds.at(size_t(league));const int round=(raw_round&0x7f)+1; + result.page.subtitle=round>league_matchdays(league)?message_text(next,::bmh::layout::CareerSession_FormatError_TextPointer3): + message_text(next,::bmh::layout::CareerSession_FormatError_TextPointer2+uint32_t((raw_round&0x80)!=0)*4)+format_number(next,round,1)+ + exe_.cstring(::bmh::layout::CareerSession_FormatError_TextPointer)+message_text(next,::bmh::layout::CareerSession_FormatError_TextPointer4); + ui::StrengthsScreen validate(data_directory_,result.page); + result.preparation=preparation_projection(next,revision+1); + // Runtime drawing scratch belongs to the session process, not the FBM. + runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2]=uint8_t(league);runtime[::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField]=uint8_t(group);runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField]=1;runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0; + runtime[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(league)); + const auto last=team_average(next,result.page.projection.rows.back().runtime_team,result.page.projection.words.effective_average_flags); + runtime[::bmh::layout::CareerSession_FormatError_ExecutableField3]=uint8_t(last.best_half_sum);runtime[::bmh::layout::CareerSession_FormatError_ExecutableField4]=uint8_t(last.best_half_sum>>8); + StrengthsOwner owner{result.page,modern::save_stream(next),rand_.seed(),game_.seed(),rand_.calls(),game_.calls(),runtime}; + g_=std::move(next);club_modal_runtime_=std::move(runtime);strengths_owner_=std::move(owner); + if(opening)++next_strengths_scope_; + ++revision;return result; + } catch(const std::exception& e) {error=e.what();return {};} +} + +std::optional ModernSession::open_top_scorers( + const ui::DeskRequest& request, uint64_t revision, const Image& underlay, std::string& error) { + error.clear(); + if (top_scorers_dispatch_active_ || top_scorers_owner_ || revision == UINT64_MAX || + next_top_scorers_scope_ == UINT64_MAX || request.kind != ui::DeskRequestKind::open_menu || + request.menu_kind != 20 || request.revision != revision || request.manager_slot < 0 || + request.manager_slot > 3 || !g_.memory.has(::bmh::layout::ActiveManager) || + g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + size_t(request.manager_slot) >= g_.manager_teams.size() || career_complete() || + (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk) || + pending_offer_dispatch_active_ || market_dispatch_active_ || calendar_advance_active_ || + league_pairings_draft_ || league_pairings_dispatch_active_ || strengths_owner_ || + strengths_dispatch_active_ || balance_draft_ || balance_dispatch_active_ || transfer_offer_editor_ || + manager_join_ || contract_quote_ || stadium_.investment || stadium_.tip || stadium_.periphery_quote || stadium_.block_expansion) { + error = "top scorers: stale or unavailable menu-20 owner"; + return {}; + } + const auto source_byte = [&](uint32_t address) { + if (g_.memory.has(address)) return g_.memory.u8(address); + const auto it = club_modal_runtime_.find(address); + return it == club_modal_runtime_.end() ? exe_.u8(address) : it->second; + }; + const uint32_t timer_start=uint32_t(source_byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2))|uint32_t(source_byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField3))<<8| + uint32_t(source_byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField4))<<16|uint32_t(source_byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField5))<<24; + const unsigned timer_duration=source_byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField); + if (timer_start != 0 && timer_duration < 200) { + error = "top scorers: active process-timer context unsupported"; + return {}; + } + try { + const int manager = request.manager_slot; + const int team = g_.manager_teams[size_t(manager)]; + const size_t manager_record = size_t(manager) * 0xb0c; + if (manager_record + 0x292 > g_.manager_records.size() || + uint16_t(g_.manager_records[manager_record + 0x290] | + uint16_t(g_.manager_records[manager_record + 0x291]) << 8) != uint16_t(team)) + throw FormatError("top scorers: manager record does not own the active team"); + int stable_team = team; + if (team == no_team()) { + // The live CupDraw_FormatError_RuntimeField3 owner is mirrored by the typed spare manager record 4. + const size_t backup = 4 * 0xb0c + 0x290; + if (manager != 0 || backup + 2 > g_.manager_records.size()) + throw FormatError("top scorers: unsupported national-coach owner"); + stable_team = int(uint16_t(g_.manager_records[backup] | + uint16_t(g_.manager_records[backup + 1]) << 8)); + } else if (team < 0 || team >= modern::league_clubs()) { + throw FormatError("top scorers: manager team is outside Source league scope"); + } + if (stable_team < 0 || stable_team >= modern::league_clubs() || size_t(stable_team) >= g_.club_ids.size()) + throw FormatError("top scorers: missing stable club identity"); + const int league = team > 0x164 ? 0 : team_league(team); + if (league < 0 || league > 8) + throw FormatError("top scorers: manager has no supported Source league"); + + ui::TopScorersIdentity identity; + identity.manager_slot = manager; + identity.runtime_team = team; + identity.club_identity = int(g_.club_ids[size_t(stable_team)]); + identity.league = league; + identity.day_counter = uint32_t(g_.date); + identity.revision = revision + 1; + identity.scope = next_top_scorers_scope_; + identity.sequence = 0; + auto page = ui::top_scorers_state_from_game(g_, identity, + ui::TopScorersMetric::goals, ui::TopScorersScope::league, underlay); + page.decorated_background = source_byte(::bmh::layout::PlainBackground) == 0; + page.gradient_text = source_byte(::bmh::layout::TextGradientDisabled) == 0 && source_byte(::bmh::layout::TextGradientMode) == 2; + page.cached_backdrop = source_byte(::bmh::layout::CareerSession_ApplyBalanceSourceStyle_ExecutableField) != 0 || source_byte(::bmh::layout::CareerSession_FormatError_ExecutableField5) != 0 || + source_byte(::bmh::layout::CareerSession_FormatError_ExecutableField6) != 0 || source_byte(::bmh::layout::CareerSession_FormatError_ExecutableField7) != 0; + TopScorersOwner owner{page, modern::save_stream(g_), rand_.seed(), game_.seed(), rand_.calls(), game_.calls()}; + top_scorers_owner_ = std::move(owner); + ++next_top_scorers_scope_; + ++revision; + return page; + } catch (const std::exception& e) { + error = e.what(); + return {}; + } +} + +std::optional ModernSession::dispatch_top_scorers( + const ui::TopScorersRequest& request, uint64_t& revision, std::string& error) { + error.clear(); + if (stadium_.block_expansion || top_scorers_dispatch_active_ || !top_scorers_owner_ || revision == UINT64_MAX || + request.identity != top_scorers_owner_->page.identity || request.identity.revision != revision || + request.identity.sequence == UINT64_MAX || request.identity.expected_settings_word != 0 || + request.identity.expected_family_word != 0 || modern::save_stream(g_) != top_scorers_owner_->native || + rand_.seed() != top_scorers_owner_->rand_seed || rand_.calls() != top_scorers_owner_->rand_calls || + game_.seed() != top_scorers_owner_->game_seed || game_.calls() != top_scorers_owner_->game_calls) { + error = "top scorers: stale, replayed or modified owner"; + return {}; + } + top_scorers_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{top_scorers_dispatch_active_}; + try { + TopScorersDispatch result; + const auto& current = top_scorers_owner_->page; + const auto& identity = request.identity; + if (identity.manager_slot < 0 || identity.manager_slot > 3 || + size_t(identity.manager_slot) >= g_.manager_teams.size() || + g_.manager_teams[size_t(identity.manager_slot)] != identity.runtime_team || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != identity.manager_slot || + uint32_t(g_.date) != identity.day_counter || identity.league != current.projection.league) + throw FormatError("top scorers: desk owner changed"); + const size_t manager_record = size_t(identity.manager_slot) * 0xb0c; + if (manager_record + 0x292 > g_.manager_records.size() || + uint16_t(g_.manager_records[manager_record + 0x290] | + uint16_t(g_.manager_records[manager_record + 0x291]) << 8) != + uint16_t(identity.runtime_team)) + throw FormatError("top scorers: manager record changed"); + const size_t backup = 4 * 0xb0c + 0x290; + const int identity_team = identity.runtime_team == no_team() ? + (backup + 2 <= g_.manager_records.size() ? + int(uint16_t(g_.manager_records[backup] | + uint16_t(g_.manager_records[backup + 1]) << 8)) : -1) : identity.runtime_team; + if (identity_team < 0 || identity_team >= modern::league_clubs() || + size_t(identity_team) >= g_.club_ids.size() || + int(g_.club_ids[size_t(identity_team)]) != identity.club_identity) + throw FormatError("top scorers: stable club identity changed"); + + if (request.action == ui::TopScorersAction::open) + throw FormatError("top scorers: open is not a modal action"); + if (request.action == ui::TopScorersAction::close) { + if (request.metric != current.metric || request.scope != current.scope) + throw FormatError("top scorers: malformed close request"); + result.closed = true; + result.page = current; + } else { + ui::TopScorersMetric metric = current.metric; + ui::TopScorersScope scope = current.scope; + if (request.action == ui::TopScorersAction::set_metric) { + const auto next_metric = current.metric == ui::TopScorersMetric::goals ? + ui::TopScorersMetric::assists : current.metric == ui::TopScorersMetric::assists ? + ui::TopScorersMetric::scorer : ui::TopScorersMetric::goals; + if (request.scope != current.scope || request.metric != next_metric) + throw FormatError("top scorers: metric request is not the Source cycle successor"); + metric = request.metric; + } else if (request.action == ui::TopScorersAction::toggle_scope) { + if (request.metric != current.metric || request.scope == current.scope) + throw FormatError("top scorers: invalid scope request"); + scope = request.scope; + } else { + throw FormatError("top scorers: unknown action"); + } + result.page = ui::top_scorers_state_from_game(g_, identity, metric, scope, current.underlay); + result.page.decorated_background = current.decorated_background; + result.page.gradient_text = current.gradient_text; + result.page.cached_backdrop = current.cached_backdrop; + } + result.page.identity.revision = revision + 1; + result.page.identity.sequence = identity.sequence + 1; + result.preparation = preparation_projection(g_, revision + 1); + if (result.closed) top_scorers_owner_.reset(); + else { + top_scorers_owner_->page = result.page; + top_scorers_owner_->native = modern::save_stream(g_); + top_scorers_owner_->rand_seed = rand_.seed(); + top_scorers_owner_->game_seed = game_.seed(); + top_scorers_owner_->rand_calls = rand_.calls(); + top_scorers_owner_->game_calls = game_.calls(); + } + ++revision; + return result; + } catch (const std::exception& e) { + error = e.what(); + return {}; + } +} + +bool ModernSession::apply_statistics_preference(const ui::DeskRequest& owner, int manager_slot, + uint8_t expected_flags, uint8_t target_flags, + uint64_t& revision, std::string& error) { + constexpr uint32_t flags_base = ::bmh::layout::Flags; + if (owner.kind != ui::DeskRequestKind::open_menu || owner.menu_kind != 23 || + owner.manager_slot != manager_slot || manager_slot < 0 || manager_slot >= 4 || + owner.revision != revision || !g_.memory.has(::bmh::layout::ActiveManager) || + g_.memory.u8(::bmh::layout::ActiveManager) != manager_slot || size_t(manager_slot) >= g_.manager_teams.size() || + career_complete() || opportunities_active() || + (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk)) { + error = "statistics: stale menu owner"; + return false; + } + const uint32_t address = flags_base + uint32_t(manager_slot) * 3; + if (!g_.memory.has(address) || g_.memory.u8(address) != expected_flags) { + error = "statistics: stale Source preference"; + return false; + } + const uint8_t delta = uint8_t(expected_flags ^ target_flags); + const bool one_metric = delta != 0 && (delta & uint8_t(delta - 1)) == 0 && delta < 0x40; + const bool absolute_pair = delta == 0xc0; + if ((!one_metric && !absolute_pair) || target_flags != uint8_t(expected_flags ^ delta)) { + error = "statistics: invalid Source preference operation"; + return false; + } + g_.memory.set8(address, target_flags); + error.clear(); + return true; +} + +std::optional ModernSession::open_opportunities( + const ui::DeskRequest& request,uint64_t revision,const Image& underlay,std::string& error, + bool national_source_case,int stable_identity) { + error.clear(); + if(opportunities_dispatch_active_||opportunities_owner_||revision==UINT64_MAX||next_opportunities_scope_==UINT64_MAX|| + request.kind!=ui::DeskRequestKind::open_menu||request.menu_kind!=23||request.revision!=revision|| + request.manager_slot<0||request.manager_slot>3||!g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=request.manager_slot|| + size_t(request.manager_slot)>=g_.manager_teams.size()||career_complete()|| + (turn_driver_.stage!=TurnDriver::Stage::MatchdayDesks&&turn_driver_.stage!=TurnDriver::Stage::SeasonEndDesk)|| + pending_offer_dispatch_active_||market_dispatch_active_||calendar_advance_active_||league_pairings_draft_|| + league_pairings_dispatch_active_||strengths_owner_||strengths_dispatch_active_||top_scorers_owner_|| + top_scorers_dispatch_active_||balance_draft_||balance_dispatch_active_||other_games_owner_||other_games_dispatch_active_|| + transfer_offer_editor_||manager_join_||contract_quote_||stadium_.investment||stadium_.tip||stadium_.periphery_quote|| + stadium_.block_expansion) { error="opportunities: stale or unavailable menu-23 owner"; return {}; } + try { + const int manager=request.manager_slot,team=g_.manager_teams[size_t(manager)]; + const int league=national_source_case?0:team_league(team); + if(national_source_case) { + if(team!=no_team()||league!=0)throw FormatError("opportunities: invalid national menu-6 owner"); + if(stable_identity<0)throw FormatError("opportunities: missing national Desk identity"); + } else if(team<0||team>=modern::league_clubs()||size_t(team)>=g_.club_ids.size()||league<0||league>=9) + throw FormatError("opportunities: unsupported team/league"); + if(underlay.width!=320||underlay.height!=240)throw FormatError("opportunities: expected captured 320x240 desktop"); + const uint32_t choice_at=::bmh::layout::CareerSession_FormatError_ExecutableField+uint32_t(manager)*2; + if(!g_.memory.has(choice_at+1))throw FormatError("opportunities: Source choice word missing"); + uint16_t mode=g_.memory.u16(choice_at);if(mode==0){mode=1;g_.memory.set16(choice_at,mode);} + if(mode!=1&&mode!=2&&mode!=4&&mode!=8)throw FormatError("opportunities: invalid stored Source mode"); + ui::OpportunitiesState page;page.identity={manager,team,national_source_case?stable_identity:int(g_.club_ids[size_t(team)]),uint32_t(g_.date),revision+1,next_opportunities_scope_,0}; + page.mode=mode;page.league_size=kLeagueSizes[league];page.underlay=underlay; + page.gradient_text=g_.memory.has(::bmh::layout::TextGradientDisabled)&&g_.memory.u8(::bmh::layout::TextGradientDisabled)==0&&g_.memory.has(::bmh::layout::TextGradientMode)&&g_.memory.u8(::bmh::layout::TextGradientMode)==2; + page.current_rank=national_source_case?national_opportunities_rank(g_,team,page.ranks):table_prediction(g_,team,mode,page.ranks,nullptr); + opportunities_owner_=OpportunitiesOwner{page,modern::save_stream(g_),game_,rand_,national_source_case};++next_opportunities_scope_; + return page; + } catch(const std::exception& e){error=e.what();return {};} +} + +std::optional ModernSession::dispatch_opportunities( + const ui::OpportunitiesRequest& request,uint64_t& revision,std::string& error) { + error.clear(); + if(opportunities_dispatch_active_||!opportunities_owner_||revision==UINT64_MAX|| + request.identity!=opportunities_owner_->page.identity||request.identity.revision!=revision|| + request.identity.sequence==UINT64_MAX||modern::save_stream(g_)!=opportunities_owner_->native|| + game_.seed()!=opportunities_owner_->game.seed()||game_.calls()!=opportunities_owner_->game.calls()|| + rand_.seed()!=opportunities_owner_->rand.seed()||rand_.calls()!=opportunities_owner_->rand.calls()) { + error="opportunities: stale, replayed or modified owner";return {}; + } + opportunities_dispatch_active_=true;struct Reset{bool& active;~Reset(){active=false;}} reset{opportunities_dispatch_active_}; + try { + const auto current=opportunities_owner_->page; // Value snapshot across all validation. + const bool national_source_case=opportunities_owner_->national_source_case; + if(current.identity.manager_slot<0||current.identity.manager_slot>3|| + size_t(current.identity.manager_slot)>=g_.manager_teams.size()|| + g_.manager_teams[size_t(current.identity.manager_slot)]!=current.identity.runtime_team|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=current.identity.manager_slot|| + uint32_t(g_.date)!=current.identity.day_counter|| + size_t(current.identity.runtime_team)>=g_.club_ids.size()|| + (!national_source_case&&int(g_.club_ids[size_t(current.identity.runtime_team)])!=current.identity.stable_club_identity)|| + (national_source_case&&(current.identity.runtime_team!=no_team()|| + current.identity.stable_club_identity<0))) + throw FormatError("opportunities: desk owner changed"); + OpportunitiesDispatch result;result.page=current; + if(request.action==ui::OpportunitiesAction::close){ + if(request.mode!=current.mode)throw FormatError("opportunities: malformed close"); + result.closed=true; + } else if(request.action==ui::OpportunitiesAction::select_mode){ + if(request.mode!=1&&request.mode!=2&&request.mode!=4&&request.mode!=8) + throw FormatError("opportunities: unsupported Source mode"); + const uint32_t choice_at=::bmh::layout::CareerSession_FormatError_ExecutableField+uint32_t(current.identity.manager_slot)*2; + if(!g_.memory.has(choice_at+1))throw FormatError("opportunities: Source choice word missing"); + g_.memory.set16(choice_at,uint16_t(request.mode)); + result.page.mode=request.mode; + result.page.current_rank=national_source_case? + national_opportunities_rank(g_,current.identity.runtime_team,result.page.ranks): + modern::table_prediction(g_,current.identity.runtime_team,request.mode,result.page.ranks,nullptr); + } else throw FormatError("opportunities: unknown action"); + result.page.identity.revision=revision+1;result.page.identity.sequence=request.identity.sequence+1; + result.preparation=preparation_projection(g_,revision+1); + if(result.closed)opportunities_owner_.reset(); + else opportunities_owner_=OpportunitiesOwner{result.page,modern::save_stream(g_),game_,rand_,national_source_case}; + ++revision;return result; + } catch(const std::exception& e){error=e.what();return {};} +} + +std::optional ModernSession::open_other_games( + const ui::DeskRequest& request, uint64_t& revision, const Image& underlay, std::string& error) { + error.clear(); + if (other_games_dispatch_active_ || other_games_owner_ || revision == UINT64_MAX || + next_other_games_scope_ == UINT64_MAX || request.kind != ui::DeskRequestKind::open_menu || + request.menu_kind != 5 || request.revision != revision || request.manager_slot < 0 || + request.manager_slot > 3 || !g_.memory.has(::bmh::layout::ActiveManager) || + g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + size_t(request.manager_slot) >= g_.manager_teams.size() || career_complete() || + (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk) || + pending_offer_dispatch_active_ || market_dispatch_active_ || calendar_advance_active_ || + league_pairings_draft_ || league_pairings_dispatch_active_ || strengths_owner_ || + strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || other_games_owner_ || other_games_dispatch_active_ || + balance_draft_ || balance_dispatch_active_ || transfer_offer_editor_ || manager_join_ || + contract_quote_ || stadium_.investment || stadium_.tip || stadium_.periphery_quote || stadium_.block_expansion) { + error = "other games: stale or unavailable menu-5 owner"; + return {}; + } + try { + if (!g_.memory.has(::bmh::layout::ActiveSelectors + 7) || !g_.memory.has(::bmh::layout::ActiveManager) || + !g_.memory.has(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(request.manager_slot)) || !g_.memory.has(::bmh::layout::FriendlyPlanCount)) + throw FormatError("other games: missing Source overview state"); + + ModernState next = g_; + // CupGroupOverviewEffects's exact entry transaction. CareerSession_FormatError_RuntimeField3 aliases selector slot four, so its + // season write precedes the first-hit selector-12 insertion/removal. + next.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField3, uint8_t(7 - (uint16_t(next.season) % 4))); + int active = next.memory.u8(::bmh::layout::ActiveManager); + if (active > 3) { + active = 0; + next.memory.set8(::bmh::layout::ActiveManager, 0); + } + next.memory.set8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(active), 0x80); + if (next.memory.u8(::bmh::layout::FriendlyPlanCount) == 0) { + modern::end_competition(next.memory, 12); + } else { + for (uint32_t i = 0; i < 8; ++i) { + const uint8_t id = next.memory.u8(::bmh::layout::ActiveSelectors + i); + if (id == 12) break; + if (id == 0x14) { next.memory.set8(::bmh::layout::ActiveSelectors + i, 12); break; } + } + } + + const int manager = active; + if (size_t(manager) >= next.manager_teams.size()) + throw FormatError("other games: active manager slot is outside typed manager list"); + const int team = next.manager_teams[size_t(manager)]; + const size_t record = size_t(manager) * 0xb0c; + if (record + 0x292 > next.manager_records.size() || team < 0 || team >= 0x190 || + uint16_t(next.manager_records[record + 0x290] | + uint16_t(next.manager_records[record + 0x291]) << 8) != uint16_t(team)) + throw FormatError("other games: manager record does not own the active team"); + int stable_team = team; + if (team > 0x164) { + const size_t backup = 4 * 0xb0c + 0x290; + if (manager != 0 || backup + 2 > next.manager_records.size()) + throw FormatError("other games: unsupported national-coach owner"); + stable_team = int(uint16_t(next.manager_records[backup] | + uint16_t(next.manager_records[backup + 1]) << 8)); + } + if (stable_team < 0 || stable_team >= modern::league_clubs() || size_t(stable_team) >= next.club_ids.size()) + throw FormatError("other games: missing stable manager club identity"); + + const uint8_t source_view = next.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(manager)); + const OtherGamesDisplayMode mode = (source_view & 0x80) + ? OtherGamesDisplayMode::detail : OtherGamesDisplayMode::compact; + const int local_cursor = source_view & 0x7f; + if (local_cursor % 16 != 0) + throw FormatError("other games: malformed Source local page cursor"); + ui::OtherGamesIdentity identity; + identity.manager_slot = manager; + identity.runtime_team = team; + identity.club_identity = int(next.club_ids[size_t(stable_team)]); + identity.day_counter = uint32_t(next.date); + identity.revision = revision + 1; + identity.scope = next_other_games_scope_; + identity.sequence = 0; + identity.expected_view_byte = source_view; + + auto page = ui::other_games_state_from_game(next,identity,texts_,exe_, + other_games_selection_.competition,other_games_selection_.linked_page,-1,mode, + local_cursor,true,underlay,club_modal_runtime_); + if (page.projection.display_mode != mode) { + // Source forces local20=detail on redraw if this round cannot use the toggle. + if (page.projection.source_participant_count <= 16 && mode != OtherGamesDisplayMode::detail) { + next.memory.set8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(manager),uint8_t(source_view | 0x80)); + identity.expected_view_byte = uint8_t(source_view | 0x80); + page.identity = identity; + } else { + throw FormatError("other games: malformed Source local page cursor"); + } + } + page.source_participant_offset = local_cursor; + OtherGamesOwner owner; + owner.page = page; + owner.desk_owner = request; + owner.round = page.projection.round; + owner.participant_offset = local_cursor; + owner.display_mode = page.projection.display_mode; + owner.native = modern::save_stream(next); + owner.runtime = club_modal_runtime_; + owner.rand_seed = rand_.seed(); owner.game_seed = game_.seed(); + owner.rand_calls = rand_.calls(); owner.game_calls = game_.calls(); + g_ = std::move(next); + other_games_owner_ = std::move(owner); + ++next_other_games_scope_; + ++revision; + return page; + } catch (const std::exception& e) { + error = e.what(); + return {}; + } +} + +std::optional ModernSession::dispatch_other_games( + const ui::OtherGamesRequest& request, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info) { + error.clear(); + if (stadium_.block_expansion || other_games_dispatch_active_ || !other_games_owner_ || revision == UINT64_MAX || + request.identity != other_games_owner_->page.identity || request.identity.revision != revision || + request.identity.sequence == UINT64_MAX || modern::save_stream(g_) != other_games_owner_->native || + club_modal_runtime_ != other_games_owner_->runtime || rand_.seed() != other_games_owner_->rand_seed || + rand_.calls() != other_games_owner_->rand_calls || game_.seed() != other_games_owner_->game_seed || + game_.calls() != other_games_owner_->game_calls) { + error = "other games: stale, replayed or modified owner"; + return {}; + } + other_games_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{other_games_dispatch_active_}; + try { + // Keep value snapshots across any external presenter call. The presenter + // may capture this ModernSession and invoke another public action while + // the modal dispatch is active. + const auto current = other_games_owner_->page; + const auto id = request.identity; + const auto desk = other_games_owner_->desk_owner; + const int owned_round=other_games_owner_->round; + const int owned_participant_offset=other_games_owner_->participant_offset; + const auto owned_display_mode=other_games_owner_->display_mode; + if (id.manager_slot != desk.manager_slot || id.manager_slot < 0 || id.manager_slot > 3 || + size_t(id.manager_slot) >= g_.manager_teams.size() || + g_.manager_teams[size_t(id.manager_slot)] != id.runtime_team || + g_.memory.u8(::bmh::layout::ActiveManager) != id.manager_slot || uint32_t(g_.date) != id.day_counter || + g_.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(id.manager_slot)) != id.expected_view_byte) + throw FormatError("other games: desk owner or view byte changed"); + const size_t rec = size_t(id.manager_slot) * 0xb0c; + if (rec + 0x292 > g_.manager_records.size() || + uint16_t(g_.manager_records[rec + 0x290] | uint16_t(g_.manager_records[rec + 0x291]) << 8) != + uint16_t(id.runtime_team)) + throw FormatError("other games: manager record changed"); + int stable_team = id.runtime_team; + if (id.runtime_team > 0x164) { + const size_t backup = 4 * 0xb0c + 0x290; + if (id.manager_slot != 0 || backup + 2 > g_.manager_records.size()) + throw FormatError("other games: unsupported national owner"); + stable_team = int(uint16_t(g_.manager_records[backup] | uint16_t(g_.manager_records[backup + 1]) << 8)); + } + if (stable_team < 0 || stable_team >= modern::league_clubs() || size_t(stable_team) >= g_.club_ids.size() || + int(g_.club_ids[size_t(stable_team)]) != id.club_identity) + throw FormatError("other games: stable club identity changed"); + if (request.action == ui::OtherGamesAction::team_info) { + if (request.value < 0 || current.projection.unfinished_predecessor || + !current.projection.fixtures_available) + throw FormatError("other games: invalid team-information target"); + bool target_visible = false; + for (const auto& row:current.projection.rows) { + target_visible |= row.home_team==request.value||row.away_team==request.value; + } + if (!target_visible) throw FormatError("other games: team-information target is not visible"); + if (!team_info) throw FormatError("other games: TeamInfo presenter unavailable"); + + ModernState next=g_; + GameRandom next_game=game_; + WatcomRandom next_rand=rand_; + auto next_runtime=club_modal_runtime_; + // Source CupGroupOverviewEffects passes the accepted Other Games drawing as the + // immediate parent's backdrop. The presenter's mutations are staged + // with the same Native, W and process-runtime owners. + const Image backdrop=ui::OtherGamesScreen(data_directory_,current).render(); + auto services=staged_club_modal_services(next,next_game,next_rand,next_runtime); + const auto live_baseline=other_games_checkpoint(); + const auto revision_baseline=revision; + const bool presenter_accepted=team_info(services,request.value,backdrop); + + // Validate the live session before consulting the owner again or + // committing staged presenter changes. A captured callback that + // mutated Native, either RNG, runtime, selection, scope or owner is + // rejected; Controller restores its pre-dispatch checkpoint. + if(revision!=revision_baseline|| + !same_other_games_live_baseline(live_baseline,other_games_checkpoint())) + throw FormatError("other games: live session changed during TeamInfo presenter"); + if(!presenter_accepted) + throw FormatError("other games: TeamInfo presenter stopped"); + if(!other_games_owner_||other_games_owner_->page.identity!=id|| + ui::OtherGamesScreen(data_directory_,other_games_owner_->page).render().pixels!=backdrop.pixels) + throw FormatError("other games: live page changed during TeamInfo presenter"); + + if(next.date!=g_.date||next.manager_teams!=g_.manager_teams|| + next.memory.u8(::bmh::layout::ActiveManager)!=id.manager_slot|| + next.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(id.manager_slot))!=id.expected_view_byte) + throw FormatError("other games: TeamInfo changed its outer desk or saved page owner"); + const size_t active_record=size_t(id.manager_slot)*0xb0c; + if(active_record+0x292>next.manager_records.size()|| + uint16_t(next.manager_records[active_record+0x290]| + uint16_t(next.manager_records[active_record+0x291])<<8)!=uint16_t(id.runtime_team)) + throw FormatError("other games: TeamInfo changed the active manager record"); + const int retained_team=id.runtime_team>0x164 + ? int(uint16_t(next.manager_records[4*0xb0c+0x290]| + uint16_t(next.manager_records[4*0xb0c+0x291])<<8)) : id.runtime_team; + if(retained_team<0||retained_team>=modern::league_clubs()||size_t(retained_team)>=next.club_ids.size()|| + int(next.club_ids[size_t(retained_team)])!=id.club_identity) + throw FormatError("other games: TeamInfo changed the stable desk club identity"); + + // LAB_000226dc clears the input event, then local_50 skips the + // entry-only stage/cursor/round setup and redraws the retained view. + const auto put_runtime=[&](uint32_t address,uint8_t value) { + if(next.memory.has(address))next.memory.set8(address,value); + else next_runtime[address]=value; + }; + put_runtime(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0); + ui::OtherGamesIdentity returned_id=id; + returned_id.revision=revision+1; + returned_id.sequence=id.sequence+1; + auto page=ui::other_games_state_from_game(next,returned_id,texts_,exe_, + current.projection.competition,current.projection.linked_page, + owned_round,owned_display_mode, + owned_participant_offset,false,current.underlay,next_runtime); + if(page.projection.competition!=current.projection.competition|| + page.projection.entry_index!=current.projection.entry_index|| + page.projection.descriptor_competition!=current.projection.descriptor_competition|| + page.projection.linked_page!=current.projection.linked_page|| + page.projection.round!=current.projection.round) + throw FormatError("other games: TeamInfo return changed the retained Source selection"); + if(page.projection.source_participant_count<=16) { + const uint32_t view_at=::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(id.manager_slot); + const uint8_t before_view=next.memory.has(view_at) + ?next.memory.u8(view_at):id.expected_view_byte; + const uint8_t forced=uint8_t(before_view|0x80); + put_runtime(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField+uint32_t(id.manager_slot),forced); + returned_id.expected_view_byte=forced; + page=ui::other_games_state_from_game(next,returned_id,texts_,exe_, + current.projection.competition,current.projection.linked_page, + owned_round,OtherGamesDisplayMode::detail, + owned_participant_offset,false,current.underlay,next_runtime); + } + page.source_participant_offset=owned_participant_offset; + other_games_source_redraw_effects(next,next_rand,next_runtime,page.projection,exe_); + OtherGamesDispatch result; + result.page=std::move(page); + result.preparation=preparation_projection(next,revision+1); + ui::OtherGamesScreen validate_page(data_directory_,result.page); + ui::DesktopScreen validate_desktop(data_directory_,result.preparation.desktop); + + // Commit only after the nested presenter and both return projections + // have succeeded. The modal scope stays owned; only its action token + // advances, matching StartupFlow's full-identity ACK. + g_=std::move(next);game_=next_game;rand_=next_rand; + club_modal_runtime_=std::move(next_runtime); + other_games_owner_->page=result.page; + other_games_owner_->round=result.page.projection.round; + other_games_owner_->participant_offset=result.page.source_participant_offset; + other_games_owner_->display_mode=result.page.projection.display_mode; + other_games_owner_->native=modern::save_stream(g_); + other_games_owner_->runtime=club_modal_runtime_; + other_games_owner_->rand_seed=rand_.seed();other_games_owner_->game_seed=game_.seed(); + other_games_owner_->rand_calls=rand_.calls();other_games_owner_->game_calls=game_.calls(); + ++revision; + return result; + } + + OtherGamesDispatch result; + if (request.action == ui::OtherGamesAction::close) { + if (request.value != -1) throw FormatError("other games: malformed close request"); + result.closed = true; + result.page = current; + } else { + ModernState next = g_; + const int manager = id.manager_slot; + const uint32_t view_at = ::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(manager); + uint8_t view = next.memory.u8(view_at); + int competition = other_games_selection_.competition; + int linked_page = other_games_selection_.linked_page; + int round = other_games_owner_->round; + int local_cursor = other_games_owner_->participant_offset; + auto mode = other_games_owner_->display_mode; + bool source_new_selection = false; + switch (request.action) { + case ui::OtherGamesAction::select_competition: { + if (current.projection.display_mode != OtherGamesDisplayMode::detail || request.value < 0 || + request.value >= int(current.projection.selectors.size())) + throw FormatError("other games: invalid selector slot"); + const auto& selector = current.projection.selectors[size_t(request.value)]; + if (!selector.active) throw FormatError("other games: inactive selector slot"); + const int old_competition=competition; + if (old_competition == selector.competition && + current.projection.source_participant_count > 16) { + local_cursor += 16; + if (local_cursor >= current.projection.source_participant_count) local_cursor = 0; + const uint8_t updated = uint8_t((view & 0x80) | (local_cursor & 0x7f)); + next.memory.set8(view_at,updated); + view = updated; + } else { + // CupGroupOverviewEffects compares the selected ID with the clicked SLOT before it + // stores the selector ID. These are intentionally different values. + if (old_competition != request.value) { + local_cursor = 0; + linked_page = 0; + const uint8_t updated = uint8_t(view & 0x80); + next.memory.set8(view_at,updated); + view = updated; + } + competition = selector.competition; + local_cursor = int(view & 0x7f); + round = -1; + source_new_selection = old_competition != competition; + } + break; + } + case ui::OtherGamesAction::select_linked_page: + if (current.projection.display_mode != OtherGamesDisplayMode::detail || request.value < 0 || + request.value >= int(current.projection.linked_pages.size()) || + current.projection.linked_pages[size_t(request.value)].ordinal != request.value) + throw FormatError("other games: invalid linked-page ordinal"); + linked_page = request.value; + round = -1; + local_cursor = int(view & 0x7f); + break; + case ui::OtherGamesAction::previous_round: + case ui::OtherGamesAction::next_round: + if (request.value != -1 || !current.projection.round_arrows_visible) + throw FormatError("other games: invalid round action"); + round = request.action == ui::OtherGamesAction::previous_round + ? (round + current.projection.rounds - 1) % current.projection.rounds + : (round + 1) % current.projection.rounds; + local_cursor = 0; + break; + case ui::OtherGamesAction::toggle_display_mode: + if (request.value != -1 || !current.projection.display_mode_toggle_available || + current.projection.unfinished_predecessor || !current.projection.fixtures_available) + throw FormatError("other games: display toggle is unavailable"); + view ^= 0x80; + next.memory.set8(view_at,view); + mode = (view & 0x80) ? OtherGamesDisplayMode::detail : OtherGamesDisplayMode::compact; + break; + case ui::OtherGamesAction::team_info: + case ui::OtherGamesAction::close: + throw FormatError("other games: malformed action"); + default: + throw FormatError("other games: unknown action"); + } + if (current.projection.source_participant_count <= 16) { + const uint8_t updated = uint8_t(view | 0x80); + if (updated != view) next.memory.set8(view_at,updated); + view = updated; mode = OtherGamesDisplayMode::detail; + } + ui::OtherGamesIdentity next_id = id; + next_id.revision = revision + 1; + next_id.sequence = id.sequence + 1; + next_id.expected_view_byte = view; + auto page = ui::other_games_state_from_game(next,next_id,texts_,exe_,competition,linked_page, + round,mode,local_cursor,source_new_selection,current.underlay,club_modal_runtime_); + if (page.projection.source_participant_count <= 16 && mode != OtherGamesDisplayMode::detail) { + const uint8_t updated = uint8_t(view | 0x80); + next.memory.set8(view_at,updated); + next_id.expected_view_byte = updated; + page.identity = next_id; + mode = OtherGamesDisplayMode::detail; + } + page.source_participant_offset = local_cursor; + result.page = std::move(page); + result.preparation = preparation_projection(next,revision+1); + g_ = std::move(next); + other_games_selection_ = {competition,linked_page}; + other_games_owner_->page = result.page; + other_games_owner_->round = result.page.projection.round; + other_games_owner_->participant_offset = local_cursor; + other_games_owner_->display_mode = mode; + other_games_owner_->native = modern::save_stream(g_); + other_games_owner_->runtime = club_modal_runtime_; + other_games_owner_->rand_seed = rand_.seed(); other_games_owner_->game_seed = game_.seed(); + other_games_owner_->rand_calls = rand_.calls(); other_games_owner_->game_calls = game_.calls(); + } + if (result.closed) { + result.page.identity.revision = revision + 1; + result.page.identity.sequence = id.sequence + 1; + result.preparation = preparation_projection(g_,revision+1); + other_games_owner_.reset(); + } + ++revision; + return result; + } catch (const std::exception& e) { + error = e.what(); + return {}; + } +} + +std::optional ModernSession::open_balance_plan( + const ui::DeskRequest& request,uint64_t revision,const Image& underlay,std::string& error) { + error.clear(); + if(request.kind!=ui::DeskRequestKind::open_menu||request.menu_kind!=28||request.revision!=revision|| + revision==UINT64_MAX||balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_|| + top_scorers_owner_||top_scorers_dispatch_active_ || stadium_.block_expansion||other_games_owner_||other_games_dispatch_active_|| + league_pairings_draft_||league_pairings_dispatch_active_||market_dispatch_active_||pending_offer_dispatch_active_|| + calendar_advance_active_||transfer_offer_editor_||manager_join_||request.manager_slot<0||request.manager_slot>=4|| + size_t(request.manager_slot)>=g_.manager_teams.size()||!g_.memory.has(::bmh::layout::ActiveManager)|| + g_.memory.u8(::bmh::layout::ActiveManager)!=request.manager_slot) { + error="balance: stale, nested or unsupported opening";return {}; + } + try { + const int slot=request.manager_slot, runtime_club=g_.manager_teams[size_t(slot)]; + if(runtime_club<0||size_t(runtime_club)>=g_.club_ids.size()||g_.date>UINT32_MAX||next_balance_scope_==UINT64_MAX) + throw FormatError("balance: invalid manager identity"); + BalanceDraft next{g_,game_,rand_,club_modal_runtime_,club_modal_runtime_,{},modern::save_stream(g_), + rand_.seed(),game_.seed(),rand_.calls(),game_.calls(),false}; + next.notice_gate={source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CompactDialogFrame), + source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField2), + source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField)}; + ModernState opening=g_; + if(!opening.memory.has(::bmh::layout::PlanTicketPrice))opening.memory.add_block(::bmh::layout::PlanTicketPrice,4); + for(int i=0;i<4;++i)opening.memory.set8(::bmh::layout::PlanTicketPrice+uint32_t(i), + source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::PlanTicketPrice+uint32_t(i))); + auto draft=modern::open_balance_plan(opening,slot); + if(!g_.memory.has(::bmh::layout::PlanTicketPrice+uint32_t(slot))) + next.runtime[::bmh::layout::PlanTicketPrice+uint32_t(slot)]=uint8_t(draft.rows[kBalanceTicketPrice]); + ui::BalanceIdentity id{slot,runtime_club,int(g_.club_ids[size_t(runtime_club)]),uint32_t(g_.date),revision,next_balance_scope_,0}; + next.page=ui::balance_from_game(g_,draft,exe_,id,underlay); + apply_balance_source_style(next.page,g_,club_modal_runtime_,exe_); + next.page.read_only_notice_enabled=next.notice_gate.enabled(); + next.page.read_only_notice.compact_dialog_frame=next.notice_gate.compact_dialog_frame!=0; + next.page.close_notice.compact_dialog_frame=next.notice_gate.compact_dialog_frame!=0; + ui::BalanceScreen validate(data_directory_,next.page); + auto accepted_page=next.page; + auto accepted_runtime=next.runtime; + next.original_runtime=accepted_runtime; + balance_draft_=std::move(next); + club_modal_runtime_=std::move(accepted_runtime); + ++next_balance_scope_; + return accepted_page; + } catch(const std::exception& e) {error=e.what();return {};} +} + +std::optional ModernSession::dispatch_balance_plan( + const ui::BalanceRequest& request,uint64_t& revision,std::string& error) { + error.clear(); + if(stadium_.block_expansion||balance_dispatch_active_||!balance_draft_||request.identity!=balance_draft_->page.identity|| + request.identity.revision!=revision||request.identity.sequence==UINT64_MAX||revision==UINT64_MAX|| + modern::save_stream(g_)!=balance_draft_->original_stream||rand_.seed()!=balance_draft_->original_rand_seed|| + game_.seed()!=balance_draft_->original_game_seed||rand_.calls()!=balance_draft_->original_rand_calls|| + game_.calls()!=balance_draft_->original_game_calls||club_modal_runtime_!=balance_draft_->original_runtime) { + error="balance: stale or nested owner action";return {}; + } + auto next=*balance_draft_; + balance_dispatch_active_=true;struct Reset {bool& x;~Reset(){x=false;}} reset{balance_dispatch_active_}; + try { + auto& identity=next.page.identity; + const int manager=identity.manager_slot; + if(manager<0||manager>=4||size_t(manager)>=g_.manager_teams.size()|| + g_.manager_teams[size_t(manager)]!=identity.runtime_club|| + int(g_.club_ids[size_t(identity.runtime_club)])!=identity.club_identity||g_.date!=identity.day_counter|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=manager) + throw FormatError("balance: manager identity changed"); + BalanceDispatch result; + if(request.kind==ui::BalanceAction::confirm_close) { + if(!next.page.pending_close||!next.warning)throw FormatError("balance: no staged warning close"); + if(request.row!=-1||request.value)throw FormatError("balance: malformed confirmation"); + const auto before=identity;identity.revision=revision+1;identity.sequence=before.sequence+1; + next.page.pending_close=false;next.page.close_notice={}; + result.closed=true;result.page=next.page; + result.preparation=preparation_projection(next.state,revision+1); + ui::validate_preparation_context(result.preparation); + ui::DesktopScreen validate(data_directory_,result.preparation.desktop); + g_=std::move(next.state);game_=next.game;rand_=next.rand;club_modal_runtime_=std::move(next.runtime); + balance_draft_.reset();++revision; + return result; + } + if(next.page.pending_close)throw FormatError("balance: warning confirmation is pending"); + auto draft=next.page.draft; + switch(request.kind) { + case ui::BalanceAction::edit_row: { + if(request.row<0||request.row>=kBalanceRows)throw FormatError("balance: invalid row"); + const auto status=modern::edit_balance_plan(next.state,draft,request.row,request.value); + if(status!=BalanceEditStatus::changed)throw FormatError("balance: edit rejected"); + break; + } + case ui::BalanceAction::cycle_view: + if(request.row!=-1||request.value)throw FormatError("balance: malformed view action"); + modern::cycle_balance_view(next.state,draft);break; + case ui::BalanceAction::take_actuals: + if(request.row!=-1||request.value)throw FormatError("balance: malformed reset action"); + modern::reset_balance_plan(next.state,draft);break; + case ui::BalanceAction::close: { + if(request.row!=-1||request.value)throw FormatError("balance: malformed close action"); + const auto original_identity=identity; + ModernState closing=next.state; + if(!closing.memory.has(::bmh::layout::PlanTicketPrice))closing.memory.add_block(::bmh::layout::PlanTicketPrice,4); + for(int i=0;i<4;++i)closing.memory.set8(::bmh::layout::PlanTicketPrice+uint32_t(i), + source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::PlanTicketPrice+uint32_t(i))); + const bool dfb_warning=modern::close_balance_plan(closing,draft); + next.state.manager_records=std::move(closing.manager_records); + const uint32_t ticket_address=::bmh::layout::PlanTicketPrice+uint32_t(manager); + if(next.state.memory.has(ticket_address))next.state.memory.set8(ticket_address,closing.memory.u8(ticket_address)); + else next.runtime[ticket_address]=closing.memory.u8(ticket_address); + next.notice_gate={source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::CompactDialogFrame), + source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField2), + source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField)}; + next.warning=dfb_warning&&next.notice_gate.enabled(); + next.page.pending_close=next.warning; + next.page.close_notice=next.warning?next.page.close_notice:ui::TaxDialogProjection{}; + next.page.draft=draft; + next.page.identity.sequence=original_identity.sequence+1; + if(next.warning) { + auto& notice=next.page.close_notice; + notice.kind=ui::TaxDialogKind::acknowledgement; + notice.source_manager_flags=uint8_t(manager)|0x40; + notice.compact_dialog_frame=next.notice_gate.compact_dialog_frame!=0; + notice.body=message_text(next.state,::bmh::layout::BalancePlan_BalanceFromGame_TextPointer2); + const size_t record=size_t(manager)*0xb0c; + if(record+0x223>next.state.manager_records.size())throw FormatError("balance: missing manager display identity"); + const size_t name_at=record+0xa8;size_t name_end=name_at; + while(name_end(next.state.manager_records.data()+name_at),name_end-name_at); + notice.portrait=next.state.manager_records[record+0x221]; + const int club=next.state.manager_teams[size_t(manager)]; + notice.badge_fallback=club==0x0fff||(club>=modern::german_clubs()&&club=modern::first_foreign_cup()&&club=0&&size_t(club)*2+2<=next.state.club_heap_78.size()) + notice.badge_sprite=(int(next.state.club_heap_78[size_t(club)*2])| + int(next.state.club_heap_78[size_t(club)*2+1])<<8)&0x1ff; + else notice.badge_fallback=true; + result.warning=true;result.page=next.page;balance_draft_=std::move(next);return result; + } + next.page.pending_close=false; + next.page.identity.revision=revision+1; + next.page.identity.sequence=original_identity.sequence+1; + result.closed=true;result.page=next.page; + result.preparation=preparation_projection(next.state,revision+1); + ui::validate_preparation_context(result.preparation); + ui::DesktopScreen validate(data_directory_,result.preparation.desktop); + g_=std::move(next.state);game_=next.game;rand_=next.rand;club_modal_runtime_=std::move(next.runtime); + balance_draft_.reset();++revision;return result; + } + default: throw FormatError("balance: unsupported action"); + } + const int calculator_x=next.page.calculator_x,calculator_y=next.page.calculator_y; + next.page.draft=draft;next.page.identity.sequence=identity.sequence+1; + next.page=ui::balance_from_game(next.state,draft,exe_,next.page.identity,next.page.underlay); + next.page.calculator_x=calculator_x;next.page.calculator_y=calculator_y; + apply_balance_source_style(next.page,next.state,next.runtime,exe_); + next.notice_gate={source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::CompactDialogFrame), + source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField2), + source_runtime_byte(next.state,next.runtime,exe_,::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField)}; + next.page.read_only_notice_enabled=next.notice_gate.enabled(); + next.page.read_only_notice.compact_dialog_frame=next.notice_gate.compact_dialog_frame!=0; + next.page.close_notice.compact_dialog_frame=next.notice_gate.compact_dialog_frame!=0; + ui::BalanceScreen validate(data_directory_,next.page); + result.page=next.page;balance_draft_=std::move(next);return result; + } catch(const std::exception& e) {error=e.what();return {};} +} + +std::optional ModernSession::open_league_pairings( + const ui::DeskRequest& request,uint64_t revision,std::string& error) { + error.clear(); + if(league_family_teaminfo_active_||request.kind!=ui::DeskRequestKind::open_menu||request.menu_kind!=1||request.revision!=revision|| + revision==std::numeric_limits::max()||strengths_owner_||strengths_dispatch_active_||balance_draft_||balance_dispatch_active_|| + top_scorers_owner_||top_scorers_dispatch_active_ || stadium_.block_expansion||other_games_owner_||other_games_dispatch_active_||league_pairings_draft_||league_pairings_dispatch_active_|| + market_dispatch_active_||pending_offer_dispatch_active_||calendar_advance_active_||transfer_offer_editor_|| + manager_join_||request.manager_slot<0||request.manager_slot>=4) { + error="pairings: stale, nested or unsupported opening";return std::nullopt; + } + try { + LeaguePairingsDraft next{g_,game_,rand_,club_modal_runtime_,club_modal_runtime_,{}, {}, + modern::save_stream(g_),rand_.seed(),game_.seed(),rand_.calls(),game_.calls()}; + for(const auto& group:turn_driver_.groups) + next.original_active_groups.emplace_back(group.desc,group.fixtures); + next.original_referee_profiles=turn_driver_.referees; + next.owner=modern::open_league_pairings_source(next.state,request.manager_slot,ui::league_pairings_constants(exe_)); + next.active_packet=validate_normal_pairings_group(next.state,next.owner,next.runtime); + const uint64_t scope=++league_pairings_scope_; + auto page=ui::league_pairings_from_game(next.state,next.owner,exe_,revision,scope,0,next.active_packet); + ui::LeaguePairingsScreen validate(data_directory_,page); + next.identity=page.identity; + next.runtime[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(next.owner.league)); + pairings_runtime_draw(next.state,next.runtime,page,exe_); + league_pairings_draft_=std::move(next);return page; + } catch(const std::exception& e) {error=e.what();return std::nullopt;} +} + +std::optional ModernSession::validate_normal_pairings_group( + const ModernState& state,LeaguePairingsOwner& owner, + const std::map& runtime) const { + //Sample synthesizes event8 only for a running process timer. These globals + //are not serialized Native pointers. The normal port starts them at zero. + const auto byte=[&](uint32_t address) {if(state.memory.has(address))return state.memory.u8(address); + const auto at=runtime.find(address);return at==runtime.end()?uint8_t(0):at->second;}; + const unsigned duration=byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField); + const uint32_t started=uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2))|(uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField3))<<8)| + (uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField4))<<16)|(uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField5))<<24); + if(duration<200&&started!=0) + throw FormatError("pairings: active process timer presentation is not implemented"); + auto packet=modern::league_pairings_active_packet_source(state,owner,turn_driver_.groups,turn_driver_.referees); + owner.active_group=packet?packet->group_index:-1; + if(!packet)owner.active_phase=false; + if(packet)modern::validate_league_pairings_active_packet_source(state,owner,*packet); + return packet; +} + +std::optional ModernSession::dispatch_league_pairings( + const ui::LeaguePairingsRequest& request,uint64_t& revision,std::string& error, + const TransferOfferTeamInfoPresenter& team_info) { + if (league_family_teaminfo_active_ || balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + const auto live_matches=[&] { + if(!league_pairings_draft_)return false; + const auto& d=*league_pairings_draft_; + if(d.original_active_groups.size()!=turn_driver_.groups.size()|| + d.original_referee_profiles!=turn_driver_.referees)return false; + for(size_t n=0;nidentity||!live_matches()|| + request.identity.sequence==std::numeric_limits::max()|| + revision==std::numeric_limits::max()) { + error="pairings: stale or nested family action";return std::nullopt; + } + if(request.event.kind==LeaguePairingsAction::team_info&&!team_info) { + error="pairings: TeamInfo presenter unavailable";return std::nullopt; + } + auto next=*league_pairings_draft_; + league_pairings_dispatch_active_=true; + struct Reset {bool& value;~Reset(){value=false;}} reset{league_pairings_dispatch_active_}; + try { + auto bound_owner=next.owner; + const auto bound_packet=validate_normal_pairings_group(next.state,bound_owner,next.runtime); + if(bound_packet!=next.active_packet||bound_owner.active_phase!=next.owner.active_phase|| + bound_owner.active_group!=next.owner.active_group) + throw FormatError("pairings: stale staged active presentation packet"); + next.owner=modern::edit_league_pairings_source(next.state,next.owner,request.event, + ui::league_pairings_constants(exe_),next.game,next.rand); + if(request.event.kind==LeaguePairingsAction::computer_tip) { + const auto put_scratch=[&](uint32_t address,uint8_t value) { + if(next.state.memory.has(address))next.state.memory.set8(address,value); + else next.runtime[address]=value; + }; + // ComputeLeagueTableForecast's final 17295(0x3fc) clears the strength scratch before + // the ordinary list redraw repopulates it from visible away rows. + put_scratch(::bmh::layout::CareerSession_FormatError_ExecutableField3,0);put_scratch(::bmh::layout::CareerSession_FormatError_ExecutableField4,0); + } + if(!next.owner.closed)next.active_packet=validate_normal_pairings_group(next.state,next.owner,next.runtime); + if(request.event.kind==LeaguePairingsAction::team_info) { + const auto parent=ui::league_pairings_from_game(next.state,next.owner,exe_,revision, + next.identity.scope,next.identity.sequence,next.active_packet); + auto services=staged_club_modal_services(next.state,next.game,next.rand,next.runtime); + if(!team_info(services,request.event.value,ui::LeaguePairingsScreen(data_directory_,parent).render())) { + error="pairings: TeamInfo presenter stopped";return std::nullopt; + } + const auto returned_packet=validate_normal_pairings_group(next.state,next.owner,next.runtime); + if(returned_packet!=next.active_packet) + throw FormatError("pairings: active presentation packet changed during TeamInfo"); + } + if(!live_matches()) {error="pairings: live state changed during modal";return std::nullopt;} + LeaguePairingsDispatch result;result.closed=next.owner.closed; + if(result.closed) { + result.preparation=preparation_projection(next.state,revision+1); + ui::validate_preparation_context(result.preparation); + ui::DesktopScreen validate(data_directory_,result.preparation.desktop); + // Move returns with event8;53435 stirs once and leaves. + next.runtime[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=8; + g_=std::move(next.state);game_=next.game;rand_=next.rand;club_modal_runtime_=std::move(next.runtime); + league_pairings_draft_.reset();++revision; + } else { + result.page=ui::league_pairings_from_game(next.state,next.owner,exe_,revision, + next.identity.scope,next.identity.sequence+1,next.active_packet); + ui::LeaguePairingsScreen validate(data_directory_,result.page); + pairings_runtime_draw(next.state,next.runtime,result.page,exe_); + next.identity=result.page.identity;league_pairings_draft_=std::move(next); + } + return result; + } catch(const std::exception& e) {error=e.what();return std::nullopt;} +} + +namespace { +ui::OutgoingTransferEditorState transfer_offer_projection(const ModernState& game, + const TransferOfferEditorState& owner, uint64_t revision, bool gradient) { + ui::OutgoingTransferEditorState out; + const auto& request = owner.request; + out.manager_slot = request.manager; out.runtime_club = request.runtime_club; + out.revision = revision; out.list_entry = request.list_entry; out.source_slot = request.source_slot; + out.player = request.expected_player; + out.seller = request.expected_seller_word == 0xffff ? 0x0fff : request.expected_seller_word & 0x7fff; + out.bid_slot = owner.bid_slot; out.source_mode = owner.mode; + out.editable = owner.editable; out.closed = owner.closed; out.quote_loan = owner.quote_loan; + out.initial_action_loan = request.loan; + out.gradient_text = gradient; + out.fee = owner.fee; out.monthly_salary = owner.salary; out.duration_years = owner.years; + out.bonuses = owner.bonuses; + const auto copy_profile = [](const TransferOfferInputProfile& p) { + return ui::OutgoingTransferCalculatorProfile{p.supported, p.currency, p.minimum, p.maximum, + p.initial, p.source_text_address, p.presets}; + }; + for (size_t n = 0; n < 2; ++n) out.money_calculators[n] = copy_profile(owner.money_profiles[n]); + for (size_t n = 0; n < 8; ++n) out.mode3_calculators[n] = copy_profile(owner.mode3_profiles[n]); + if (owner.closed) return out; // No modal is constructed after Source cleanup. + ui::IncomingTransferDecisionView view; + view.source_outgoing_editor_context = true; + view.valid = true; view.list_entry = request.list_entry; view.player = out.player; + view.seller = out.seller; view.seller_manager = out.seller == 0x0fff ? -1 : game.manager_of(out.seller); + view.viewer_manager = request.manager; + view.asking_fee = owner.asking_fee; view.asking_monthly_salary = owner.asking_salary; + view.quoted_fee = owner.quoted_fee; view.quoted_monthly_salary = owner.quoted_salary; + view.quoted_years = owner.years; + const uint32_t list = ::bmh::layout::EditorList + uint32_t(request.list_entry) * 0x58; + for (uint32_t n = 0; n < 4; ++n) { + auto& row = view.offers[n]; + const auto buyer = game.memory.u16(list + n * 2); + row.bid_index = int(n); row.present = buyer != 0xffff; + row.buyer = row.present ? int(buyer) : -1; + row.buyer_manager = row.present ? game.manager_of(row.buyer) : -1; + row.fee = game.memory.u32(list + 0x1c + n * 4); + row.monthly_salary = game.memory.u32(list + 0x0c + n * 4); + const auto raw_term = game.memory.u8(list + 0x34 + n); + row.loan = (raw_term & 0x80) != 0; row.contract_months = raw_term & 0x7f; + row.eligible = row.present; + for (uint32_t k = 0; k < 7; ++k) row.bonuses[k] = game.memory.u8(list + 0x38 + n * 7 + k); + } + out.panel = ui::incoming_transfer_decision_from_game(game, view); + return out; +} +} + +ui::OutgoingTransferEditorState loan_return_offer_editor_projection( + const ModernState& game, const TransferOfferEditorState& owner, uint64_t revision, bool gradient) { + return transfer_offer_projection(game, owner, revision, gradient); +} + +TransferOfferEditorState edit_transfer_offer_from_ui(ModernState& game, + const TransferOfferEditorState& owner, const ui::OutgoingTransferRequest& request, + GameRandom& game_random, WatcomRandom& watcom_random) { + return modern::edit_transfer_offer_editor_source(game, owner, + {TransferOfferEditorField(uint8_t(request.field)), request.value, request.accepted}, + game_random, watcom_random); +} + +std::optional ModernSession::open_transfer_offer( + const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (request.kind != ui::TransferMarketRequestKind::open_offer || transfer_offer_editor_ || + market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ || + request.revision != revision || revision == std::numeric_limits::max() || + request.manager_slot < 0 || request.manager_slot >= 4 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || + request.bid.manager != request.manager_slot || request.bid.list_entry < 0 || request.bid.list_entry >= 40 || + request.bid.source_slot != int(modern::transfer_list_slot()) + request.bid.list_entry || request.selected_players.size() > 1) { + error = "transfer offer: stale, nested or unsupported marked opening"; + return std::nullopt; + } + const uint32_t list = ::bmh::layout::EditorList + uint32_t(request.bid.list_entry) * 0x58; + if (!g_.memory.has(list + 0x57)) { error = "transfer offer: missing Native list row"; return std::nullopt; } + const uint16_t seller_word = g_.memory.u16(list + 8); + if (!request.selected_players.empty()) { + const auto& selected = request.selected_players.front(); + const int seller = seller_word == 0xffff ? -1 : int(seller_word & 0x7fff); + if (selected.squad_row != -1 || selected.source_slot != request.bid.source_slot || + selected.list_entry != request.bid.list_entry || selected.player != request.bid.player || + selected.seller != seller) { + error = "transfer offer: selected row does not match the Native market identity"; + return std::nullopt; + } + } + int bid_slot = -1; + for (int n = 0; n < 4; ++n) { + const auto buyer = g_.memory.u16(list + uint32_t(n) * 2); + if (buyer == 0xffff || buyer == request.runtime_club) { bid_slot = n; break; } + } + const TransferOfferEditorRequest input{request.manager_slot, request.runtime_club, request.bid.list_entry, + request.bid.source_slot, request.bid.player, seller_word, bid_slot, request.offer_is_loan}; + auto next_state = g_; auto next_game = game_; auto next_rand = rand_; + market_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_}; + try { + auto owner = modern::open_transfer_offer_editor_source(next_state, input, next_game, next_rand); + if (!owner.supported) { error = owner.reason; return std::nullopt; } + // Opening has Source G-seeding/G92..108 even for a full read-only list. + const auto next_revision = revision + 1; + TransferOfferEditorDispatch result; + result.preparation = preparation_projection(next_state, next_revision); + result.editor = transfer_offer_projection(next_state, owner, next_revision, result.preparation.desktop.gradient_text); + ui::OutgoingTransferScreen validate(data_directory_, result.editor); + g_ = std::move(next_state); game_ = next_game; rand_ = next_rand; + transfer_offer_editor_ = std::move(owner); transfer_offer_revision_ = next_revision; revision = next_revision; + return result; + } catch (const std::exception& e) { error = e.what(); return std::nullopt; } +} + +std::optional ModernSession::open_poach( + int manager_slot, int squad_slot, uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ || + revision == std::numeric_limits::max() || manager_slot < 0 || manager_slot >= 4 || + size_t(manager_slot) >= g_.manager_teams.size() || !g_.memory.has(::bmh::layout::ActiveManager) || + g_.memory.u8(::bmh::layout::ActiveManager) != manager_slot) { + error = "poach: stale, nested or unsupported opening"; + return std::nullopt; + } + auto next_state = g_; auto next_game = game_; auto next_rand = rand_; + market_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_}; + try { + PoachDispatch result; + result.start = modern::start_poach(next_state, manager_slot, squad_slot, next_rand); + if (result.start.status == PoachStatus::ready) { + const int row = 0x28 + result.start.offer_row; + const TransferOfferEditorRequest input{manager_slot, g_.manager_teams[size_t(manager_slot)], row, int(modern::transfer_list_slot()) + row, + result.start.player, next_state.memory.u16(::bmh::layout::EditorList + uint32_t(row) * 0x58 + 8), 0, false, true}; + auto owner = modern::open_transfer_offer_editor_source(next_state, input, next_game, next_rand); + if (!owner.supported) { error = owner.reason; return std::nullopt; } + const auto next_revision = revision + 1; + TransferOfferEditorDispatch editor; + editor.preparation = preparation_projection(next_state, next_revision); + editor.editor = transfer_offer_projection(next_state, owner, next_revision, editor.preparation.desktop.gradient_text); + result.editor = std::move(editor); + transfer_offer_editor_ = std::move(owner); + transfer_offer_revision_ = next_revision; + poach_ = result.start; + revision = next_revision; + } else if (result.start.status != PoachStatus::invalid) { + ++revision; // draws, and "Transfermarkt überlastet" counts the attempt + } + g_ = std::move(next_state); game_ = next_game; rand_ = next_rand; + return result; + } catch (const std::exception& e) { error = e.what(); return std::nullopt; } +} + +bool ModernSession::close_poach_table_selection(const ui::LeagueFamilyRequest& request,std::string& error) { + error.clear(); + if(!poach_table_selection_ || request.kind!=ui::LeagueFamilyRequestKind::close || request.from_child!=1 || + !canonical_table_envelope(request) || !league_family_owner_ || league_family_owner_->child!=1 || + league_family_owner_->identity!=request.identity || !league_family_owner_->table || + league_family_owner_->table->phase!=TableDispatchPhase::ready || + modern::save_stream(g_)!=league_family_owner_->native || club_modal_runtime_!=league_family_owner_->runtime || + game_.seed()!=league_family_owner_->game_seed || game_.calls()!=league_family_owner_->game_calls || + rand_.seed()!=league_family_owner_->rand_seed || rand_.calls()!=league_family_owner_->rand_calls) { + error="poach: stale Table selection close";return false; + } + const uint32_t at=::bmh::layout::LeagueTableDisplayModes+uint32_t(request.identity.manager)*2; + uint16_t word=uint16_t(g_.memory.u16(at)&0x0f7f); + if(source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField)!=0)word|=0x80; + g_.memory.set16(at,word); + if(g_.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2))g_.memory.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0);else club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0; + // FriendlyMatchScreen returns directly to19c1c. No21213 family close. + league_family_owner_.reset();return true; +} + +bool ModernSession::dispatch_poach_ui(const ui::TransferMarketRequest& request, + const Image& backdrop, const PoachPlayerSelector& select, const PoachUiAccept& accept, + uint64_t& revision, std::string& error) { + error.clear(); + if (!accept || request.kind!=ui::TransferMarketRequestKind::open_poach || + !g_.memory.has(::bmh::layout::GameMode) || g_.memory.u8(::bmh::layout::GameMode)!=3 || + request.revision!=revision || revision==UINT64_MAX || request.manager_slot<0 || request.manager_slot>3 || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager)!=request.manager_slot || + size_t(request.manager_slot)>=g_.manager_teams.size() || + request.runtime_club!=g_.manager_teams[size_t(request.manager_slot)] || + request.bid.manager!=request.manager_slot || request.bid.list_entry!=-1 || request.bid.player!=-1 || + request.bid.source_slot!=-1 || request.bid.fee!=0 || request.bid.annual_salary!=0 || + request.bid.contract_years!=1 || request.bid.poach || std::any_of(request.bid.bonuses.begin(),request.bid.bonuses.end(), + [](uint32_t n){return n!=0;}) || request.squad_row!=-1 || request.expected_player!=-1 || + request.preview_source_slot!=-1 || request.preview_seller!=-1 || request.preview_is_purchase || + request.preview_is_loan || !request.selected_players.empty() || + backdrop.width!=320 || backdrop.height!=240 || advertising_renewal_dispatch_active_ || pending_offer_dispatch_active_ || market_dispatch_active_ || + calendar_advance_active_ || transfer_offer_editor_ || poach_ || manager_join_ || contract_quote_ || + league_family_owner_ || league_pairings_draft_ || strengths_owner_ || top_scorers_owner_ || + other_games_owner_ || balance_draft_ || stadium_.opened || + (turn_driver_.stage!=TurnDriver::Stage::MatchdayDesks && turn_driver_.stage!=TurnDriver::Stage::SeasonEndDesk)) { + error="poach: stale or competing selection";return false; + } + const auto checkpoint=advertising_session_checkpoint(revision); + try { + const int manager=request.manager_slot; + const size_t record=size_t(manager)*0xb0c; + PoachDispatch result; + result.start.manager=manager; + // These three notices precede the Table modal in Reset. + if (record+0x8c0>g_.manager_records.size()) throw FormatError("poach: missing manager record"); + const bool attempts_used=(g_.manager_records[record+0x8be] | + uint16_t(g_.manager_records[record+0x8bf])<<8)!=0xffff; + if(attempts_used) { + result.start.status=PoachStatus::attempts_used; + result.start.messages.push_back(message_text(g_,::bmh::layout::CareerSession_DispatchPoachUi_TextPointer2)); + } else if(g_.manager_records[record+0x220]>>5==1) { + result.start.status=PoachStatus::transfer_ban; + result.start.messages.push_back(message_text(g_,::bmh::layout::CareerSession_DispatchPoachUi_TextPointer)); + } else if(request.offer_is_loan) { + auto services=staged_club_modal_services(g_,game_,rand_,club_modal_runtime_); + services.set_runtime_byte(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField,0); + services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2,g_.manager_records[record+0x210]); + services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField,2); + result.start.messages.push_back(message_text(g_,::bmh::layout::CareerSession_DispatchPoachUi_TextPointer3)); + } else { + if(!select) throw FormatError("poach: Source player selection presenter unavailable"); + // The cloned Session owns the existing50775 controls implementation. + // begin_league_family(child1) itself does not call53435; only the + // host Table owner is reused, never prepare/close-family effects. + ModernSession staged=*this; + staged.poach_table_selection_=true; + uint64_t selection_revision=revision; + auto services=staged.staged_club_modal_services(staged.g_,staged.game_,staged.rand_,staged.club_modal_runtime_); + services.set_runtime_byte(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField,0); + services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2,g_.manager_records[record+0x210]); + services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField,2); + services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField,0);services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0); + //50775 control7 toggles this existing BSS byte. Materialize its + // actual current value in the staged runtime, including when it + // was read from the executable rather than persisted in Native. + services.set_runtime_byte(::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField,services.runtime_byte(::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField)); + auto entry=staged.strengths_open_request(selection_revision); + if(!entry)throw FormatError("poach: missing Table selection identity"); + entry->identity.league=g_.manager_records[record+0x210];entry->identity.league_group=0; + if(!staged.begin_league_family(entry->identity,1,selection_revision,error))throw FormatError(error); + market_dispatch_active_=true; + const auto live_baseline=advertising_session_checkpoint(revision); + const auto selection=select(staged,services,manager,selection_revision,backdrop); + if(!advertising_session_unchanged(live_baseline,revision)) + throw FormatError("poach: selection changed the live session"); + auto& next=staged.g_; + if(next.date!=g_.date || next.manager_teams!=g_.manager_teams || + !next.memory.has(::bmh::layout::ActiveManager) || next.memory.u8(::bmh::layout::ActiveManager)!=manager) + throw FormatError("poach: selection changed its manager/calendar context"); + market_dispatch_active_=false; + int slot=-1; + if(selection) { + if(selection->origin!=ClubPlayerDetailOrigin::squad || selection->human_loan_index!=-1) + throw FormatError("poach: selection is not an ordinary squad row"); + const auto player=modern::club_player_detail_context(next,*selection); + slot=player.source_slot; + if(slot<0 || slot>=int(modern::transfer_list_slot()) || modern::slot_team(slot)!=selection->runtime_team || + (next.squad_slots.at(size_t(slot))&0xfff)!=selection->player_id) + throw FormatError("poach: stale player selection"); + } + // Preserve actual Table/ClubInfo/card effects, including a cancelled + // selection. No LeagueScreenShown entry and no family-close RNG stir. + g_=std::move(next);game_=staged.game_;rand_=staged.rand_;club_modal_runtime_=std::move(staged.club_modal_runtime_); + if(selection) { + auto opened=open_poach(manager,slot,revision,error); + if(!opened) throw FormatError(error); + result=std::move(*opened); + } + if(revision==checkpoint.revision) ++revision; + } + const auto accepted_baseline=advertising_session_checkpoint(revision); + accept(result,preparation_projection(revision)); + if(!advertising_session_unchanged(accepted_baseline,revision)) + throw FormatError("poach: UI acknowledgement changed the session"); + return true; + } catch(const std::exception& e) { + restore_advertising_session_checkpoint(checkpoint);revision=checkpoint.revision; + error=e.what();return false; + } +} + +std::optional ModernSession::dispatch_transfer_offer( + const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& presenters, + uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info, + const TransferOfferPlayerInfoPresenter& player_info) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (!transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ || + request.identity.revision != revision || transfer_offer_revision_ != revision || + revision == std::numeric_limits::max()) { + error = "transfer offer: stale or nested editor event"; return std::nullopt; + } + const auto& current = *transfer_offer_editor_; + const auto& id = request.identity; + const int seller = current.request.expected_seller_word == 0xffff ? 0x0fff : current.request.expected_seller_word & 0x7fff; + if (id.manager_slot != current.request.manager || id.runtime_club != current.request.runtime_club || + id.list_entry != current.request.list_entry || id.source_slot != current.request.source_slot || + id.player != current.request.expected_player || id.seller != seller || id.bid_slot != current.bid_slot || + request.quoted_fee != current.quoted_fee || request.quoted_monthly_salary != current.quoted_salary || + request.quoted_years != current.years) { + error = "transfer offer: mismatched editor identity or quote"; return std::nullopt; + } + uint32_t fee = current.fee, salary = current.salary; + uint8_t years = current.years; auto bonuses = current.bonuses; + bool quote_loan = current.quote_loan; + const unsigned field = unsigned(request.field); + if (request.kind == ui::OutgoingTransferRequestKind::quote_change) { + if (field > unsigned(ui::OutgoingTransferField::quote_loan)) { + error = "transfer offer: invalid editor field"; return std::nullopt; + } + if (request.accepted) { + if (field == 0) fee = request.value; + else if (field == 1) salary = request.value; + else if (field == 2) years = uint8_t(request.value); + else if (field < 10) bonuses[field - 3] = uint8_t(field < 6 ? request.value : request.value / 5); + else quote_loan = !quote_loan; + } + } else if (request.kind != ui::OutgoingTransferRequestKind::submit && request.kind != ui::OutgoingTransferRequestKind::cancel && + request.kind != ui::OutgoingTransferRequestKind::team_info && + request.kind != ui::OutgoingTransferRequestKind::player_info) { + error = "transfer offer: unsupported editor event"; return std::nullopt; + } + if (request.fee != fee || request.monthly_salary != salary || request.duration_years != years || + request.bonuses != bonuses || request.quote_loan != quote_loan) { + error = "transfer offer: posted row differs from the single Source field event"; return std::nullopt; + } + if(request.kind==ui::OutgoingTransferRequestKind::team_info&&!team_info) { + error="transfer offer: TeamInfo presenter unavailable"; return std::nullopt; + } + if(request.kind==ui::OutgoingTransferRequestKind::player_info&&!player_info) { + error="transfer offer: PlayerInfo presenter unavailable"; return std::nullopt; + } + auto next_state = g_; auto next_game = game_; auto next_rand = rand_; + auto next_runtime=club_modal_runtime_; + auto owner = current; TransferActionResult action; + auto hooks = presenters; + switch (turn_driver_.transfer_allocator_context) { + case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + hooks.before_accounts = {}; hooks.after_paid_accounts = {}; + market_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_}; + try { + if (request.kind == ui::OutgoingTransferRequestKind::quote_change) { + owner = edit_transfer_offer_from_ui(next_state, current, request, next_game, next_rand); + } else if (request.kind == ui::OutgoingTransferRequestKind::cancel) { + owner = modern::cancel_transfer_offer_editor_source(next_state, current); + } else if(request.kind==ui::OutgoingTransferRequestKind::team_info) { + // Validate the complete old Native row before any modal effect. + const auto validation=modern::cancel_transfer_offer_editor_source(next_state,current); + if(!validation.supported) {error=validation.reason;return std::nullopt;} + auto services=staged_club_modal_services(next_state,next_game,next_rand,next_runtime); + const auto parent=transfer_offer_projection(next_state,current,revision, + next_state.memory.u8(::bmh::layout::TextGradientDisabled)==0); + const Image backdrop=ui::OutgoingTransferScreen(data_directory_,parent).render(); + if(!team_info(services,current.request.runtime_club,backdrop)) { + error="transfer offer: TeamInfo presenter stopped";return std::nullopt; + } + owner=modern::resume_transfer_offer_team_info_source(next_state,current,next_rand); + } else if(request.kind==ui::OutgoingTransferRequestKind::player_info) { + const auto selection=modern::transfer_offer_player_info_selection_source(next_state,current); + auto services=staged_club_modal_services(next_state,next_game,next_rand,next_runtime); + const auto parent=transfer_offer_projection(next_state,current,revision, + next_state.memory.u8(::bmh::layout::TextGradientDisabled)==0); + const Image backdrop=ui::OutgoingTransferScreen(data_directory_,parent).render(); + services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField,1); // Source direct entry persists, unlike4f548. + if(!player_info(services,selection,backdrop)) { + error="transfer offer: PlayerInfo presenter stopped";return std::nullopt; + } + owner=modern::resume_transfer_offer_player_info_source(next_state,current, + services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField),services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2),next_rand); + } else { + MinuteReport report; + auto submitted = modern::submit_transfer_offer_editor_source(next_state, current, next_rand, hooks, report); + owner = std::move(submitted.editor); action = submitted.action; + if (report.unsupported) { error = report.reason; return std::nullopt; } + } + if (!owner.supported) { error = owner.reason; return std::nullopt; } + // a poaching editor that closes frees its special row and counts the attempt (Reset) + if (owner.closed && poach_) modern::finish_poach(next_state, *poach_); + const bool changed = modern::save_stream(next_state) != modern::save_stream(g_) || next_runtime != club_modal_runtime_ || + next_game.seed() != game_.seed() || next_game.calls() != game_.calls() || + next_rand.seed() != rand_.seed() || next_rand.calls() != rand_.calls(); + const auto next_revision = revision + uint64_t(changed); + TransferOfferEditorDispatch result; + result.preparation = preparation_projection(next_state, next_revision); + result.editor = transfer_offer_projection(next_state, owner, next_revision, result.preparation.desktop.gradient_text); + result.action = action; + if (!owner.closed) { ui::OutgoingTransferScreen validate(data_directory_, result.editor); } + g_ = std::move(next_state); game_ = next_game; rand_ = next_rand; + club_modal_runtime_=std::move(next_runtime); + if (owner.closed) { transfer_offer_editor_.reset(); poach_.reset(); } else transfer_offer_editor_ = std::move(owner); + transfer_offer_revision_ = next_revision; revision = next_revision; + return result; + } catch (const std::exception& e) { error = e.what(); return std::nullopt; } +} + +std::optional ModernSession::preview_transfer_market( + const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (request.kind != ui::TransferMarketRequestKind::preview_quote || + transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ || + request.revision != revision || revision == std::numeric_limits::max() || + request.manager_slot < 0 || request.manager_slot >= 4 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)]) { + error = "transfer market: stale or nested preview"; + return std::nullopt; + } + if (request.preview_is_purchase) { + if (request.preview_snapshot_index != -1 || request.squad_row != -1 || request.bid.manager != request.manager_slot || + request.bid.list_entry < 0 || request.bid.list_entry >= 40 || + request.bid.source_slot != request.preview_source_slot || + request.preview_source_slot != int(modern::transfer_list_slot()) + request.bid.list_entry || + request.bid.player != request.expected_player) { + error = "transfer market: mismatched preview listing identity"; + return std::nullopt; + } + } else if (request.preview_snapshot_index >= 0) { + const auto identity = modern::transfer_market_snapshot_preview(g_, request.manager_slot, + request.runtime_club, request.preview_snapshot_index); + if (!identity || identity->displayed_row != request.squad_row || identity->player != request.expected_player || + identity->source_slot != request.preview_source_slot || request.preview_seller != request.runtime_club) { + error = "transfer market: mismatched lender snapshot identity"; + return std::nullopt; + } + } else { + const auto range = squad_range(request.runtime_club); + if (request.preview_snapshot_index != -1 || request.squad_row < 0 || size_t(request.squad_row) >= range.count || + request.preview_source_slot != int(range.first + size_t(request.squad_row)) || + request.preview_seller != request.runtime_club) { + error = "transfer market: mismatched preview roster identity"; + return std::nullopt; + } + } + auto next_rand = rand_; + market_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_}; + try { + const TransferMarketPreviewRequest input{request.manager_slot, request.runtime_club, + request.preview_source_slot, request.expected_player, request.preview_seller, + request.preview_is_purchase, request.preview_is_loan, request.preview_snapshot_index}; + const auto result = modern::quote_transfer_market_preview_source(g_, input, next_rand); + if (!result.supported) { + error = result.reason.empty() ? "transfer market: unsupported Source preview" : result.reason; + return std::nullopt; + } + const bool changed = next_rand.seed() != rand_.seed() || next_rand.calls() != rand_.calls(); + const auto next_revision = revision + uint64_t(changed); + TransferMarketPreviewDispatch dispatch; + dispatch.preparation = preparation_projection(next_revision); + if (!dispatch.preparation.transfer_market) + throw FormatError("transfer market: preview has no ordinary projection"); + dispatch.quote = {request.manager_slot, request.runtime_club, request.preview_source_slot, + request.expected_player, request.preview_seller, next_revision, + result.delta, result.projected_balance, request.preview_is_purchase, request.preview_is_loan, request.preview_snapshot_index}; + // Projection construction can throw. Keep the live W stream and revision + // unchanged until both the Source result and the projection are valid. + rand_ = next_rand; + revision = next_revision; + return dispatch; + } catch (const std::exception& e) { + error = e.what(); + return std::nullopt; + } +} + +std::optional ModernSession::dispatch_transfer_market( + const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& presenters, + uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ || + request.revision != revision || revision == std::numeric_limits::max() || + request.manager_slot < 0 || request.manager_slot >= 4 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)]) { + error = "transfer market: stale or nested request"; + return std::nullopt; + } + if (request.kind == ui::TransferMarketRequestKind::submit_bid) { + if (request.bid.manager != request.manager_slot || request.squad_row != -1 || + request.expected_player != -1 || + std::any_of(request.bid.bonuses.begin(), request.bid.bonuses.end(), + [](uint32_t value) { return value > 255; })) { + error = "transfer market: invalid buyer request"; + return std::nullopt; + } + } else if (request.kind == ui::TransferMarketRequestKind::list_player) { + const auto range = squad_range(request.runtime_club); + if (request.squad_row < 0 || size_t(request.squad_row) >= range.count || + range.first + size_t(request.squad_row) >= g_.squad_slots.size() || + request.expected_player < 0 || request.expected_player >= 0xfff || + (g_.squad_slots[range.first + size_t(request.squad_row)] & 0xfff) != request.expected_player) { + error = "transfer market: stale seller row"; + return std::nullopt; + } + } else { + error = "transfer market: unsupported action"; + return std::nullopt; + } + // Reset sends an owned marked player through the same Size2 + // listing for both VER-KAUFEN and VER-LEIHEN. Only a buyer's OpenTransferEditor + // offer owns the actual loan term; listing does not create a loan record. + if ((request.offer_is_loan && request.kind != ui::TransferMarketRequestKind::list_player) || + request.selected_players.size() > 1) { + error = "transfer market: this caller does not own buyer loan or marked batch processing"; + return std::nullopt; + } + if (!request.selected_players.empty()) { + const auto& selected = request.selected_players.front(); + const bool matches = request.kind == ui::TransferMarketRequestKind::list_player + ? selected.squad_row == request.squad_row && selected.player == request.expected_player && + selected.seller == request.runtime_club && + selected.source_slot == int(squad_range(request.runtime_club).first + size_t(request.squad_row)) + : selected.list_entry == request.bid.list_entry && selected.source_slot == request.bid.source_slot && + selected.player == request.bid.player && selected.squad_row == -1; + if (!matches) { + error = "transfer market: mismatched marked selection"; + return std::nullopt; + } + } + + auto next_state = g_; + auto next_game = game_; + auto next_rand = rand_; + auto hooks = presenters; + // A presenter cannot supply the allocator gate or insert the special + // pending caller's severance/ACK/news sequence into a direct purchase. + switch (turn_driver_.transfer_allocator_context) { + case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + // Reset -> OpenTransferEditor establishes DeskActions_EditorFail_RuntimeField2=0 at LAB1b67e before + // resolving the AI seller. This explicitly selected App entry supplies + // that transient ownership; a missing FBM byte is never the observation. + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + hooks.before_accounts = {}; + hooks.after_paid_accounts = {}; + market_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_}; + MinuteReport report; + try { + const auto before = modern::save_stream(g_); + TransferActionResult result; + if (request.kind == ui::TransferMarketRequestKind::list_player) + result = modern::list_manager_player(next_state, request.manager_slot, request.squad_row, next_rand, report); + else + result = modern::submit_transfer_bid_source_human_buyer(next_state, request.bid, next_rand, hooks, report); + if (report.unsupported || result.status == TransferActionStatus::unsupported) { + error = report.reason.empty() ? "transfer market: unsupported Source sale" : report.reason; + return std::nullopt; + } + const bool changed = modern::save_stream(next_state) != before || + next_rand.seed() != rand_.seed() || next_rand.calls() != rand_.calls() || + next_game.seed() != game_.seed() || next_game.calls() != game_.calls(); + if (changed) { + // Pure projections reject inconsistent squad/board/training state + // before any staged notice effects become live. + (void)ui::preparation_from_game(next_state, exe_, revision + 1); + g_ = std::move(next_state); + game_ = next_game; + rand_ = next_rand; + ++revision; + } + return result; + } catch (const std::exception& e) { + error = e.what(); + return std::nullopt; + } +} + +bool ModernSession::finish(ui::CareerInitializationResult& result, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const bool previous_advance = calendar_advance_active_; + calendar_advance_active_ = true; + struct AdvanceReset { bool& active; bool previous; ~AdvanceReset() { active = previous; } } + advance_reset{calendar_advance_active_, previous_advance}; + MinuteReport report; + modern::career_managers_end(g_, false); + const auto season_pause = [this](const char* checkpoint) { + if (turn_driver_.season_pause) turn_driver_.season_pause(checkpoint, g_); + }; + if (!modern::career_season_setup(g_, game_, rand_, report, season_pause, turn_driver_.season_cup_draw) || + !modern::career_first_steps(g_, game_, rand_, report)) { + error = report.reason; + return false; + } + // DailyInterest's loop: the event of season day 0 (AdvanceTurn) and the first desk + std::vector referees = db_.raw_referee_properties; + MatchdayContext ctx; + ctx.month = modern::month_code(g_.date); + ctx.season_day = g_.season_day(); + ctx.weekday = modern::weekday_code(g_.date); + ctx.referees = &referees; + const uint16_t entry = g_.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(g_.season_day()) * 2); + std::vector groups = modern::prepare_event(g_, entry, ctx, game_, rand_, report); + modern::enter_event_desk(g_, 0, groups, game_, rand_, report, true, turn_driver_.desk_autosave); + if (report.unsupported) { + error = report.reason; + return false; + } + if (!modern::begin_turn_driver(turn_driver_, g_, std::move(groups), entry, db_.raw_referee_properties, + session_id_, 1, error)) + return false; + capture_source_desk_callargs(); + // Both UI projections must reflect the freshly initialized driver cursor. + // Reuse its prepared groups; these projections do not prepare an event or draw RNG. + result.desktop = desktop_projection(1); + result.preparation = preparation_projection(1); + for (size_t m = 0; m < managers_.size(); ++m) + managers_[m].runtime_club = g_.manager_teams.at(m); + result.managers = managers_; + flush_native_autosave(); + return true; +} + +TurnAdvanceResult ModernSession::dispatch_kickoff(const ui::DeskRequest& request, uint64_t& revision, + std::string& error) { + error.clear(); + if (strengths_owner_ || strengths_dispatch_active_ || balance_draft_ || balance_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_ || league_pairings_draft_ || league_pairings_dispatch_active_ || transfer_offer_editor_ || pending_offer_dispatch_active_ || market_dispatch_active_) { + error = "pending_offer_decision_active"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (career_complete()) { + error = "career_complete"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = -1; + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (!saved_turn_error_.empty()) { + error = saved_turn_error_; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (request.kind != ui::DeskRequestKind::advance_turn || request.revision != revision) { + error = "stale_manager_or_revision"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (request.manager_slot != int(g_.memory.u8(::bmh::layout::ActiveManager))) { + error = "stale_manager_or_revision"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + const auto remain_at_desk = [&](TurnDeskKind kind, std::string reason) { + if (reason.empty()) reason = "post-desk pending presenter stopped"; + error = std::move(reason); + TurnAdvanceResult out; + out.kind = kind; + out.manager_slot = request.manager_slot; + out.date = g_.date; + out.revision = revision; + out.reason = error; + return out; + }; + if (revision == std::numeric_limits::max() || + (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk)) + return remain_at_desk(TurnDeskKind::Failed, "stale_or_exhausted_turn_cursor"); + + // Pending decisions and their cursor checks must complete together or + // restore the previous desk. Once simulation starts, its terminal failure + // cursor must stay claimed: external presentation cannot be rolled back. + struct KickoffTransaction { + ModernSession& session; + uint64_t& revision; + std::optional before; + void restore() { + if (!before) return; + auto checkpoint = std::move(*before); + before.reset(); + revision = checkpoint.revision; + session.restore_advertising_session_checkpoint(std::move(checkpoint)); + } + ~KickoffTransaction() { restore(); } + } transaction{*this, revision, advertising_session_checkpoint(revision)}; + const auto stop_at_desk = [&](TurnDeskKind kind, std::string reason) { + transaction.restore(); + return remain_at_desk(kind, std::move(reason)); + }; + const bool previous_advance = calendar_advance_active_; + calendar_advance_active_ = true; + struct AdvanceReset { bool& active; bool previous; ~AdvanceReset() { active = previous; } } + advance_reset{calendar_advance_active_, previous_advance}; + if ((turn_driver_.stage == TurnDriver::Stage::MatchdayDesks || + turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk) && + pending_offer_entry_policy_ == PendingOfferEntryPolicy::normal_interactive) { + // AdvanceTurn resolves this manager before the next desk or simulation. + // An unsupported decision must leave the driver unclaimed and retryable. + pending_offer_dispatch_active_ = true; + struct PendingReset { bool& active; ~PendingReset() { active = false; } } + pending_reset{pending_offer_dispatch_active_}; + try { + const auto modal_baseline = advertising_session_checkpoint(revision); + auto next_state = g_; + auto next_game = game_; + auto next_rand = rand_; + const auto hooks = pending_hooks_for_dispatch(pending_offer_hooks_); + MinuteReport pending_report; + // Explicit supported interactive runtime policy, not reconstructed + // Original transient bytes or an answer inferred from missing data. + const PendingOfferDeskRequest pending_request{ + PendingOfferDeskRuntimeMode::normal_interactive, + int(g_.manager_teams.size()), turn_driver_.manager_position}; + // A nomination desk has one temporary national manager but retains + // the original order prefix. Its Source post-return owner can differ + // from the runtime desk owner, so ordinary permutation checks do not apply. + const auto pending = turn_driver_.national_nomination_desk + ? modern::process_national_nomination_pending_after_desk( + next_state, pending_request, next_game, next_rand, hooks, pending_report) + : modern::process_natural_pending_offers_after_desk( + next_state, pending_request, next_game, next_rand, hooks, pending_report); + // This existing fingerprint covers Native and its qualified + // runtime/owners, RNG and revision, not arbitrary memory writes. + if (!advertising_session_unchanged(modal_baseline, revision) || + turn_driver_.manager_position != modal_baseline.driver.manager_position || + turn_driver_.revision != modal_baseline.driver.revision || + turn_driver_.calendar_entry != modal_baseline.driver.calendar_entry) + return stop_at_desk(TurnDeskKind::Failed, "pending_offer_reentrant_state"); + if (pending_report.unsupported || !pending.completed) + return stop_at_desk(TurnDeskKind::WaitingAtDesk, + pending_report.reason.empty() ? "post-desk pending decision incomplete" : pending_report.reason); + // Even a batch without owned offers performs Source's last-manager + // cleanup and completed-loop cursor write. No intermediate revision. + g_ = std::move(next_state); + game_ = next_game; + rand_ = next_rand; + } catch (const std::exception& e) { + return stop_at_desk(TurnDeskKind::WaitingAtDesk, e.what()); + } + } + // Resolve names before advancing: next_event can reorder clubs at a season + // transition. The result view must keep the identities of the played event. + std::vector names; + names.reserve(g_.club_ids.size()); + for (size_t team = 0; team < g_.club_ids.size(); ++team) + names.push_back(ui::original_to_utf8(g_.club_name(int(team)))); + const bool had_results = turn_driver_.last_results.valid; + const uint32_t previous_result_date = turn_driver_.last_results.date; + const uint32_t previous_day = g_.date; + const uint16_t previous_calendar_entry = turn_driver_.calendar_entry; + // Desk actions legitimately advance the app's projection revision between turns. + // Adopt that already-validated current revision before handing off the kickoff. + // AdvanceTurn(param1=1) skips only later pre-match offer generation in this + // already prepared loop. Legacy/headless callers retain their explicit path. + // Select it after a complete staged batch so Waiting cannot alter the cursor. + turn_driver_.suppress_remaining_pre_match_offers = + pending_offer_entry_policy_ == PendingOfferEntryPolicy::normal_interactive && + turn_driver_.loaded_matchday_resume; + // Select the complete nomination-desk lifecycle only for the interactive + // controller, after the staged outgoing batch has completed successfully. + turn_driver_.enable_national_nomination_desks = + pending_offer_entry_policy_ == PendingOfferEntryPolicy::normal_interactive; + turn_driver_.revision = revision; + MinuteReport report; + // Contract expiry can also be reached by a headless/unpresented session. + // Keep the checkpoint from before the complete pending decision batch so a + // missing decision owner cannot commit its Native cursor cleanup or leave + // an expired player partially advanced. + std::optional contract_expiry_checkpoint = transaction.before; + transaction.before.reset(); // claim the completed decision batch before simulation callbacks + turn_driver_.reality_rules = &exe_; + turn_driver_.sportschau_source = sportschau_source_options(); + TurnAdvanceResult result = modern::advance_to_next_desk(turn_driver_, g_, + TurnAdvanceRequest{request.manager_slot, request.revision}, game_, rand_, report); + if (result.kind == TurnDeskKind::Failed || result.kind == TurnDeskKind::WaitingAtDesk) { + if (contract_expiry_checkpoint && (result.reason.find("month change: a contract ends") != std::string::npos || + result.reason.find("month change: human-owner loan record is incomplete") != std::string::npos || + result.reason.find("month change: human-owner loan cannot be restored safely") != std::string::npos || + result.reason.find("month change: expiring human-borrower loan") != std::string::npos || + result.reason.find("month change: human-borrower loan return dialog") != std::string::npos || + result.reason.find("month change: OpenTransferEditor return-offer editor") != std::string::npos)) { + const uint64_t checkpoint_revision = contract_expiry_checkpoint->revision; + restore_advertising_session_checkpoint(std::move(*contract_expiry_checkpoint)); + revision = checkpoint_revision; + return remain_at_desk(result.kind, result.reason); + } + return stop_at_desk(result.kind, result.reason); + } + revision = result.revision; + if (g_.date != previous_day || turn_driver_.calendar_entry != previous_calendar_entry) + capture_source_desk_callargs(); + lineup_entry_manager_ = -1; + lineup_entry_club_ = -1; + completed_results_.reset(); + const auto& snapshot = turn_driver_.last_results; + if (snapshot.valid && !snapshot.groups.empty() && + (!had_results || snapshot.date != previous_result_date)) { + completed_results_ = ui::matchday_results_from_snapshot(snapshot, [&](int team) { + const size_t id = size_t(team & 0x0fff); + return id < names.size() ? names[id] : std::string(); + }, exe_, g_); + } + flush_native_autosave(); + return result; +} + + +bool ModernSession::dispatch_mailbox(const ui::MailboxActionRequest& request, uint64_t& revision, + std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + if (active < 0 || active > 3 || size_t(active) >= g_.manager_teams.size() || + request.manager_slot != active || request.revision != revision || + revision == std::numeric_limits::max()) { + error = "Diese Nachricht gehört zu einem veralteten Postfach."; + return false; + } + constexpr size_t entry_size = 0xa0, entries = 40; + if (request.entry_index < 0 || size_t(request.entry_index) >= entries || + g_.mailbox.size() < entries * entry_size) { + error = "Diese Nachricht ist nicht mehr vorhanden."; + return false; + } + const size_t at = size_t(request.entry_index) * entry_size; + if (!std::equal(request.expected_entry.begin(), request.expected_entry.end(), g_.mailbox.begin() + at)) { + error = "Diese Nachricht wurde inzwischen geändert."; + return false; + } + const auto word = [&](size_t p) { + return uint32_t(g_.mailbox[p]) | uint32_t(g_.mailbox[p + 1]) << 8 | + uint32_t(g_.mailbox[p + 2]) << 16 | uint32_t(g_.mailbox[p + 3]) << 24; + }; + const uint32_t bit = uint32_t(1) << active; + const uint32_t recipients = word(at), kept = word(at + 4); + if (!(recipients & bit)) { + error = "Diese Nachricht ist nicht an diesen Manager gerichtet."; + return false; + } + size_t target = at; + uint32_t value = recipients; + if (request.kind == ui::MailboxActionKind::toggle_keep) { + int count = 0; + for (size_t i = 0; i < entries; ++i) + if ((word(i * entry_size) & bit) && (word(i * entry_size + 4) & bit)) ++count; + // MailboxStateFromGame tests (recipient word + 1), NOT the kept word. Preserve + // its manager-specific five-entry exception, including blocked unkeep. + if (!((recipients + 1u) & bit) && count >= 5) { + error = "Die Originalgrenze für gemerkte Nachrichten ist erreicht."; + return false; + } + target += 4; value = kept ^ bit; + } else if (request.kind == ui::MailboxActionKind::delete_for_manager) { + if (kept & bit) { + error = "Diese Nachricht ist noch gemerkt."; + return false; + } + value = recipients ^ bit; + if (value == 0x80000000u) value = 0; + } else { + error = "Unbekannte Postfachaktion."; + return false; + } + for (size_t i = 0; i < 4; ++i) g_.mailbox[target + i] = uint8_t(value >> (8 * i)); + ++revision; + return true; +} + +std::optional ModernSession::pending_mailbox_notification(uint64_t revision) const { + if (!g_.memory.has(::bmh::layout::ActiveManager)) return std::nullopt; + const int manager = int(g_.memory.u8(::bmh::layout::ActiveManager)); + if (manager < 0 || manager >= 4 || size_t(manager) >= g_.manager_teams.size() || + g_.manager_teams[size_t(manager)] == no_team() || !g_.memory.has(::bmh::layout::MailboxRecipientMask) || + (g_.memory.u32(::bmh::layout::MailboxRecipientMask) & (uint32_t(1) << manager)) == 0) + return std::nullopt; + return ui::mailbox_state_from_game(g_, manager, revision); +} + +bool ModernSession::acknowledge_mailbox_close(const ui::MailboxCloseRequest& request, + uint64_t revision, std::string& error) { + if (!g_.memory.has(::bmh::layout::ActiveManager) || request.manager_slot < 0 || request.manager_slot >= 4 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + request.manager_slot != int(g_.memory.u8(::bmh::layout::ActiveManager)) || request.revision != revision) { + error = "Diese Nachrichtenansicht gehört zu einem veralteten Manager oder Spielstand."; + return false; + } + // MailboxStateFromGame clears only this manager's MailboxRecipientMask bit on normal exit. + // The latch lives outside the FBM data blocks and does not advance game revision. + if (g_.memory.has(::bmh::layout::MailboxRecipientMask)) { + const uint32_t notifications = g_.memory.u32(::bmh::layout::MailboxRecipientMask); + const uint32_t bit = uint32_t(1) << request.manager_slot; + if (notifications & bit) g_.memory.set32(::bmh::layout::MailboxRecipientMask, notifications & ~bit); + } + error.clear(); + return true; +} + +bool ModernSession::dispatch_settings(const ui::SettingsWriteRequest& request, uint64_t& revision, + std::string& error) { + if ((live_settings_owner_ && !live_settings_dispatch_active_) || + (desk_settings_owner_ && !desk_settings_dispatch_active_)) { + error = "Diese Einstellung gehört zum geöffneten Einstellungsmenü."; + return false; + } + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + auto& mem = g_.memory; + if (request.manager_slot < 0 || request.manager_slot > 3 || + size_t(request.manager_slot) >= g_.manager_teams.size() || !mem.has(::bmh::layout::ActiveManager) || + int(mem.u8(::bmh::layout::ActiveManager)) != request.manager_slot || request.revision != revision || + revision == std::numeric_limits::max()) { + error = "Diese Einstellungsaktion gehört zu einem veralteten Manager oder Stand."; + return false; + } + if (request.row >= 20 || request.column >= 9 || !mem.has(::bmh::layout::LeaguePresentationOptions + 179) || + !mem.has(::bmh::layout::GameMode) || !mem.has(::bmh::layout::CompetitionSelection)) { + error = "Der Einstellungszustand ist unvollständig."; + return false; + } + std::array raw{}; + for (size_t i = 0; i < raw.size(); ++i) { + const uint32_t address = ::bmh::layout::LeaguePresentationOptions + uint32_t(i); + if (!mem.has(address)) { error = "Der Einstellungszustand ist unvollständig."; return false; } + raw[i] = mem.u8(address); + } + if (raw != request.expected_raw) { + error = "Die Einstellungen wurden inzwischen geändert."; + return false; + } + const size_t index = size_t(request.row) * 9 + request.column; + const uint32_t address = ::bmh::layout::LeaguePresentationOptions + uint32_t(index); + ui::SettingsAvailabilityInputs inputs{mem.u8(::bmh::layout::GameMode), mem.u32(::bmh::layout::CompetitionSelection), + uint8_t(sound_capabilities_ && !sound_capabilities_->music), + uint8_t(sound_capabilities_ && !sound_capabilities_->effects)}; + auto availability = ui::project_settings_availability(raw, inputs, exe_); + // The host supplies the portable sound driver's capabilities. Headless + // callers without that provider retain the unknown Source latch boundary. + if (!sound_capabilities_) { availability[5] = raw[5]; availability[6] = raw[6]; } + const bool sound_cell = request.row == 0 && (request.column == 5 || request.column == 6); + if (sound_cell && !sound_capabilities_) { + error = "Diese Einstellung ist noch nicht verfügbar."; + return false; + } + const bool scoped_settings = (live_settings_owner_.has_value() && live_settings_dispatch_active_) || + (desk_settings_owner_.has_value() && desk_settings_dispatch_active_); + if (((request.row == 8 && request.column == 7) && !scoped_settings) || + (request.column == 7 && request.row >= 14 && request.row <= 19)) { + error = "Diese Einstellung ist noch nicht verfügbar."; + return false; + } + if ((request.operation != ui::SettingsEdit::toggle_binary && + request.operation != ui::SettingsEdit::decrement && request.operation != ui::SettingsEdit::increment) || + (request.column < 7 && request.operation != ui::SettingsEdit::toggle_binary) || + (request.column >= 7 && request.operation == ui::SettingsEdit::toggle_binary)) { + error = "Die Aktion passt nicht zum Einstellungsfeld."; + return false; + } + const uint8_t shown = availability[index]; + const uint8_t raw_value = sound_cell && sound_capabilities_ ? uint8_t(raw[index] & 0x7f) : raw[index]; + if (request.column < 7 && ((shown & 0x80) || raw_value >= 2)) { + error = "Dieses Einstellungsfeld ist im aktuellen Modus gesperrt."; + return false; + } + const uint8_t old = raw_value; + uint8_t next = old; + if (request.operation == ui::SettingsEdit::toggle_binary) { + // Inventory of actual current consumers: direct match-engine buttons, + // matchday/season flags and the live-scene switch. Other cells are not + // made writable merely because the Original UI displayed a cell. + // Tie the write whitelist to the concrete consumer ranges. League + // remapping reads rows 0..4, columns 0..3; matchday display kinds 1/2 + // map to columns 0..2 and rows 0..4 or 17..19. + const bool consumed = (sound_cell && sound_capabilities_.has_value()) || + (request.row == 0 && request.column == 4) || // A5: match/Sportschau sound + ((request.row <= 4 && request.column <= 3) || + ((request.row <= 4 || request.row >= 17) && request.column <= 2)) || + ((request.row == 5 || (request.row >= 9 && request.row <= 12)) && request.column == 0) || + (request.row == 1 && request.column == 4) || // B5 live-scene option + (request.row == 2 && request.column == 4) || // C5: Reality player numbers (RealityMatch_FormatError_ExecutableField) + (request.row == 5 && request.column == 5) || // F6: Source manager-match desk gate (MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField) + (request.row == 6 && request.column == 5) || // G6: transfer confirmation wait (OutcomeDelayDisabled) + (request.row == 16 && request.column == 6) || // Q7: own-club Sportschau preference (MatchdaySetup_ConsiderSportschauFixture_RuntimeField) + (request.row == 13 && request.column == 6) || // N7: Source kickoff competition list (SportschauAwards_MatchdayIntroView_RuntimeField) + (request.row == 1 && request.column == 6) || // B7: SportschauIntro intro gate (Controller_FormatError_RuntimeField) + (request.row == 2 && request.column == 6) || // C7: SportschauIntro intro-animation gate (Controller_FormatError_RuntimeField2) + (request.row == 3 && request.column == 6) || // D7: selected report progression (ReplayProgressionMode) + (request.row == 4 && request.column == 6) || // E7: Source-owned Sportschau scenes (ReplayChanceMode) + (request.row == 5 && request.column == 6) || // F7: SportschauIntro fixture-report gate (Controller_FormatError_RuntimeField3) + (request.row == 6 && request.column == 6) || // G7: MatchdayIntro player/award rating (SportschauAwards_FinishSportschauAwards_RuntimeField) + (request.row == 7 && request.column == 6) || // H7: SportschauTeamInfo competition totals (SportschauAwards_SportschauTeamInfoView_RuntimeField) + (request.row == 2 && request.column == 5) || // C6 drawer-handle behavior (CareerSession_DispatchDesktopLayout_RuntimeField) + (request.row == 3 && request.column == 5) || // D6 native desktop drag raster (CareerSession_DispatchDesktopLayout_RuntimeField2) + (request.row == 4 && request.column == 5) || // E6 always-visible shortcut bar (DeskState_FormatError_RuntimeField3) + (request.row == 7 && request.column == 5) || // H6 transfer option + (request.row == 8 && (request.column == 5 || request.column == 6)) || // I6/I7 + (request.row >= 10 && request.row <= 13 && request.column == 4) || // K5:N5 match buttons + (request.row >= 10 && request.row <= 12 && request.column == 6) || // K7:M7 presentation + (request.row == 9 && request.column == 6) || // J7 season-entrant visibility (SeasonEntrants_SeasonEntrantsFromGame_TextPointer) + (request.row == 15 && request.column == 4) || // P5 + (request.row == 16 && request.column == 4) || // Q5 + (request.row == 17 && request.column == 4); // R5: secondary leagues (CalendarState_FormatError_RuntimeField2) + if (!consumed || (old != 0 && old != 1)) { + error = "Diese Einstellung ist noch nicht verfügbar."; + return false; + } + if (request.row == 16 && request.column == 4 && + g_.season_day() >= 110 && g_.season_day() <= 230) { + error = ui::original_to_utf8(message_text(g_, ::bmh::layout::CareerSession_DispatchSettings_TextPointer)); + return false; + } + // SettingsSourceRefusal only permits re-enabling R5 while CareerSessionRuntimeField4 is zero. + // LeagueRoundCounters is the saved league_rounds block; CareerSessionRuntimeField4 is its sixth byte. + // Turning the leagues off remains possible after they have started. + if (request.row == 17 && request.column == 4 && old != 0 && + (g_.league_rounds.size() <= 5 || g_.league_rounds[5] != 0)) { + error = ui::original_to_utf8(message_text(g_, ::bmh::layout::CareerSession_DispatchSettings_TextPointer2)); + return false; + } + next = old ^ 1; + } else { + // Column8: existing presentation speeds B8:F8, H8 process budget, + // J8 postponed limit and K8 autosave. Column9 only exposes values + // already read by Main's Source live presenters or CupDrawScreen. + const bool consumed = (request.column == 7 && + ((request.row <= 6) || request.row == 7 || request.row == 9 || request.row == 10 || + (scoped_settings && request.row == 8))) || + // A9 match minutes; B9:C9 chance result; D9:E9 bookings; F9:G9 rolling ball; + // I9 cup draw; K9 Reality report; M9 preview/shootout; P9 shot. + (request.column == 8 && ((request.row >= 0 && request.row <= 6) || + request.row == 7 || request.row == 8 || request.row == 10 || request.row == 12 || request.row == 15)); + if (!consumed || old >= 200) { + error = "Diese Einstellung ist noch nicht verfügbar."; + return false; + } + if (request.column == 8) { + // SettingsSourceRefusal's ninth column is stored doubled for display. Its + // Source edit step is two raw units; decrement is enabled only + // above 1 and increment only below 0xc6 (198). Preserve odd raw + // values exactly, as the original does. + if (request.operation == ui::SettingsEdit::decrement) { + if (old <= 1) { error = "Der Zahlenwert ist bereits am Originalminimum."; return false; } + next = uint8_t(old - 2); + } else { + if (old >= 198) { error = "Der Zahlenwert ist bereits am Originalmaximum."; return false; } + next = uint8_t(old + 2); + } + } else if (request.column == 7) { + if (request.operation == ui::SettingsEdit::decrement) { + if (old == 0) { error = "Der Zahlenwert ist bereits am Originalminimum."; return false; } + next = uint8_t(old - 1); + } else { + const uint8_t limit = exe_.u8(::bmh::layout::CareerSession_DispatchSettings_RuntimeField + request.row); + if (old >= limit) { error = "Der Zahlenwert ist bereits am Originalmaximum."; return false; } + next = uint8_t(old + 1); + } + } + } + if (next == old) { error = "Die Einstellung hat sich nicht geändert."; return false; } + mem.set8(address, next); + ++revision; + return true; +} + +std::optional ModernSession::open_live_settings( + const LiveSettingsRequest& request,MatchEngine& engine,uint64_t& revision,std::string& error) { + error.clear(); + if(!calendar_advance_active_||live_settings_owner_||request.minute<0||request.minute>255|| + request.manager_slot<0||request.manager_slot>=int(g_.manager_teams.size())|| + request.revision!=revision||revision==UINT64_MAX||next_live_settings_scope_==UINT64_MAX|| + &engine.state!=&g_||&engine.game!=&game_||&engine.rand!=&rand_|| + engine.groups.empty()||engine.groups.size()!=turn_driver_.groups.size()|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=request.manager_slot|| + size_t(request.manager_slot)>=g_.manager_teams.size()|| + g_.manager_teams[size_t(request.manager_slot)]!=request.runtime_team|| + request.runtime_team<0||size_t(request.runtime_team)>=g_.team_flags.size()|| + live_overview_owner_||live_intervention_||balance_draft_||balance_dispatch_active_|| + strengths_owner_||strengths_dispatch_active_||league_family_owner_||league_pairings_draft_|| + league_pairings_dispatch_active_||other_games_owner_||other_games_dispatch_active_|| + top_scorers_owner_||top_scorers_dispatch_active_||pending_offer_dispatch_active_||market_dispatch_active_|| + transfer_offer_editor_||manager_join_||contract_quote_||stadium_.investment||stadium_.tip|| + stadium_.periphery_quote||stadium_.block_expansion) { + error="live settings: stale, nested or unauthenticated Source S request";return {}; + } + for(size_t i=0;i raw{}; + for(size_t i=0;i buttons(180); + for(size_t i=0;i ModernSession::dispatch_live_settings( + const LiveSettingsAction& action,MatchEngine& engine,uint64_t& revision,std::string& error) { + error.clear(); + if(!calendar_advance_active_||!live_settings_owner_||revision==UINT64_MAX|| + live_settings_owner_->request.revision!=revision||&engine.state!=&g_|| + &engine.game!=&game_||&engine.rand!=&rand_||engine.groups.size()!=live_settings_owner_->active_groups.size()|| + engine.referees!=live_settings_owner_->referees||modern::save_stream(g_)!=live_settings_owner_->native|| + engine.buttons!=live_settings_owner_->expected_buttons||engine.live_desk_disabled!=live_settings_owner_->expected_live_desk_disabled|| + engine.live_scene_visible!=live_settings_owner_->expected_live_scene_visible||club_modal_runtime_!=live_settings_owner_->expected_runtime|| + rand_.seed()!=live_settings_owner_->rand_seed||rand_.calls()!=live_settings_owner_->rand_calls|| + game_.seed()!=live_settings_owner_->game_seed||game_.calls()!=live_settings_owner_->game_calls|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=live_settings_owner_->request.manager_slot|| + size_t(live_settings_owner_->request.manager_slot)>=g_.manager_teams.size()|| + g_.manager_teams[size_t(live_settings_owner_->request.manager_slot)]!=live_settings_owner_->request.runtime_team) { + error="live settings: stale owner or no longer at the Source observer";return {}; + } + for(size_t i=0;iactive_groups[i].first|| + engine.groups[i].fixtures!=live_settings_owner_->active_groups[i].second|| + engine.groups[i].desc!=turn_driver_.groups[i].desc||engine.groups[i].fixtures!=turn_driver_.groups[i].fixtures) { + error="live settings: active Source match list changed";return {}; + } + const auto current=*live_settings_owner_; + struct LiveSettingsBoundaryScope { + bool& active;bool previous; + explicit LiveSettingsBoundaryScope(bool& value):active(value),previous(value){active=false;} + ~LiveSettingsBoundaryScope(){active=previous;} + } boundary(calendar_advance_active_); + std::optional write_rollback; + const uint64_t revision_before_action=revision; + try { + if(const auto* write=std::get_if(&action)) { + if(write->owner_sequence!=current.request.sequence||write->write.manager_slot!=current.request.manager_slot|| + write->write.revision!=revision) + throw FormatError("live settings: write belongs to another Source owner"); + write_rollback=g_; + live_settings_dispatch_active_=true; + struct Reset { bool& active;~Reset(){active=false;} } reset{live_settings_dispatch_active_}; + uint64_t staged_revision=revision; + if(!dispatch_settings(write->write,staged_revision,error)) + throw FormatError(error.empty()?"live settings: Source cell write rejected":error); + ModernState staged=std::move(g_); + g_=*write_rollback; + std::array raw{}; + for(size_t i=0;i buttons(180); + for(size_t i=0;i(&action)) { + if(file->owner_sequence!=current.request.sequence||file->request.manager_slot!=current.request.manager_slot|| + file->request.origin_item_id!=-1||file->request.revision!=revision||revision==UINT64_MAX) + throw FormatError("live settings: file request belongs to another owner"); + ModernState staged=g_;bool loaded=false; + if(!apply_settings_file(file->request,current.request.manager_slot,-1,staged,loaded,error)) + throw FormatError(error.empty()?"live settings: .EIN request rejected":error); + auto state=ui::settings_from_game(staged,current.request.manager_slot,revision+1,exe_,sound_capabilities_); + ui::SettingsScreen validate(data_directory_,state); + std::vector buttons(180); + for(size_t i=0;i(action); + if(close.owner!=current.request||close.owner.sequence!=current.request.sequence||close.owner.revision!=revision) + throw FormatError("live settings: stale or mismatched Source close"); + if(revision==UINT64_MAX)throw FormatError("live settings: revision exhausted"); + ModernState next=g_;auto runtime=club_modal_runtime_; + std::array raw{}; + for(size_t i=0;i>(8*i))); + source_runtime_set_byte(next,runtime,::bmh::layout::CareerSession_FormatError_ExecutableField8,1); // EndPhase requests its normal redraw on return. + auto state=ui::settings_from_game(next,current.request.manager_slot,revision+1,exe_,sound_capabilities_); + ui::SettingsScreen validate(data_directory_,state); + std::vector buttons(180); + for(size_t i=0;i(desk_settings_owner_->owner) : std::nullopt, + desk_settings_owner_ ? desk_settings_owner_->initial_h8 : uint8_t(0), + next_desk_settings_scope_,revision}; +} + +bool ModernSession::apply_settings_file(const ui::SaveLoadRequest& request,int manager_slot,int origin_item_id, + ModernState& staged,bool& loaded,std::string& error) const { + constexpr size_t kBytes=180; + loaded=false; + if(request.file_kind!=ui::SaveLoadFileKind::settings||request.manager_slot!=manager_slot|| + request.origin_item_id!=origin_item_id||request.path.filename().empty()) { + error="invalid_settings_file_owner";return false; + } + std::string extension=request.path.extension().string(); + std::transform(extension.begin(),extension.end(),extension.begin(), + [](unsigned char c){return char(std::tolower(c));}); + if (extension != (content::find(data_directory_) ? ".obsettings" : ".ein")) { + error = "invalid_settings_file_extension"; + return false; + } + const uint32_t base=::bmh::layout::LeaguePresentationOptions; + if(!staged.memory.has(base+uint32_t(kBytes-1))) {error="settings_file_memory_unavailable";return false;} + std::error_code ec; + const auto status=std::filesystem::symlink_status(request.path,ec); + if(!ec&&std::filesystem::is_symlink(status)) {error="settings_file_target_is_symlink";return false;} + if(request.action==ui::SaveLoadAction::load) { + Bytes bytes; + try { + bytes = content::find(data_directory_) + ? content::load_preferences(request.path, "settings", kBytes) + : read_file(request.path); + } catch (const std::exception &) { + error = "settings_file_read_failed"; + return false; + } + if(bytes.size()!=kBytes) {error="settings_file_wrong_size";return false;} + for(size_t i=0;i raw{}; + for(size_t i=0;i(bytes.data()),std::streamsize(bytes.size()));file.flush(); + if(!file) {error="settings_file_write_failed";return false;} + } catch(const std::exception&) {error="settings_file_write_failed";return false;} + error.clear();return true; +} + +void ModernSession::restore_desk_settings_checkpoint(DeskSettingsCheckpoint checkpoint,uint64_t& revision) { + g_=std::move(checkpoint.state);club_modal_runtime_=std::move(checkpoint.runtime); + desk_settings_owner_.reset(); + if(checkpoint.owner) { + DeskSettingsOwnerState restored;restored.owner=*checkpoint.owner; + restored.initial_h8=checkpoint.initial_h8;restored.native=modern::save_stream(g_); + restored.expected_runtime=club_modal_runtime_;restored.rand_seed=rand_.seed(); + restored.game_seed=game_.seed();restored.rand_calls=rand_.calls();restored.game_calls=game_.calls(); + desk_settings_owner_=std::move(restored); + } + next_desk_settings_scope_=checkpoint.next_scope;revision=checkpoint.revision; +} + +std::optional ModernSession::open_desk_settings( + const ui::DeskRequest& request,uint64_t& revision,std::string& error) { + error.clear(); + if(request.kind!=ui::DeskRequestKind::open_menu||request.menu_kind!=19||request.value!=-1|| + request.item_id<0||request.item_id>=54||request.revision!=revision||revision==UINT64_MAX|| + next_desk_settings_scope_==UINT64_MAX||request.manager_slot<0||request.manager_slot>3|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=request.manager_slot|| + size_t(request.manager_slot)>=g_.manager_teams.size()|| + live_settings_owner_||desk_settings_owner_||live_overview_owner_||live_intervention_|| + balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_|| + league_family_owner_||league_family_teaminfo_active_||league_pairings_draft_|| + league_pairings_dispatch_active_||other_games_owner_||other_games_dispatch_active_|| + top_scorers_owner_||top_scorers_dispatch_active_||opportunities_owner_||opportunities_dispatch_active_|| + pending_offer_dispatch_active_||market_dispatch_active_||transfer_offer_editor_||manager_join_|| + contract_quote_||advertising_renewal_dispatch_active_||stadium_.investment||stadium_.tip|| + stadium_.periphery_quote||stadium_.block_expansion|| + calendar_advance_active_||career_complete()) { + error="desk settings: stale, nested or unauthenticated menu-19 request";return {}; + } + try { + const auto desk=desktop_projection(revision); + const auto source=std::find_if(desk.items.begin(),desk.items.end(),[&](const ui::DeskItem& item) { + return item.id==request.item_id; + }); + if(source==desk.items.end()||source->kind!=19||source->disabled||desk.manager_slot!=request.manager_slot) { + error="desk settings: menu-19 source item is not currently enabled";return {}; + } + if(!g_.memory.has(::bmh::layout::LeaguePresentationOptions+179)||!g_.memory.has(::bmh::layout::GameMode)||!g_.memory.has(::bmh::layout::CompetitionSelection)) { + error="desk settings: Source settings block is incomplete";return {}; + } + ModernState staged=g_;auto runtime=club_modal_runtime_; + std::array raw{}; + for(size_t i=0;i ModernSession::dispatch_desk_settings( + const DeskSettingsAction& action,uint64_t& revision,std::string& error) { + error.clear(); + if(!desk_settings_owner_||revision==UINT64_MAX||desk_settings_owner_->owner.revision!=revision|| + modern::save_stream(g_)!=desk_settings_owner_->native||club_modal_runtime_!=desk_settings_owner_->expected_runtime|| + rand_.seed()!=desk_settings_owner_->rand_seed||rand_.calls()!=desk_settings_owner_->rand_calls|| + game_.seed()!=desk_settings_owner_->game_seed||game_.calls()!=desk_settings_owner_->game_calls|| + !g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=desk_settings_owner_->owner.manager_slot) { + error="desk settings: stale owner or changed session";return {}; + } + const auto current=*desk_settings_owner_; + const uint64_t revision_before=revision; + std::optional rollback; + try { + if(const auto* write=std::get_if(&action)) { + if(write->owner_sequence!=current.owner.sequence||write->write.manager_slot!=current.owner.manager_slot|| + write->write.revision!=revision)throw FormatError("desk settings: write belongs to another owner"); + rollback=g_;desk_settings_dispatch_active_=true; + struct Reset { bool& active;~Reset(){active=false;} } reset{desk_settings_dispatch_active_}; + uint64_t staged_revision=revision; + if(!dispatch_settings(write->write,staged_revision,error)) + throw FormatError(error.empty()?"desk settings: Source write rejected":error); + ModernState staged=std::move(g_);g_=*rollback; + std::array raw{}; + for(size_t i=0;i(&action)) { + if(file->owner_sequence!=current.owner.sequence||file->request.manager_slot!=current.owner.manager_slot|| + file->request.revision!=revision||file->request.origin_item_id!=current.owner.source_item_id|| + revision==UINT64_MAX) + throw FormatError("desk settings: file request belongs to another owner"); + ModernState staged=g_;bool loaded=false; + if(!apply_settings_file(file->request,current.owner.manager_slot,current.owner.source_item_id, + staged,loaded,error)) + throw FormatError(error.empty()?"desk settings: .EIN request rejected":error); + auto state=ui::settings_from_game(staged,current.owner.manager_slot,revision+1,exe_,sound_capabilities_); + ui::SettingsScreen validate(data_directory_,state); + DeskSettingsOwnerState updated=current;updated.owner.revision=revision+1; + updated.native=modern::save_stream(staged);updated.expected_runtime=club_modal_runtime_; + updated.rand_seed=rand_.seed();updated.game_seed=game_.seed(); + updated.rand_calls=rand_.calls();updated.game_calls=game_.calls(); + DeskSettingsDispatch result{updated.owner,false,std::move(state)}; + g_=std::move(staged);desk_settings_owner_=std::move(updated);++revision; + return result; + } + const auto& close=std::get(action); + if(close.owner!=current.owner||close.owner.revision!=revision) + throw FormatError("desk settings: stale close request"); + ModernState next=g_;auto runtime=club_modal_runtime_; + std::array raw{}; + for(size_t i=0;i(int(new_h8)-int(current.initial_h8)); + const uint32_t remaining=source_runtime_u32(next,runtime,exe_,::bmh::layout::CareerSession_FormatError_ExecutableField2); + const uint32_t adjusted=remaining+uint32_t(int32_t(delta)*60); + for(uint32_t i=0;i<4;++i) + source_runtime_set_byte(next,runtime,::bmh::layout::CareerSession_FormatError_ExecutableField2+i,uint8_t(adjusted>>(8*i))); + } + next.live_scene=uint8_t(1-(raw[13]&1))!=0; + source_runtime_set_byte(next,runtime,::bmh::layout::CareerSession_DispatchLiveSubstitution_ExecutableField,next.memory.u8(::bmh::layout::CareerSession_FormatError_RuntimeField2)); + uint32_t code=0; + for(uint32_t i=0;i<6;++i)code=code*10+next.memory.u8(::bmh::layout::CareerSession_FormatError_RuntimeField + (i+14)*9); + for(uint32_t i=0;i<4;++i)source_runtime_set_byte(next,runtime,::bmh::layout::CareerSession_FormatError_RuntimeField9+i,uint8_t(code>>(8*i))); + auto state=ui::settings_from_game(next,current.owner.manager_slot,revision+1,exe_,sound_capabilities_); + ui::SettingsScreen validate(data_directory_,state); + DeskSettingsDispatch result{current.owner,true,std::move(state)};result.owner.revision=revision+1; + g_=std::move(next);club_modal_runtime_=std::move(runtime);desk_settings_owner_.reset();++revision; + return result; + } catch(const std::exception& e) { + if(rollback) {g_=std::move(*rollback);revision=revision_before;desk_settings_owner_=current;} + error=e.what();return {}; + } +} + +std::optional ModernSession::check_advertising_renewal(int manager_slot, int display_slot, + uint64_t& revision, std::string& error) { + error.clear(); + if (advertising_renewal_dispatch_active_) { + error = "advertising_renewal_active"; + return std::nullopt; + } + if (!g_.memory.has(::bmh::layout::ActiveManager) || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() || + int(g_.memory.u8(::bmh::layout::ActiveManager)) != manager_slot || revision == std::numeric_limits::max()) { + error = "Diese Werbeaktion ist nicht mehr aktuell."; + return std::nullopt; + } + AdvertisingRenewal renewal = modern::check_advertising_renewal(g_, manager_slot, display_slot, rand_); + if (renewal.status == AdvertisingRenewal::Status::invalid) { + error = "Diese Werbefläche gibt es nicht."; + return std::nullopt; + } + if (renewal.status != AdvertisingRenewal::Status::not_expired) ++revision; + return renewal; +} + +bool ModernSession::answer_advertising_renewal(int manager_slot, int contract_slot, bool renew, uint64_t& revision, + std::string& error) { + error.clear(); + if (advertising_renewal_dispatch_active_) { + error = "advertising_renewal_active"; + return false; + } + if (!g_.memory.has(::bmh::layout::ActiveManager) || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() || + int(g_.memory.u8(::bmh::layout::ActiveManager)) != manager_slot || revision == std::numeric_limits::max() || + !modern::answer_advertising_renewal(g_, manager_slot, contract_slot, renew)) { + error = "Diese Vertragsverlängerung ist nicht mehr aktuell."; + return false; + } + ++revision; + return true; +} + + + +ModernSession::AdvertisingSessionCheckpoint ModernSession::advertising_session_checkpoint(uint64_t revision) const { + AdvertisingSessionCheckpoint c; + c.state=g_; c.game=game_; c.rand=rand_; c.driver=turn_driver_; + c.desk_callargs=source_desk_callargs_; c.saved_turn_error=saved_turn_error_; + c.completed_results=completed_results_; c.lineup_manager=lineup_entry_manager_; + c.lineup_club=lineup_entry_club_; c.managers=managers_; c.stock_tip=last_stock_tip_; + c.property_notice=last_property_notice_; c.credit_notice=last_credit_notice_; + c.stadium=stadium_; c.next_stadium_scope=next_stadium_scope_; + c.contract_quote=contract_quote_; c.next_contract_quote_id=next_contract_quote_id_; + c.last_contract_request_id=last_contract_request_id_; c.options_applied=options_applied_; + c.pending_offer_active=pending_offer_dispatch_active_; c.market_active=market_dispatch_active_; + c.pairings_active=league_pairings_dispatch_active_; c.family_teaminfo_active=league_family_teaminfo_active_; + c.strengths_active=strengths_dispatch_active_; c.top_scorers_active=top_scorers_dispatch_active_; + c.other_games_active=other_games_dispatch_active_; c.balance_active=balance_dispatch_active_; + c.calendar_active=calendar_advance_active_; c.next_other_games_scope=next_other_games_scope_; + c.other_games_owner=other_games_owner_; c.other_games_selection=other_games_selection_; + c.next_balance_scope=next_balance_scope_; c.balance=balance_draft_; + c.next_strengths_scope=next_strengths_scope_; c.strengths=strengths_owner_; + c.family=league_family_owner_; c.next_family_id=next_league_family_id_; + c.next_top_scorers_scope=next_top_scorers_scope_; c.top_scorers=top_scorers_owner_; + c.pairings_scope=league_pairings_scope_; c.pairings=league_pairings_draft_; + c.transfer_editor=transfer_offer_editor_; c.poach=poach_; + c.transfer_offer_revision=transfer_offer_revision_; c.pending_hooks=pending_offer_hooks_; + c.pending_policy=pending_offer_entry_policy_; c.runtime=club_modal_runtime_; + c.last_request_id=last_advertising_request_id_; c.manager_join=manager_join_; + c.revision=revision; c.session_id=session_id_; + return c; +} + +void ModernSession::restore_advertising_session_checkpoint(AdvertisingSessionCheckpoint c) { + g_=std::move(c.state); game_=c.game; rand_=c.rand; turn_driver_=std::move(c.driver); + source_desk_callargs_=std::move(c.desk_callargs); saved_turn_error_=std::move(c.saved_turn_error); + completed_results_=std::move(c.completed_results); lineup_entry_manager_=c.lineup_manager; + lineup_entry_club_=c.lineup_club; managers_=std::move(c.managers); last_stock_tip_=c.stock_tip; + last_property_notice_=std::move(c.property_notice); last_credit_notice_=std::move(c.credit_notice); + stadium_=std::move(c.stadium); next_stadium_scope_=c.next_stadium_scope; + contract_quote_=std::move(c.contract_quote); next_contract_quote_id_=c.next_contract_quote_id; + last_contract_request_id_=c.last_contract_request_id; options_applied_=c.options_applied; + pending_offer_dispatch_active_=c.pending_offer_active; market_dispatch_active_=c.market_active; + league_pairings_dispatch_active_=c.pairings_active; league_family_teaminfo_active_=c.family_teaminfo_active; + strengths_dispatch_active_=c.strengths_active; top_scorers_dispatch_active_=c.top_scorers_active; + other_games_dispatch_active_=c.other_games_active; balance_dispatch_active_=c.balance_active; + calendar_advance_active_=c.calendar_active; next_other_games_scope_=c.next_other_games_scope; + other_games_owner_=std::move(c.other_games_owner); other_games_selection_=c.other_games_selection; + next_balance_scope_=c.next_balance_scope; balance_draft_=std::move(c.balance); + next_strengths_scope_=c.next_strengths_scope; strengths_owner_=std::move(c.strengths); + league_family_owner_=std::move(c.family); next_league_family_id_=c.next_family_id; + next_top_scorers_scope_=c.next_top_scorers_scope; top_scorers_owner_=std::move(c.top_scorers); + league_pairings_scope_=c.pairings_scope; league_pairings_draft_=std::move(c.pairings); + transfer_offer_editor_=std::move(c.transfer_editor); poach_=std::move(c.poach); + transfer_offer_revision_=c.transfer_offer_revision; pending_offer_hooks_=std::move(c.pending_hooks); + pending_offer_entry_policy_=c.pending_policy; club_modal_runtime_=std::move(c.runtime); + last_advertising_request_id_=c.last_request_id; manager_join_=std::move(c.manager_join); +} + +bool ModernSession::advertising_session_unchanged(const AdvertisingSessionCheckpoint& c, + uint64_t revision) const { + const auto byte_same=[&](uint32_t at) { + const bool live_has=g_.memory.has(at), saved_has=c.state.memory.has(at); + return live_has==saved_has && (!live_has || g_.memory.u8(at)==c.state.memory.u8(at)); + }; + const bool manager_ids_same = managers_.size()==c.managers.size() && + std::equal(managers_.begin(),managers_.end(),c.managers.begin(),[](const auto& a,const auto& b) { + return a.slot==b.slot && a.master_club==b.master_club && a.runtime_club==b.runtime_club; + }); + return modern::save_stream(g_)==modern::save_stream(c.state) && same_strengths_runtime_state(g_,c.state) && + g_.manager_teams==c.state.manager_teams && byte_same(::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField) && byte_same(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField) && + rand_.seed()==c.rand.seed() && rand_.calls()==c.rand.calls() && + game_.seed()==c.game.seed() && game_.calls()==c.game.calls() && + turn_driver_.stage==c.driver.stage && source_desk_callargs_==c.desk_callargs && + lineup_entry_manager_==c.lineup_manager && lineup_entry_club_==c.lineup_club && manager_ids_same && + session_id_==c.session_id && last_advertising_request_id_==c.last_request_id && revision==c.revision && + club_modal_runtime_==c.runtime && + pending_offer_dispatch_active_==c.pending_offer_active && market_dispatch_active_==c.market_active && + league_pairings_dispatch_active_==c.pairings_active && league_family_teaminfo_active_==c.family_teaminfo_active && + strengths_dispatch_active_==c.strengths_active && top_scorers_dispatch_active_==c.top_scorers_active && + other_games_dispatch_active_==c.other_games_active && balance_dispatch_active_==c.balance_active && + calendar_advance_active_==c.calendar_active && + bool(other_games_owner_)==bool(c.other_games_owner) && bool(balance_draft_)==bool(c.balance) && + bool(strengths_owner_)==bool(c.strengths) && bool(league_family_owner_)==bool(c.family) && + bool(top_scorers_owner_)==bool(c.top_scorers) && bool(league_pairings_draft_)==bool(c.pairings) && + bool(transfer_offer_editor_)==bool(c.transfer_editor) && bool(poach_)==bool(c.poach) && + bool(manager_join_)==bool(c.manager_join) && bool(stadium_.opened)==bool(c.stadium.opened) && + bool(contract_quote_)==bool(c.contract_quote) && + next_other_games_scope_==c.next_other_games_scope && next_balance_scope_==c.next_balance_scope && + next_strengths_scope_==c.next_strengths_scope && next_league_family_id_==c.next_family_id && + next_top_scorers_scope_==c.next_top_scorers_scope && league_pairings_scope_==c.pairings_scope && + next_stadium_scope_==c.next_stadium_scope && next_contract_quote_id_==c.next_contract_quote_id && + last_contract_request_id_==c.last_contract_request_id && transfer_offer_revision_==c.transfer_offer_revision; +} + +std::optional ModernSession::dispatch_advertising_renewal( + const ui::AdvertisingRequest& request, uint64_t& revision, std::string& error, + const AdvertisingRenewalPresenter& presenter) { + error.clear(); + const auto competing_owner = [&] { + return pending_offer_dispatch_active_ || market_dispatch_active_ || league_pairings_dispatch_active_ || + league_family_teaminfo_active_ || strengths_dispatch_active_ || top_scorers_dispatch_active_ || + other_games_dispatch_active_ || balance_dispatch_active_ || calendar_advance_active_ || + balance_draft_.has_value() || strengths_owner_.has_value() || top_scorers_owner_.has_value() || + other_games_owner_.has_value() || league_family_owner_.has_value() || league_pairings_draft_.has_value() || + manager_join_.has_value() || transfer_offer_editor_.has_value() || poach_.has_value() || + stadium_.opened || stadium_.investment.has_value() || stadium_.tip.has_value() || + stadium_.periphery_quote.has_value() || stadium_.selection_status.has_value() || + stadium_.block_expansion.has_value() || contract_quote_.has_value() || + (turn_driver_.stage!=TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage!=TurnDriver::Stage::SeasonEndDesk); + }; + if (advertising_renewal_dispatch_active_ || competing_owner()) { + error = "Eine andere Session-Aktion oder ein konkurrierender Screen ist aktiv."; + return std::nullopt; + } + if (!presenter || request.kind != ui::AdvertisingActionKind::check_renewal || + request.request_id == 0 || request.request_id <= last_advertising_request_id_ || + request.manager_slot < 0 || request.manager_slot > 3 || + !g_.memory.has(::bmh::layout::ActiveManager) || int(g_.memory.u8(::bmh::layout::ActiveManager)) != request.manager_slot || + size_t(request.manager_slot) >= g_.manager_teams.size() || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || + request.revision != revision || revision == std::numeric_limits::max() || + request.renewal_display_slot < 0 || request.renewal_display_slot > 15 || + request.renewal_contract_slot < 0 || request.renewal_contract_slot > 15 || + request.offer != AdvertisingOfferRequest{} || request.spending != AdvertisingSpendingRequest{}) { + error = "Diese Werbeaktion ist nicht mehr aktuell."; + return std::nullopt; + } + const size_t record = size_t(request.manager_slot) * 0xb0c + 0xa34 + + size_t(request.renewal_contract_slot) * 0x0c; + if (record + 12 > g_.manager_records.size() || + !std::equal(request.renewal_expected_contract.begin(), request.renewal_expected_contract.end(), + g_.manager_records.begin() + std::ptrdiff_t(record)) || + (request.renewal_expected_contract[6] & 0x7f) == 0 || request.renewal_expected_contract[5] != 0) { + error = "Diese Vertragsverlängerung ist nicht mehr aktuell."; + return std::nullopt; + } + + const auto checkpoint = advertising_session_checkpoint(revision); + const auto restore = [&] { + restore_advertising_session_checkpoint(checkpoint); + revision = checkpoint.revision; + }; + advertising_renewal_dispatch_active_ = true; + struct ActiveReset { bool& active; ~ActiveReset() { active = false; } } active_reset{advertising_renewal_dispatch_active_}; + try { + ModernState staged = g_; + WatcomRandom staged_rand = rand_; + auto renewal = modern::check_advertising_renewal(staged, request.manager_slot, + request.renewal_display_slot, staged_rand); + if (renewal.status == AdvertisingRenewal::Status::invalid || + renewal.contract_slot != request.renewal_contract_slot || + renewal.status == AdvertisingRenewal::Status::not_expired) { + restore(); error = "Diese Vertragsverlängerung ist nicht mehr aktuell."; return std::nullopt; + } + const auto presentation = presenter(staged, renewal); + if (!advertising_session_unchanged(checkpoint, revision)) { + restore(); error = "Die Session wurde während des Werbedialogs verändert."; return std::nullopt; + } + // Always restore the snapshot after presentation. This makes the rollback + // unconditional, including hidden owners, IDs and runtime maps; only the + // staged Source result below is allowed to become live. + restore(); + if (renewal.status == AdvertisingRenewal::Status::offered) { + if (presentation != AdvertisingRenewalPresentation::renew && + presentation != AdvertisingRenewalPresentation::decline) { + error = "Die Vertragsverlängerung wurde nicht bestätigt."; return std::nullopt; + } + const bool renew = presentation == AdvertisingRenewalPresentation::renew; + if (!modern::answer_advertising_renewal(staged, request.manager_slot, + request.renewal_contract_slot, renew)) { + error = "Diese Vertragsverlängerung ist nicht mehr aktuell."; return std::nullopt; + } + } else if (renewal.status == AdvertisingRenewal::Status::declined_by_sponsor) { + if (presentation != AdvertisingRenewalPresentation::acknowledged) { + error = "Die Sponsorabsage wurde nicht bestätigt."; return std::nullopt; + } + } else { + error = "Unbekannter Source-Verlängerungsstatus."; return std::nullopt; + } + g_ = std::move(staged); + rand_ = staged_rand; + last_advertising_request_id_ = request.request_id; + ++revision; + error.clear(); + return renewal; + } catch (const std::exception&) { + restore(); error = "Die Vertragsverlängerung konnte nicht bestätigt werden."; return std::nullopt; + } catch (...) { + restore(); error = "Die Vertragsverlängerung konnte nicht bestätigt werden."; return std::nullopt; + } +} + +bool ModernSession::apply_advertising(const ui::AdvertisingRequest& request, uint64_t& revision, + std::string& error, const AdvertisingAcknowledge& acknowledge, + const AdvertisingRenewalPresenter& presenter) { + auto before = advertising_checkpoint(); + const auto old_revision = revision; + const auto restore = [&] { + restore_advertising_checkpoint(std::move(before)); + revision = old_revision; + }; + try { + AdvertisingActionResult result; + if (request.kind == ui::AdvertisingActionKind::check_renewal) { + if (!presenter) { + error = "Die Original-Verlängerungsfrage ist nicht verfügbar."; + restore(); return false; + } + result.renewal = dispatch_advertising_renewal(request, revision, error, presenter); + if (!result.renewal) { restore(); return false; } + } else if (!dispatch_advertising(request, revision, error, &result.spending)) { + restore(); return false; + } + if (acknowledge) acknowledge(result); + return true; + } catch (...) { + restore(); + throw; + } +} + +bool ModernSession::accept_advertising_selection(const ui::AdvertisingState& observed, + int display_slot, int raw_offer, uint64_t request_id, uint64_t& revision, std::string& error) { + if (display_slot < 0 || display_slot >= int(observed.offers.size())) { + error = "Dieses Werbeangebot kann nicht übernommen werden."; return false; + } + const auto& view = observed.offers[size_t(display_slot)]; + const auto candidate = std::find_if(view.offers.begin(), view.offers.end(), + [&](const auto& offer) { return offer.raw_slot == raw_offer; }); + if (candidate == view.offers.end()) { + error = "Dieses Werbeangebot kann nicht übernommen werden."; return false; + } + ui::AdvertisingRequest request; + request.request_id = request_id; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_team_id; + request.revision = observed.revision; + request.kind = ui::AdvertisingActionKind::accept_offer; + request.offer.manager = observed.manager_slot; + request.offer.display_slot = display_slot; + request.offer.contract_slot = view.contract_slot; + request.offer.expected_contract = view.contract_bytes; + request.offer.raw_slot = candidate->raw_slot; + request.offer.expected_offer = candidate->bytes; + return apply_advertising(request, revision, error); +} + +bool ModernSession::set_advertising_budget(const ui::AdvertisingState& observed, int target_slot, + uint32_t amount, uint64_t request_id, uint64_t& revision, std::string& error, + AdvertisingSpendingResult& result) { + if (target_slot < 16 || target_slot > 18) { + error = "Dieser Werbeausgabenauftrag ist nicht mehr gültig."; return false; + } + const auto& view = observed.spending[size_t(target_slot - 16)]; + ui::AdvertisingRequest request; + request.request_id = request_id; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_team_id; + request.revision = observed.revision; + request.kind = ui::AdvertisingActionKind::set_spending; + request.spending.manager = observed.manager_slot; + request.spending.target_slot = target_slot; + request.spending.amount = amount; + request.spending.expected_amount = view.current_amount; + request.spending.expected_delivery_weeks = view.delivery_weeks; + return apply_advertising(request, revision, error, + [&](const AdvertisingActionResult& applied) { result = applied.spending; }); +} + +bool ModernSession::dispatch_advertising(const ui::AdvertisingRequest& request, uint64_t& revision, + std::string& error, AdvertisingSpendingResult* spending_result) { + if (advertising_renewal_dispatch_active_) { error = "advertising_renewal_active"; return false; } + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + error.clear(); + if (spending_result) *spending_result = {}; + const int manager = request.manager_slot; + if (!g_.memory.has(::bmh::layout::ActiveManager) || manager < 0 || manager > 3 || + size_t(manager) >= g_.manager_teams.size() || int(g_.memory.u8(::bmh::layout::ActiveManager)) != manager || + request.runtime_club != g_.manager_teams[size_t(manager)] || + request.revision != revision || revision == std::numeric_limits::max() || + request.request_id == 0 || request.request_id <= last_advertising_request_id_ || + request.kind == ui::AdvertisingActionKind::check_renewal || + request.renewal_display_slot != -1 || request.renewal_contract_slot != -1 || + request.renewal_expected_contract != std::array{}) { + error = "Diese Werbeaktion ist nicht mehr aktuell."; + return false; + } + if (request.kind == ui::AdvertisingActionKind::accept_offer) { + if (request.offer.manager != manager || request.spending != AdvertisingSpendingRequest{}) { + error = "Das Werbeangebot enthält fremde Ausgabedaten."; + return false; + } + const auto result = modern::accept_advertising_offer(g_, request.offer); + if (result.status != AdvertisingOfferStatus::accepted) { + error = result.status == AdvertisingOfferStatus::unsupported_extension + ? "Diese Vertragsverlängerung ist noch nicht verfügbar." + : "Dieses Werbeangebot kann nicht übernommen werden."; + return false; + } + } else if (request.kind == ui::AdvertisingActionKind::set_spending) { + if (request.spending.manager != manager || request.offer != AdvertisingOfferRequest{}) { + error = "Der Ausgabenauftrag enthält fremde Vertragsdaten."; + return false; + } + const auto result = modern::set_advertising_spending(g_, request.spending, rand_); + if (spending_result) *spending_result = result; + if (result.status != AdvertisingSpendingStatus::accepted && + result.status != AdvertisingSpendingStatus::no_change && + result.status != AdvertisingSpendingStatus::insufficient_funds) { + error = "Dieser Werbeausgabenauftrag ist nicht mehr gültig."; + return false; + } + // Insufficient funds is an Original handled response: it clears the old + // merchandise amount, but neither books cash nor draws a delivery delay. + } else { + error = "Unbekannte Werbeaktion."; + return false; + } + last_advertising_request_id_ = request.request_id; + ++revision; + return true; +} + +bool ModernSession::dispatch_contract(const ui::ContractRequest& request, uint64_t& revision, + ui::ContractActionResult& result, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const auto reject = [&](std::string message) { error = std::move(message); return false; }; + const auto original_text = [&](uint32_t address) { + return ui::original_to_utf8(texts_[(address - ::bmh::layout::TextPointerTable) / 4]); + }; + const int active = g_.memory.has(::bmh::layout::ActiveManager) ? int(g_.memory.u8(::bmh::layout::ActiveManager)) : -1; + if (request.request_id == 0 || request.request_id <= last_contract_request_id_ || + request.revision != revision || revision == std::numeric_limits::max() || + request.manager_slot != active || active < 0 || active > 3 || + size_t(active) >= g_.manager_teams.size() || request.runtime_club != g_.manager_teams[size_t(active)] || + request.runtime_club == no_team()) + return reject("Der Vertragsauftrag gehört zu einem veralteten Manager oder Stand."); + const bool team_bonuses = request.kind == ui::ContractActionKind::submit_bonuses && request.row == -1; + const SquadRange range = squad_range(request.runtime_club); + int player = -1; + size_t board = 0; + if (team_bonuses) { + if (request.player_id != -1 || request.quote_id != 0) + return reject("Der Teamprämienauftrag enthält eine fremde Spieleridentität."); + } else { + if (request.row < 0 || size_t(request.row) >= range.count || request.row >= 24 || + range.first + size_t(request.row) >= g_.squad_slots.size()) + return reject("Der ausgewählte Kaderplatz ist nicht mehr gültig."); + player = g_.squad_slots[range.first + size_t(request.row)] & 0x0fff; + if (player == 0x0fff || player != request.player_id || size_t(player) >= g_.players.size()) + return reject("Der Spieler gehört nicht mehr zu diesem Kaderplatz."); + board = size_t(active) * 0x840 + size_t(request.row) * 0x58; + if (board + 0x58 > g_.tactics.size()) return reject("Der Vertragsdatensatz ist unvollständig."); + } + if (request.kind == ui::ContractActionKind::request_demands) { + if (request.quote_id != 0 || request.term_column != 0 || request.demand != 0 || request.monthly_salary != 0 || + request.insurance_months != 0 || std::any_of(request.proposed_bonuses.begin(), + request.proposed_bonuses.end(), [](uint8_t b) { return b != 0; })) + return reject("Der Forderungsauftrag enthält ungültige Angebotsdaten."); + ModernState staged_game = g_; + WatcomRandom staged_rand = rand_; + std::array demands{}; + try { demands = modern::contract_demands(staged_game, active, request.row, true, staged_rand); } + catch (const std::exception&) { return reject("Die Gehaltsforderungen konnten nicht ermittelt werden."); } + if (modern::save_stream(staged_game) != modern::save_stream(g_)) + return reject("Die Forderungsabfrage hat unerwartet den Spielstand verändert."); + rand_ = staged_rand; + ++revision; + ContractQuoteRecord quote; + quote.quote_id = next_contract_quote_id_++; + quote.request_id = request.request_id; + quote.revision = revision; + quote.manager_slot = active; + quote.runtime_club = request.runtime_club; + quote.row = request.row; + quote.player_id = player; + quote.demands = demands; + contract_quote_ = quote; + last_contract_request_id_ = request.request_id; + result.success = true; + result.quote_id = quote.quote_id; + result.demands = demands; + return true; + } + if (!team_bonuses && (!contract_quote_ || request.quote_id != contract_quote_->quote_id || + request.request_id <= contract_quote_->request_id || request.revision != contract_quote_->revision || + request.manager_slot != contract_quote_->manager_slot || request.runtime_club != contract_quote_->runtime_club || + request.row != contract_quote_->row || player != contract_quote_->player_id)) + return reject("Dieser Auftrag ist nicht mehr an die aktuelle Verhandlung gebunden."); + const bool full_mode = g_.memory.u8(::bmh::layout::GameMode) == 3; + if (request.kind == ui::ContractActionKind::insure_player) { + if (!full_mode || request.term_column >= 4 || request.insurance_months < 1 || request.insurance_months > 60 || + request.demand != 0 || request.monthly_salary != 0 || + std::any_of(request.proposed_bonuses.begin(), request.proposed_bonuses.end(), [](uint8_t b) { return b != 0; })) + return reject("Der Versicherungsauftrag enthält ungültige Daten."); + // ContractBonuses checks these in this order and uses the corresponding Original dialog. + if (g_.tactics[board + 0x0b] & 0x20) return reject(original_text(::bmh::layout::CareerSession_Reject_TextPointer)); + if (g_.tactics[board + 0x0b] & 0x40) return reject(original_text(::bmh::layout::CareerSession_Reject_TextPointer2)); + if (g_.tactics[board + 0x43] != 0) return reject(original_text(::bmh::layout::CareerSession_Reject_TextPointer3)); + if (g_.players[size_t(player)].w35c >> 27) return reject(original_text(::bmh::layout::CareerSession_Reject_TextPointer4)); + ModernState staged_game = g_; + if (!modern::contract_insurance(staged_game, active, request.row, request.term_column, request.insurance_months).accepted) + return reject("Die Versicherung konnte nicht bestätigt werden."); + g_ = std::move(staged_game); + ++revision; + last_contract_request_id_ = request.request_id; + contract_quote_->revision = revision; + result.success = result.accepted = true; + result.quote_id = contract_quote_->quote_id; + result.demands = contract_quote_->demands; + return true; + } + for (size_t i = 0; i < request.proposed_bonuses.size(); ++i) + if (request.proposed_bonuses[i] > (i < 3 ? 20 : 200)) + return reject("Die Prämie liegt über dem Originalmaximum."); + if (request.kind == ui::ContractActionKind::submit_bonuses) { + if (!full_mode || request.term_column != 0 || request.demand != 0 || request.monthly_salary != 0 || + request.insurance_months != 0) return reject("Der Prämienauftrag enthält ungültige Daten."); + ModernState staged_game = g_; + const bool accepted = modern::contract_bonuses(staged_game, active, request.row, request.proposed_bonuses); + g_ = std::move(staged_game); + ++revision; + last_contract_request_id_ = request.request_id; + contract_quote_.reset(); + result.success = true; + result.accepted = accepted; + result.feedback = accepted ? original_text(team_bonuses ? ::bmh::layout::CareerSession_Reject_TextPointer8 : ::bmh::layout::CareerSession_Reject_TextPointer9) : + team_bonuses ? original_text(::bmh::layout::CareerSession_Reject_TextPointer7) : std::string{}; + return true; + } + if (request.kind != ui::ContractActionKind::submit_offer || request.term_column >= 4 || request.insurance_months != 0 || + request.demand != contract_quote_->demands[request.term_column] || request.demand == 0 || + request.demand == std::numeric_limits::max() || request.monthly_salary > 200000 || + (g_.tactics[board + 0x4f] & 0x80) || (g_.tactics[board + 0x0b] & 0x60)) + return reject("Dieses Angebot ist im Original nicht mehr verhandelbar."); + if (!full_mode && !std::equal(request.proposed_bonuses.begin(), request.proposed_bonuses.end(), + g_.tactics.begin() + long(board + 0x12))) + return reject("Prämienänderungen sind nur in Spielmodus III verfügbar."); + ModernState staged_game = g_; + WatcomRandom staged_rand = rand_; + bool accepted = false; + try { + accepted = modern::contract_offer(staged_game, active, request.row, request.term_column, + request.monthly_salary, request.demand, false, false, staged_rand, + &request.proposed_bonuses); + } catch (const std::exception&) { return reject("Der Vertrag konnte nicht verhandelt werden."); } + g_ = std::move(staged_game); + rand_ = staged_rand; + ++revision; + last_contract_request_id_ = request.request_id; + contract_quote_.reset(); + result.success = true; + result.accepted = accepted; + result.feedback = original_text(accepted ? ::bmh::layout::CareerSession_Reject_TextPointer5 : ::bmh::layout::CareerSession_Reject_TextPointer6); + return true; +} + +bool ModernSession::validate_desk_setting_owner(const DeskSettingIdentity& identity, uint64_t revision, + std::string& error, bool require_desk_phase) const { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (balance_draft_ || balance_dispatch_active_ || league_pairings_draft_ || league_pairings_dispatch_active_) { + error = "league_pairings_active"; return false; + } + if (career_complete()) { error = "career_complete"; return false; } + if (require_desk_phase && ((turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk) || + pending_offer_dispatch_active_ || market_dispatch_active_ || calendar_advance_active_ || + transfer_offer_editor_ || manager_join_ || contract_quote_ || stadium_.investment || + stadium_.tip || stadium_.periphery_quote)) { + error = "desk_setting_unavailable"; return false; + } + const int active = g_.memory.has(::bmh::layout::ActiveManager) ? int(g_.memory.u8(::bmh::layout::ActiveManager)) : -1; + if (identity.manager_slot != active || active < 0 || active > 3 || + size_t(active) >= g_.manager_teams.size() || identity.revision != revision || revision == UINT64_MAX) { + error = "stale_manager_or_revision"; return false; + } + const int club = g_.manager_teams[size_t(active)]; + const size_t rec = size_t(active) * 0xb0c; + if (identity.runtime_club != club || club < 0 || club > no_team() || size_t(club) >= g_.club_ids.size() || + identity.stable_club_identity != std::optional(int(g_.club_ids[size_t(club)])) || + rec + 0xb0c > g_.manager_records.size() || size_t(active + 1) * 5 > g_.manager_options.size() || + (int(g_.manager_records[rec + 0x290]) | int(g_.manager_records[rec + 0x291]) << 8) != club) { + error = "invalid_desk_setting_owner"; return false; + } + return true; +} + +bool ModernSession::apply_desk_setting(int manager, bool price, int index, int value, std::string& error) { + const size_t rec = size_t(manager) * 0xb0c; + const bool national = g_.manager_teams[size_t(manager)] == no_team(); + if (price) { + // Uint8T4: local offsets35..86 map to admission values8..25. + if (national || value < 8 || value > 25) { error = "invalid_ticket_price"; return false; } + g_.manager_records[rec + 0x26e] = uint8_t(value); + } else { + if (index < 0 || index > 4) { error = "invalid_automation_index"; return false; } + const size_t at = size_t(manager) * 5 + size_t(index); + if (index == 0) { + if (g_.manager_options[at] > 8 || value < 0 || value > 8) { + error = "invalid_saved_formation_automation"; return false; + } + // SizeT6 uses the saved outdoor/indoor formation availability. + const uint8_t mask = g_.manager_records[rec + 0x218 + size_t(g_.indoor)]; + if (value != 0 && !(mask & (1u << (value - 1)))) { + error = "unavailable_saved_formation"; return false; + } + g_.manager_options[at] = uint8_t(value); + } else { + if (index == 4 && national) { error = "national_team_training_unavailable"; return false; } + if (value != 0 && value != 1) { error = "invalid_automation_value"; return false; } + // Explicit bool setters and SDL toggles preserve every other bit. + g_.manager_options[at] = uint8_t((g_.manager_options[at] & ~uint8_t(1)) | uint8_t(value)); + } + } + error.clear(); + return true; +} + +bool ModernSession::dispatch_ticket_price(const TicketPriceRequest& request, uint64_t& revision, + std::string& error) { + if (!validate_desk_setting_owner(request.identity, revision, error)) return false; + if (request.price < 8 || request.price > 25) { error = "invalid_ticket_price"; return false; } + if (!apply_desk_setting(request.identity.manager_slot, true, -1, request.price, error)) return false; + ++revision; + return true; +} + +bool ModernSession::dispatch_automation(const AutomationRequest& request, uint64_t& revision, + std::string& error) { + if (!validate_desk_setting_owner(request.identity, revision, error)) return false; + const int index = int(request.automation); + if (index < 0 || index > 4) { error = "invalid_automation_index"; return false; } + int value = int(request.enabled); + if (index == 0) { + if (request.enabled != request.formation.has_value() || + (request.formation && (*request.formation < 1 || *request.formation > 8))) { + error = "invalid_saved_formation_automation"; return false; + } + value = request.formation.value_or(0); + } else if (request.formation) { error = "unexpected_formation_selection"; return false; } + if (!apply_desk_setting(request.identity.manager_slot, false, index, value, error)) return false; + ++revision; + return true; +} + +bool ModernSession::dispatch_desk_widget(const ui::DeskRequest& request, uint64_t& revision, + std::string& error) { + const int active = g_.memory.has(::bmh::layout::ActiveManager) ? int(g_.memory.u8(::bmh::layout::ActiveManager)) : -1; + DeskSettingIdentity identity{request.manager_slot, -1, std::nullopt, request.revision}; + if (active >= 0 && size_t(active) < g_.manager_teams.size()) { + identity.runtime_club = g_.manager_teams[size_t(active)]; + if (identity.runtime_club >= 0 && size_t(identity.runtime_club) < g_.club_ids.size()) + identity.stable_club_identity = int(g_.club_ids[size_t(identity.runtime_club)]); + } + if (!validate_desk_setting_owner(identity, revision, error, false)) return false; + const bool price = request.kind == ui::DeskRequestKind::change_ticket_price; + if (!price && request.kind != ui::DeskRequestKind::change_option) { + error = "unsupported_desk_widget"; return false; + } + // Keep SDL requests bound to a visible, open and enabled MEN drawer/item. + const auto desk = desktop_projection(revision); + const int expected_kind = price ? 55 : 64; + const auto item = std::find_if(desk.items.begin(), desk.items.end(), [&](const ui::DeskItem& item) { + return item.id == request.item_id && item.kind == expected_kind && item.open && !item.disabled; + }); + if (request.menu_kind != expected_kind || item == desk.items.end()) { + error = "stale_or_closed_desk_widget"; return false; + } + int value = request.value; + if (!price) { + if (request.value < 0 || request.value > 4) { error = "invalid_automation_index"; return false; } + const size_t at = size_t(active) * 5 + size_t(request.value); + if (request.value == 0) { + if (g_.manager_options[at] > 8) { error = "invalid_saved_formation_automation"; return false; } + value = g_.manager_options[at]; + const uint8_t mask = g_.manager_records[size_t(active) * 0xb0c + 0x218 + size_t(g_.indoor)]; + do { value = (value + 1) % 9; } while (value != 0 && !(mask & (1u << (value - 1)))); + } else value = (g_.manager_options[at] ^ 1) & 1; + } + if (!apply_desk_setting(active, price, request.value, value, error)) return false; + ++revision; + return true; +} + +bool ModernSession::dispatch_desktop_layout(const ui::DeskRequest& request, uint64_t& revision, + std::string& error) { + constexpr size_t kItems=54, kStride=16, kBytes=kItems*kStride; + if (request.kind != ui::DeskRequestKind::change_layout || request.revision != revision || + request.manager_slot < 0 || size_t(request.manager_slot) >= g_.manager_teams.size() || + !g_.memory.has(::bmh::layout::ActiveManager) || int(g_.memory.u8(::bmh::layout::ActiveManager)) != request.manager_slot || + turn_driver_.stage==TurnDriver::Stage::Failed || turn_driver_.stage==TurnDriver::Stage::CareerComplete || + career_complete()) { + error="stale_or_invalid_desk_layout_owner"; return false; + } + if (transfer_offer_editor_ || pending_offer_dispatch_active_ || market_dispatch_active_ || + balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || other_games_owner_ || other_games_dispatch_active_ || + stadium_.block_expansion || advertising_renewal_dispatch_active_) { + error="desk_layout_blocked_during_active_flow"; return false; + } + if (request.item_id < 1 || request.item_id >= int(kItems)) { error="invalid_desk_layout_item"; return false; } + const uint32_t base=::bmh::layout::DesktopsUnsigned+uint32_t(request.manager_slot)*0x360u; + if (!g_.memory.has(base+kBytes-1)) { error="desk_layout_memory_unavailable"; return false; } + std::array actual{}; + for(size_t i=0;i>8);}; + const auto moved_x=read16(request.layout_after,at); + const uint8_t moved_y=request.layout_after[at+2]; + if(request.menu_kind!=expected[at+12]) { error="desk_layout_item_kind_mismatch"; return false; } + const bool source_drag_enabled=g_.memory.has(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField)&&g_.memory.u8(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField)==0; + if((request.layout_operation==ui::DeskLayoutOperation::move_item|| + request.layout_operation==ui::DeskLayoutOperation::set_folder|| + request.layout_operation==ui::DeskLayoutOperation::return_folder_child|| + request.layout_operation==ui::DeskLayoutOperation::send_to_folder|| + request.layout_operation==ui::DeskLayoutOperation::restore_folder_child)&&!source_drag_enabled) { + error="source_desk_drag_disabled";return false; + } + switch(request.layout_operation) { + case ui::DeskLayoutOperation::move_item: { + if(request.layout_target_item!=-1 || expected[at+12]==72) { error="invalid_desk_layout_move_target"; return false; } + for(size_t i=0;imax_x || + moved_y<1 || moved_y>max_y || + (snap && ((source_x%5)!=0 && source_x!=max_x || (moved_y%5)!=0 && moved_y!=max_y))) { + error="desk_layout_move_outside_source_bounds"; return false; + } + write16(expected,at,moved_x); expected[at+2]=moved_y; + break; + } + case ui::DeskLayoutOperation::toggle_quickbar_drawer: { + const int id=request.item_id; + const int kind=expected[at+12]; + if(request.layout_target_item!=id || id<1 || id>=54 || kind<50 || kind>71 || + kind!=request.menu_kind || (request.value!=2 && request.value!=8)) { + error="invalid_desk_quickbar_drawer"; return false; + } + if(expected[at+5]==0xff) { + int tail=0; + size_t guard=0; + while(expected[size_t(tail)*kStride+5]!=0) { + if(++guard>=kItems) { error="invalid_desk_layout_chain"; return false; } + tail=expected[size_t(tail)*kStride+5]; + if(tail<0 || tail>=int(kItems)) { error="invalid_desk_layout_links"; return false; } + } + expected[at+5]=0; expected[at+6]=uint8_t(tail); + expected[size_t(tail)*kStride+5]=uint8_t(id); + const bool opened=!(request.value==8 && id>2); + expected[at+13]=uint8_t((expected[at+13]&0x7f)|(opened?0x80:0)); + } else { + const uint8_t previous=expected[at+6],next=expected[at+5]; + if(previous>=kItems || (next!=0 && next>=kItems)) { error="invalid_desk_layout_links"; return false; } + expected[size_t(previous)*kStride+5]=next; + if(next!=0) expected[size_t(next)*kStride+6]=previous; + expected[at+5]=expected[at+6]=0xff; + } + break; + } + case ui::DeskLayoutOperation::return_folder_child: { + const int folder=request.layout_target_item; + if(request.item_id<1||request.item_id>30||folder<0||folder>=3|| + expected[at+5]!=0xff||expected[at+6]!=0xff||(expected[at+1]&0x10)!=0|| + (expected[at+13]&0x7f)!=folder||expected[at+12]>=50) { + error="invalid_desk_folder_child_return"; return false; + } + bool owner_open=false; + for(size_t item=1;item=int(kItems)) break; + cursor=next; + } + if(owner_open) break; + } + if(!owner_open) { error="desk_folder_child_owner_closed"; return false; } + const int max_x=std::max(1,319-int(expected[at+3])),max_y=std::max(1,239-int(expected[at+4])); + const int source_x=int(moved_x&0xefff); + const bool snap=g_.memory.has(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField2)&&g_.memory.u8(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField2)==0; + if((moved_x&0x1000)!=(read16(expected,at)&0x1000)||source_x<1||source_x>max_x||moved_y<1||moved_y>max_y|| + (snap&&(((source_x%5)!=0&&source_x!=max_x)||((moved_y%5)!=0&&moved_y!=max_y)))) { + error="desk_folder_child_return_outside_source_bounds";return false; + } + int tail=0;size_t guard=0; + while(expected[size_t(tail)*kStride+5]!=0) { + if(++guard>=kItems) { error="invalid_desk_layout_chain";return false; } + tail=expected[size_t(tail)*kStride+5]; + if(tail<0||tail>=int(kItems)) { error="invalid_desk_layout_links";return false; } + } + expected[at]=request.layout_after[at];expected[at+1]=request.layout_after[at+1];expected[at+2]=moved_y; + expected[at+5]=0;expected[at+6]=uint8_t(tail); + expected[size_t(tail)*kStride+5]=uint8_t(request.item_id); + break; + } + case ui::DeskLayoutOperation::send_to_folder: { + const int folder=request.layout_target_item; + const uint8_t previous=expected[at+6],next=expected[at+5]; + if(request.item_id<1||request.item_id>30||folder<0||folder>=3|| + expected[at+5]==0xff||expected[at+12]>=50||expected[at+12]==12|| + (expected[at+13]&0x7f)!=folder||previous>=kItems||(next!=0&&next>=kItems)|| + expected[size_t(previous)*kStride+5]!=request.item_id|| + (next!=0&&expected[size_t(next)*kStride+6]!=request.item_id)) { + error="invalid_desk_bin_send";return false; + } + expected[size_t(previous)*kStride+5]=next; + if(next!=0)expected[size_t(next)*kStride+6]=previous; + expected[at+5]=expected[at+6]=0xff; + break; + } + case ui::DeskLayoutOperation::restore_folder_child: { + const int folder=request.layout_target_item; + if(request.item_id<1||request.item_id>30||folder<0||folder>=3|| + expected[at+5]!=0xff||expected[at+6]!=0xff||(expected[at+1]&0x10)!=0|| + (expected[at+13]&0x7f)!=folder||expected[at+12]>=50) { + error="invalid_desk_bin_restore";return false; + } + bool owner_open=false; + for(size_t item=1;item=int(kItems)) break; + cursor=next; + } + if(owner_open)break; + } + if(!owner_open) { error="desk_bin_restore_folder_closed";return false; } + int tail=0;size_t guard=0; + while(expected[size_t(tail)*kStride+5]!=0) { + if(++guard>=kItems) { error="invalid_desk_layout_chain";return false; } + tail=expected[size_t(tail)*kStride+5]; + if(tail<0||tail>=int(kItems)) { error="invalid_desk_layout_links";return false; } + } + expected[at+5]=0;expected[at+6]=uint8_t(tail); + expected[size_t(tail)*kStride+5]=uint8_t(request.item_id); + break; + } + case ui::DeskLayoutOperation::set_folder: { + const int target=request.layout_target_item; + const int kind=expected[at+12]; + if(kind>=50 || request.item_id>30 || (expected[at+1]&0x10)!=0 || target<1 || target>=int(kItems) || expected[size_t(target)*kStride+12]<50 || + expected[size_t(target)*kStride+12]>52) { error="invalid_desk_folder_drop"; return false; } + const size_t target_at=size_t(target)*kStride; + const uint8_t folder=uint8_t(expected[target_at+12]-50); + int folder_count=0; + for(int child=1;child<=30;++child) { + const size_t child_at=size_t(child)*kStride; + if(expected[child_at+5]==0xff && (expected[child_at+1]&0x10)==0 && + (expected[child_at+13]&0x7f)==folder) ++folder_count; + } + const bool already_in_folder=expected[at+5]==0xff&&(expected[at+13]&0x7f)==folder; + if(folder_count-(already_in_folder?1:0)>=12) { error="desk_folder_source_capacity"; return false; } + const int previous=expected[at+6], next=expected[at+5]; + if((previous!=0xff && previous>=int(kItems)) || (next!=0xff && next>=kItems)) { error="invalid_desk_layout_links"; return false; } + if(previous!=0xff) expected[size_t(previous)*kStride+5]=uint8_t(next); + if(next>0 && next<0xff) expected[size_t(next)*kStride+6]=uint8_t(previous); + expected[at+13]=uint8_t((expected[at+13]&0x80)|folder); + expected[at+5]=expected[at+6]=0xff; + write16(expected,at,moved_x); expected[at+2]=moved_y; + break; + } + case ui::DeskLayoutOperation::none: + error="unsupported_desk_layout_operation"; return false; + } + if(expected!=request.layout_after) { error="desk_layout_after_state_not_source_derived"; return false; } + ModernState staged=g_; + for(size_t i=0;i 3 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || + request.revision != revision) { + error = "Die Taktikanfrage ist veraltet."; return false; + } + if (request.kind != ui::TacticsRequestKind::set_tactic || request.index < 0 || request.index >= 8 || + request.desired_value < 0 || request.desired_value > exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField + request.index)) { + error = "Ungültige Taktikeinstellung."; return false; + } + const bool live_option = (g_.memory.has(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) ? g_.memory.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) : exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3)) != 0; + if (live_option && exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField2 + request.index) == 0) { + error = "Diese Taktikeinstellung ist nicht verfügbar."; return false; + } + if ((request.index == 0 && request.desired_assistant_attitude != std::optional(0)) || + (request.index != 0 && request.desired_assistant_attitude)) { + error = "Ungültige Assistenteneinstellung."; return false; + } + // RerateTeam: only +d2..+d9 and (index 0) option byte +2. + // The tactic board, player order and both RNG streams stay untouched. + const size_t rec = size_t(request.manager_slot) * 0xb0c; + const size_t option = size_t(request.manager_slot) * 5 + 2; + if (g_.manager_records.size() < rec + 0xb0c || g_.manager_options.size() <= option) { + error = "Die Taktikdaten sind unvollständig."; return false; + } + g_.manager_records[rec + 0xd2 + size_t(request.index)] = uint8_t(request.desired_value); + if (request.index == 0) g_.manager_options[option] = 0; + ++revision; + return true; +} + +bool ModernSession::dispatch_lineup(const ui::LineupRequest& request, uint64_t& revision, + std::string& error) { + if (calendar_advance_active_ || pending_offer_dispatch_active_) { + error = "lineup_unavailable_during_calendar_advance"; + return false; + } + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + error.clear(); + const int active = g_.memory.has(::bmh::layout::ActiveManager) ? int(g_.memory.u8(::bmh::layout::ActiveManager)) : -1; + if (request.manager_slot != active || active < 0 || active > 3 || + size_t(active) >= g_.manager_teams.size() || request.runtime_club != g_.manager_teams[size_t(active)] || + request.revision != revision || revision == std::numeric_limits::max() || + request.runtime_club < 0 || request.runtime_club >= int(g_.team_flags.size())) { + error = "Die Aufstellungsaktion ist veraltet."; + return false; + } + const SquadRange range = squad_range(request.runtime_club); + if (range.count < 11 || range.first + range.count > g_.squad_slots.size() || + g_.tactics.size() < size_t(active + 1) * 0x840 || + g_.manager_options.size() <= size_t(active) * 5 || g_.player_cards.size() != g_.players.size()) { + error = "Der Aufstellungszustand ist unvollständig."; + return false; + } + if (request.kind == ui::LineupRequestKind::prepare_lineup) { + ModernState staged = g_; + try { + // PitchScreen opens through the human Int2 path first. + // Existing assistant scoring retains its documented port limitations. + auto_lineup(staged, request.runtime_club, 0xe4); + prepare_lineup_entry(staged, request.runtime_club); // PrepareLineupEntry. + modern::open_lineup_screen(staged, active); // OpenBMH deviates from the original: supports designated set-piece record initialization and validation. +// supported rule profile NormalizePitchSetPieceSource entry initialization. + if (!initialize_pitch_set_piece_source(staged, active, request.runtime_club)) + throw std::runtime_error("set-piece set-piece record did not validate"); + const uint32_t display=uint32_t(::bmh::layout::CareerSession_AnyOf_ExecutableField+active*2); + if(staged.memory.has(display)&&(staged.memory.u16(display)&0x80)&& + !normalize_pitch_set_piece_source(staged,active,request.runtime_club)) + throw std::runtime_error("set-piece reentry redraw did not validate"); + } catch (const std::exception& e) { + error = std::string("Diese Aufstellung kann im aktuellen Spielmodus noch nicht vorbereitet werden. (") + e.what() + ")"; + return false; + } + // Accept only the valid authoritative eleven produced by the human path. + std::array seen{}; + for (int row = 0; row < 11; ++row) { + const uint16_t slot = staged.squad_slots.at(range.first + size_t(row)); + const int id = slot & 0x0fff; + const auto* board = staged.tactics.data() + size_t(active) * 0x840 + size_t(row) * 0x58; + if (id == 0x0fff || size_t(id) >= g_.players.size() || seen[size_t(id)] || + !(slot & 0x8000) || (slot & 0x4000) || int8_t(board[0x41]) < 0 || + int8_t(board[0x41]) > 19 || int8_t(board[0x42]) < 0 || int8_t(board[0x42]) > 8) { + error = "Die Aufstellung ist noch nicht für den Anstoß vorbereitet."; + return false; + } + seen[size_t(id)] = true; + } + g_ = std::move(staged); + lineup_entry_manager_ = active; + lineup_entry_club_ = request.runtime_club; + ++revision; + return true; + } + if (request.kind != ui::LineupRequestKind::swap_players || + lineup_entry_manager_ != active || lineup_entry_club_ != request.runtime_club || + request.first_row < 0 || request.second_row < 0 || request.first_row == request.second_row || + size_t(request.first_row) >= range.count || size_t(request.second_row) >= range.count) { + error = "Der Spielerwechsel ist nicht freigegeben."; + return false; + } + const size_t first = range.first + size_t(request.first_row); + const size_t second = range.first + size_t(request.second_row); + const uint16_t first_slot = g_.squad_slots.at(first), second_slot = g_.squad_slots.at(second); + const int first_id = (first_slot & 0x0fff) == 0x0fff ? -1 : first_slot & 0x0fff; + const int second_id = (second_slot & 0x0fff) == 0x0fff ? -1 : second_slot & 0x0fff; + if (first_slot != request.first_slot || second_slot != request.second_slot || + first_id != request.first_player || second_id != request.second_player || + first_id < 0 || second_id < 0 || size_t(first_id) >= g_.players.size() || size_t(second_id) >= g_.players.size()) { + error = "Die Kaderzeilen wurden inzwischen geändert."; + return false; + } + // SizeT3 requires injury/foreign-rule confirmations for special + // swaps. Until those dialogs exist, reject that path before any writes. + if (((g_.players[size_t(first_id)].w364 >> 16) & 0x1f) != 0 || + ((g_.players[size_t(second_id)].w364 >> 16) & 0x1f) != 0) { + error = "Ein verletzter Spieler kann hier noch nicht eingewechselt werden."; + return false; + } + if ((request.first_row < 11) != (request.second_row < 11) && exe_.u8(::bmh::layout::ForeignPlayerLimitEnabled) != 0) { + error = "Dieser Wechsel benötigt eine Bestätigung der Ausländerregel."; + return false; + } + const size_t board_base = size_t(active) * 0x840; + auto* a = g_.tactics.data() + board_base + size_t(request.first_row) * 0x58; + auto* b = g_.tactics.data() + board_base + size_t(request.second_row) * 0x58; + const uint8_t ax = a[0x41], ay = a[0x42], bx = b[0x41], by = b[0x42]; + // Original SquadSlotsBoardEntriesChangePlaces moves the player/tactics entry, then restores + // the 0xc000 role bits to their roster rows. Preserve bit 12 and the + // player id with the entry; keep the starter/bench flags with the slot. + g_.squad_slots[first] = uint16_t((second_slot & 0x1fff) | (first_slot & 0xc000)); + g_.squad_slots[second] = uint16_t((first_slot & 0x1fff) | (second_slot & 0xc000)); + std::swap_ranges(a, a + 0x58, b); + a[0x41] = ax; a[0x42] = ay; b[0x41] = bx; b[0x42] = by; + // GatedByParamLive is applied to every marked row, not just the two swapped + // players. Keep card-side row identity synchronized with the roster. + for (size_t row = 0; row < range.count; ++row) { + const uint16_t slot = g_.squad_slots[range.first + row]; + if ((slot & 0xc000) == 0) continue; + const size_t id = slot & 0x0fff; + if (id >= g_.players.size()) continue; + g_.player_cards[id] = uint16_t((g_.player_cards[id] & 0xffe0) | uint16_t(row)); + } + g_.manager_options.at(size_t(active) * 5) = 0; // source manual mode selects DispatchLiveOverview + ++revision; + return true; +} + +std::optional ModernSession::dispatch_live_overview( + const LiveOverviewAction& action, MatchEngine& engine, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info) { + error.clear(); + if (!calendar_advance_active_ || !live_overview_owner_ || revision==UINT64_MAX || live_overview_owner_->request.revision!=revision || + &engine.state!=&g_ || &engine.game!=&game_ || &engine.rand!=&rand_ || + (live_overview_owner_->phase_result + ? (!phase_result_request_ || live_overview_owner_->request.group_index!=int(phase_result_request_->group_index)) + : live_overview_owner_->request.group_index!=0) || engine.groups.empty() || + engine.groups.size()!=live_overview_owner_->active_groups.size() || + engine.groups.size()!=turn_driver_.groups.size() || + engine.groups.front().desc!=turn_driver_.groups.front().desc || + engine.groups.front().fixtures!=turn_driver_.groups.front().fixtures || + engine.referees!=live_overview_owner_->referees) { + error="live overview: stale owner or no longer at the Source minute boundary"; + return {}; + } + for(size_t i=0;iactive_groups[i].first || + engine.groups[i].fixtures!=live_overview_owner_->active_groups[i].second) { + error="live overview: active Source match group changed";return {}; + } + const auto live= *live_overview_owner_; + struct LiveBoundaryFamilyScope { + bool& active; bool previous; + explicit LiveBoundaryFamilyScope(bool& value) : active(value), previous(value) { active=false; } + ~LiveBoundaryFamilyScope() { active=previous; } + } family_scope(calendar_advance_active_); + LiveOverviewDispatch result;result.kind=live.kind; + try { + if(const auto* family=std::get_if(&action)) { + if((live.kind!=LiveOverviewKind::league_table&&live.kind!=LiveOverviewKind::league_pairings&& + live.kind!=LiveOverviewKind::league_strengths) || + family->identity!=live.family_identity || family->identity.revision!=revision || + !league_family_owner_ || league_family_owner_->identity!=family->identity || + family->from_child!=league_family_owner_->child) + throw FormatError("live overview: mismatched League family owner"); + if(family->kind==ui::LeagueFamilyRequestKind::close) { + auto preparation=close_league_family(*family,revision,error); + if(!preparation)throw FormatError(error.empty()?"live overview: Source family close rejected":error); + result.closed=true;result.preparation=std::move(*preparation);live_overview_owner_.reset();return result; + } + if(family->kind==ui::LeagueFamilyRequestKind::control && family->from_child==1) { + auto page=dispatch_league_table_control(*family,revision,error); + if(!page)throw FormatError(error.empty()?"live overview: Source Table control rejected":error); + result.table=page->page;result.family_identity=page->identity; + result.table_phase=page->phase;result.table_dialog=page->dialog; + } else if(family->kind==ui::LeagueFamilyRequestKind::table_range_result && family->from_child==1) { + auto page=dispatch_league_table_range_reply(*family,revision,error); + if(!page)throw FormatError(error.empty()?"live overview: Source Table range reply rejected":error); + result.table=page->page;result.family_identity=page->identity; + result.table_phase=page->phase;result.table_dialog=page->dialog; + } else if(family->kind==ui::LeagueFamilyRequestKind::table_forecast_presented && family->from_child==1) { + auto page=acknowledge_league_forecast_present(*family,revision,error); + if(!page)throw FormatError(error.empty()?"live overview: Source Table forecast ACK rejected":error); + result.table=page->page;result.family_identity=page->identity; + result.table_phase=page->phase;result.table_dialog=page->dialog; + } else if(family->kind==ui::LeagueFamilyRequestKind::team_info && family->from_child==1) { + auto identity=dispatch_family_table_team_info(*family,revision,error,team_info); + if(!identity)throw FormatError(error.empty()?"live overview: Source Table TeamInfo rejected":error); + auto page=current_league_table_dispatch(error); + if(!page)throw FormatError(error.empty()?"live overview: Source Table return is unavailable":error); + result.table=page->page;result.family_identity=page->identity; + result.table_phase=page->phase;result.table_dialog=page->dialog; + } else if((family->kind==ui::LeagueFamilyRequestKind::select_league || + family->kind==ui::LeagueFamilyRequestKind::toggle_league_group) && family->from_child==1) { + if(!select_league_family_page(*family,revision,error)) + throw FormatError(error.empty()?"live overview: Source Table selector rejected":error); + auto page=current_league_table_dispatch(error); + if(!page)throw FormatError(error.empty()?"live overview: Source Table selector projection missing":error); + result.table=page->page;result.family_identity=page->identity; + result.table_phase=page->phase;result.table_dialog=page->dialog; + } else if(family->kind==ui::LeagueFamilyRequestKind::navigate && + family->target_child>=1 && family->target_child<=3) { + if(family->from_child==3) { + if(!suspend_strengths_for_family(*family,revision,error)) + throw FormatError(error.empty()?"live overview: Source Strengths child return rejected":error); + } else if(family->from_child==2) { + if(!suspend_pairings_for_family(*family,revision,error)) + throw FormatError(error.empty()?"live overview: Source Pairings child return rejected":error); + } + auto fresh=strengths_open_request(revision); + if(!fresh)throw FormatError("live overview: Source family has no active manager projection"); + auto identity=fresh->identity; + identity.family_id=family->identity.family_id; + identity.family_sequence=family->identity.family_sequence+1; + identity.league=family->identity.league; + identity.league_group=family->identity.league_group; + identity.manager_default_league=family->identity.manager_default_league; + identity.source_param2=family->identity.source_param2; + if(!prepare_league_family_child(identity,family->target_child,revision,error)) + throw FormatError(error.empty()?"live overview: Source family child preparation rejected":error); + identity.expected_family_word=g_.memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2); + if(family->target_child==1) { + if(!advance_league_family(*family,identity,1,revision,error)) + throw FormatError(error.empty()?"live overview: Source Table handoff rejected":error); + auto page=current_league_table_dispatch(error); + if(!page)throw FormatError(error.empty()?"live overview: Source Table handoff projection missing":error); + result.kind=LiveOverviewKind::league_table; + result.table=page->page;result.family_identity=page->identity; + result.table_phase=page->phase;result.table_dialog=page->dialog; + } else if(family->target_child==2) { + LeaguePairingsDraft draft{g_,game_,rand_,club_modal_runtime_,club_modal_runtime_,{}, {}, + modern::save_stream(g_),rand_.seed(),game_.seed(),rand_.calls(),game_.calls()}; + for(const auto& group:engine.groups)draft.original_active_groups.emplace_back(group.desc,group.fixtures); + draft.original_referee_profiles=engine.referees; + draft.owner=modern::open_league_pairings_source(draft.state,identity.manager,ui::league_pairings_constants(exe_)); + if(draft.owner.league!=identity.league) { + // Source Move chooses the family league before its first visible page. + draft.owner.league=identity.league; + draft.owner.round=std::min(draft.state.league_rounds.at(size_t(identity.league)), + league_matchdays(identity.league)-1); + draft.owner.title_round=draft.state.league_rounds.at(size_t(identity.league)); + if(draft.owner.round>=league_matchdays(identity.league)) + throw FormatError("live overview: selected Source Pairings league round is outside its schedule"); + } + draft.active_packet=validate_normal_pairings_group(draft.state,draft.owner,draft.runtime); + const uint64_t child_scope=++league_pairings_scope_; + auto page=ui::league_pairings_from_game(draft.state,draft.owner,exe_,revision, + child_scope,family->identity.family_sequence+1,draft.active_packet); + draft.identity=page.identity; + draft.runtime[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(draft.owner.league)); + pairings_runtime_draw(draft.state,draft.runtime,page,exe_); + league_pairings_draft_=std::move(draft); + if(!advance_league_family(*family,identity,2,revision,error)) + throw FormatError(error.empty()?"live overview: Source Pairings handoff rejected":error); + result.kind=LiveOverviewKind::league_pairings; + result.pairings=std::move(page); + result.family_identity=league_family_owner_->identity; + } else { + ui::StrengthsRequest open=*fresh;open.identity=identity;open.kind=ui::StrengthsAction::open; + auto page=dispatch_strengths(open,revision,error,{},true); + if(!page||page->closed)throw FormatError(error.empty()?"live overview: Source Strengths entry rejected":error); + if(!advance_league_family(*family,page->page.identity,3,revision,error)) + throw FormatError(error.empty()?"live overview: Source Strengths handoff rejected":error); + result.kind=LiveOverviewKind::league_strengths; + result.strengths=page->page;result.family_identity=page->page.identity; + } + } else { + throw FormatError("live overview: unsupported Source family transition"); + } + if(league_family_owner_) { + result.family_identity=league_family_owner_->identity; + live_overview_owner_->kind=result.kind; + live_overview_owner_->family_identity=result.family_identity; + } + live_overview_owner_->request.revision=revision; + return result; + } + if(const auto* strengths=std::get_if(&action)) { + if(live.kind!=LiveOverviewKind::league_strengths || !strengths_owner_ || + strengths->identity!=strengths_owner_->page.identity || + strengths->identity.revision!=revision || strengths->identity!=live.family_identity) + throw FormatError("live overview: mismatched Source Strengths owner"); + if(strengths->kind==ui::StrengthsAction::table || strengths->kind==ui::StrengthsAction::pairings) { + ui::LeagueFamilyRequest navigation; + navigation.identity=live.family_identity; + navigation.kind=ui::LeagueFamilyRequestKind::navigate; + navigation.from_child=3; + navigation.target_child=strengths->kind==ui::StrengthsAction::table?1:2; + struct RestoreObserverScope { bool& flag; bool previous; explicit RestoreObserverScope(bool& f):flag(f),previous(f){flag=true;} ~RestoreObserverScope(){flag=previous;} } observer_scope(calendar_advance_active_); + return dispatch_live_overview(LiveOverviewAction{navigation},engine,revision,error,team_info); + } + if(strengths->kind==ui::StrengthsAction::close) { + ui::LeagueFamilyRequest close;close.identity=live.family_identity; + close.kind=ui::LeagueFamilyRequestKind::close;close.from_child=3;close.target_child=0; + auto preparation=close_league_family(close,revision,error); + if(!preparation)throw FormatError(error.empty()?"live overview: Source Strengths close rejected":error); + result.closed=true;result.preparation=std::move(*preparation);live_overview_owner_.reset();return result; + } + const auto prior=live.family_identity; + auto page=dispatch_strengths(*strengths,revision,error,team_info,false); + if(!page || page->closed)throw FormatError(error.empty()?"live overview: Source Strengths action rejected":error); + if(!refresh_family_after_child(prior,3,page->page.identity,revision,error)) + throw FormatError(error.empty()?"live overview: Source Strengths ACK rejected":error); + result.strengths=page->page;result.preparation=page->preparation; + result.family_identity=page->page.identity; + live_overview_owner_->family_identity=result.family_identity; + live_overview_owner_->request.revision=revision; + return result; + } + if(const auto* pairings=std::get_if(&action)) { + if(live.kind!=LiveOverviewKind::league_pairings || !league_pairings_draft_ || + pairings->identity!=league_pairings_draft_->identity || pairings->identity.revision!=revision) + throw FormatError("live overview: mismatched Source Pairings owner"); + if(pairings->event.kind==LeaguePairingsAction::close) { + ui::LeagueFamilyRequest close;close.identity=live.family_identity; + close.kind=ui::LeagueFamilyRequestKind::close;close.from_child=2;close.target_child=0; + auto preparation=close_league_family(close,revision,error); + if(!preparation)throw FormatError(error.empty()?"live overview: Source Pairings close rejected":error); + result.closed=true;result.preparation=std::move(*preparation);live_overview_owner_.reset();return result; + } + auto page=dispatch_league_pairings(*pairings,revision,error,team_info); + if(!page)throw FormatError(error.empty()?"live overview: Source Pairings action rejected":error); + result.closed=page->closed;result.pairings=page->page;result.preparation=page->preparation; + if(result.closed) { + // The Source Move return is completed by the outer G/T wrapper. + live_overview_owner_.reset();league_family_owner_.reset(); + } else { + live_overview_owner_->request.revision=revision; + if(league_family_owner_) { + live_overview_owner_->family_identity=league_family_owner_->identity; + result.family_identity=league_family_owner_->identity; + } + } + return result; + } + const auto* cup=std::get_if(&action); + if(!cup || live.kind!=LiveOverviewKind::cup_other_games || !other_games_owner_ || + cup->identity!=other_games_owner_->page.identity || cup->identity.revision!=revision) + throw FormatError("live overview: mismatched Source cup overview owner"); + auto page=dispatch_other_games(*cup,revision,error,team_info); + if(!page)throw FormatError(error.empty()?"live overview: Source cup overview action rejected":error); + result.closed=page->closed;result.cup=page->page;result.preparation=page->preparation; + if(result.closed)live_overview_owner_.reset(); + else live_overview_owner_->request.revision=revision; + return result; + } catch(const std::exception& e) { + error=e.what();return {}; + } +} + +bool ModernSession::begin_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine& engine, uint64_t& revision, std::string& error) { + error.clear(); + if (live_intervention_ || minute <= 2 || (source_mode != 2 && source_mode != 8) || + revision == std::numeric_limits::max() || manager < 0 || manager >= int(g_.manager_teams.size()) || + team < 0 || team >= int(g_.team_flags.size()) || g_.manager_teams[size_t(manager)] != team || + g_.manager_of(team) != manager || &engine.state != &g_ || &engine.game != &game_ || &engine.rand != &rand_) { + error = "Der Live-Eingriff kann für diesen Manager oder Modus nicht geöffnet werden."; + return false; + } + bool current_match = false; + for (const MatchGroup& group : engine.groups) for (int match = 0; match < group.matches(); ++match) { + const uint32_t bit = uint32_t(1) << match; + if ((group.kickoff_void_mask & bit) || (group.void_mask() & bit)) continue; + const int home = group.fixtures.at(size_t(match) * 2); + const int away = group.fixtures.at(size_t(match) * 2 + 1); + if (std::find(g_.live_matches.begin(), g_.live_matches.end(), home) != g_.live_matches.end() && + (team == home || team == away)) current_match = true; + } + if (!current_match) { + error = "Die Mannschaft spielt in der aktuellen Partie nicht."; + return false; + } + LiveInterventionCheckpoint checkpoint; + checkpoint.state = g_; + checkpoint.groups = engine.groups; + checkpoint.game = engine.game; + checkpoint.rand = engine.rand; + checkpoint.minute = minute; checkpoint.source_mode = source_mode; + checkpoint.manager = manager; checkpoint.team = team; + checkpoint.initial_revision = revision; checkpoint.current_revision = revision; + live_intervention_ = std::move(checkpoint); + if (source_mode == 2) { + try { + ModernState entered = g_; + prepare_lineup_entry(entered, team); // PitchScreen's unconditional PrepareLineupEntry entry pass. + g_ = std::move(entered); + } catch (const std::exception& e) { + live_intervention_.reset(); + error = std::string("Die Live-Aufstellung kann nicht geöffnet werden: ") + e.what(); + return false; + } + } + if (g_.memory.has(::bmh::layout::ActiveManager)) g_.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager)); + return true; +} + +bool ModernSession::begin_live_event_intervention(const LiveMatchEvent& event, MatchEngine& engine, + uint64_t& revision, std::string& error) { + error.clear(); + const int manager = event.manager_slot, team = event.team; + if (live_intervention_ || event.minute < 1 || (event.kind != 1 && event.kind != 2) || + event.group_index >= engine.groups.size() || event.match_index < 0 || event.side < 0 || event.side > 1 || + manager < 0 || manager >= int(g_.manager_teams.size()) || team < 0 || + team >= int(g_.team_flags.size()) || event.player < 0 || event.player >= int(g_.players.size()) || + g_.manager_teams[size_t(manager)] != team || g_.manager_of(team) != manager || + g_.manager_option(manager, 1) || engine.live_desk_disabled || !(g_.team_morale.at(size_t(team)) & 0x80) || + &engine.state != &g_ || &engine.game != &game_ || &engine.rand != &rand_ || + revision == std::numeric_limits::max()) { + error = "Der automatische Live-Eingriff gehört nicht zu einem aktuellen Source-Ereignis."; + return false; + } + const MatchGroup& group = engine.groups[event.group_index]; + if (event.match_index >= group.matches() || + group.fixtures.at(size_t(event.match_index) * 2 + size_t(event.side)) != team || + group.fixtures.at(size_t(event.match_index) * 2 + size_t(1 - event.side)) != event.opponent || + (group.kickoff_void_mask >> event.match_index & 1) || (group.void_mask() >> event.match_index & 1) || + std::find(g_.live_matches.begin(), g_.live_matches.end(), group.fixtures.at(size_t(event.match_index) * 2)) == + g_.live_matches.end()) { + error = "Das Source-Ereignis gehört nicht zur aktuell gezeigten Partie."; + return false; + } + // The Source event already changed this exact player/slot before opening PitchScreen. + bool event_player_found = false; + const auto range = squad_range(team); + for (size_t offset = 0; offset < range.count; ++offset) { + const size_t slot = size_t(range.first) + offset; + const uint16_t entry = g_.squad_slots.at(slot); + if ((entry & 0x0fff) != event.player) continue; + if (event.kind == 2 && (g_.players.at(size_t(event.player)).w35c >> 27) != 0 && !(entry & 0x8000)) + event_player_found = true; + if (event.kind == 1 && (g_.players.at(size_t(event.player)).w368 & 0x07000000u) != 0 && !(entry & 0x8000)) + event_player_found = true; + } + if (!event_player_found) { + error = "Der Source-Spielerstatus passt nicht mehr zum automatischen Eingriff."; + return false; + } + LiveInterventionCheckpoint checkpoint; + checkpoint.state = g_; checkpoint.groups = engine.groups; + checkpoint.game = engine.game; checkpoint.rand = engine.rand; + checkpoint.minute = event.minute; checkpoint.source_mode = 2; + checkpoint.manager = manager; checkpoint.team = team; checkpoint.source_event = true; + checkpoint.event = event; checkpoint.initial_revision = revision; checkpoint.current_revision = revision; + live_intervention_ = std::move(checkpoint); + try { + ModernState entered = g_; + prepare_lineup_entry(entered, team); + g_ = std::move(entered); + } catch (const std::exception& e) { + live_intervention_.reset(); + error = std::string("Die automatische Live-Aufstellung kann nicht geöffnet werden: ") + e.what(); + return false; + } + if (g_.memory.has(::bmh::layout::ActiveManager)) g_.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager)); + return true; +} + +bool ModernSession::finish_live_event_intervention(const LiveMatchEvent& event, MatchEngine& engine, + uint64_t& revision, std::string& error) { + error.clear(); + if (!live_intervention_ || !live_intervention_->source_event || + live_intervention_->event.group_index != event.group_index || + live_intervention_->event.match_index != event.match_index || + live_intervention_->event.side != event.side || live_intervention_->event.team != event.team || + live_intervention_->event.opponent != event.opponent || + live_intervention_->event.player != event.player || live_intervention_->event.kind != event.kind || + live_intervention_->minute != event.minute || live_intervention_->manager != event.manager_slot || + live_intervention_->current_revision != revision || &engine.state != &g_ || + &engine.game != &game_ || &engine.rand != &rand_ || revision == std::numeric_limits::max()) { + error = "Der automatische Live-Menüabschluss ist veraltet oder gehört zu einem anderen Ereignis."; + return false; + } + if (event.group_index >= engine.groups.size() || event.match_index < 0 || event.side < 0 || event.side > 1) { + error = "Das Source-Ereignis gehört nicht mehr zur aktiven Partie."; + return false; + } + const MatchGroup& group = engine.groups[event.group_index]; + if (event.match_index >= group.matches() || + group.fixtures.at(size_t(event.match_index) * 2 + size_t(event.side)) != event.team || + group.fixtures.at(size_t(event.match_index) * 2 + size_t(1 - event.side)) != event.opponent || + (group.kickoff_void_mask >> event.match_index & 1) || (group.void_mask() >> event.match_index & 1)) { + error = "Die aktive Partie hat sich während der automatischen Aufstellung geändert."; + return false; + } + if (engine.groups.size() != live_intervention_->groups.size() || + group.desc != live_intervention_->groups[event.group_index].desc || + group.fixtures != live_intervention_->groups[event.group_index].fixtures) { + error = "Die Matchgruppenstruktur hat sich während der Source-Aufstellung geändert."; + return false; + } + // PitchScreen returns to EventImpl; its single Source rerate remains at the event's + // existing tail, so this boundary only consumes the authenticated modal owner. + ++revision; + live_intervention_.reset(); + return true; +} + +bool ModernSession::finish_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine& engine, uint64_t& revision, std::string& error) { + error.clear(); + if (!live_intervention_ || live_intervention_->minute != minute || + live_intervention_->source_mode != source_mode || live_intervention_->manager != manager || + live_intervention_->team != team || live_intervention_->current_revision != revision || + &engine.state != &g_ || &engine.game != &game_ || &engine.rand != &rand_) { + error = "Der Live-Menüabschluss ist veraltet oder gehört zu einem anderen Eingriff."; + return false; + } + const LiveInterventionCheckpoint& checkpoint = *live_intervention_; + ModernState staged_state = g_; + std::vector staged_groups = engine.groups; + GameRandom staged_game = engine.game; + WatcomRandom staged_rand = engine.rand; + MatchEngine staged_engine(staged_state, staged_groups, staged_game, staged_rand, engine.referees); + staged_engine.indoor = engine.indoor; + staged_engine.alternate_event_roll = engine.alternate_event_roll; + staged_engine.match_events_disabled = engine.match_events_disabled; + staged_engine.live_scene_visible = engine.live_scene_visible; + staged_engine.live_desk_disabled = engine.live_desk_disabled; + staged_engine.month = engine.month; + staged_engine.trace = engine.trace; + staged_engine.show = engine.show; + staged_engine.leave_screens = engine.leave_screens; + staged_engine.buttons = engine.buttons; + MinuteReport report; + staged_engine.rerate_team(team, report); + if (report.unsupported) { + g_ = checkpoint.state; + engine.groups = checkpoint.groups; + engine.game = checkpoint.game; + engine.rand = checkpoint.rand; + revision = checkpoint.initial_revision; + live_intervention_.reset(); + error = "Die Mannschaft kann nach dem Live-Eingriff nicht neu bewertet werden: " + report.reason; + return false; + } + g_ = std::move(staged_state); + engine.groups = std::move(staged_groups); + engine.game = staged_game; + engine.rand = staged_rand; + if (revision == std::numeric_limits::max()) { + g_ = checkpoint.state; + engine.groups = checkpoint.groups; + engine.game = checkpoint.game; + engine.rand = checkpoint.rand; + revision = checkpoint.initial_revision; + live_intervention_.reset(); + error = "Die Live-Menürevisionsnummer ist erschöpft."; + return false; + } + ++revision; + live_intervention_.reset(); + return true; +} + +void ModernSession::abort_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine& engine, uint64_t& revision) { + if (!live_intervention_ || live_intervention_->minute != minute || + live_intervention_->source_mode != source_mode || live_intervention_->manager != manager || + live_intervention_->team != team || &engine.state != &g_ || + &engine.game != &game_ || &engine.rand != &rand_) return; + g_ = std::move(live_intervention_->state); + if (live_intervention_->source_event && engine.groups.size() == live_intervention_->groups.size()) { + // Preserve MatchGroup element addresses held by MatchEngine::event/side; + // side reacquires its record byte pointers immediately after this callback. + for (size_t i = 0; i < engine.groups.size(); ++i) + engine.groups[i] = std::move(live_intervention_->groups[i]); + } else { + engine.groups = std::move(live_intervention_->groups); + } + engine.game = live_intervention_->game; + engine.rand = live_intervention_->rand; + revision = live_intervention_->initial_revision; + live_intervention_.reset(); +} + +bool ModernSession::dispatch_live_substitution(const ui::LineupRequest& request, int minute, + int source_mode, MatchEngine& engine, uint64_t& revision, std::string& error) { + error.clear(); + // PitchScreen stays open for repeated actions; EndPhase rerates once after + // event 8 closes either live menu. + if (source_mode != 2 || request.kind != ui::LineupRequestKind::swap_players || + (minute <= 2 && (!live_intervention_ || !live_intervention_->source_event))) { + error = "Der Eingriff ist in dieser Spielminute nicht verfügbar."; + return false; + } + const int active = request.manager_slot; + const int team = request.runtime_club; + if (!live_intervention_ || live_intervention_->minute != minute || + live_intervention_->source_mode != source_mode || live_intervention_->manager != active || + live_intervention_->team != team || live_intervention_->current_revision != revision || + request.revision != revision || revision == std::numeric_limits::max() || + active < 0 || active > 3 || request.manager_slot != active || team < 0 || + size_t(active) >= g_.manager_teams.size() || g_.manager_teams[size_t(active)] != team || + g_.manager_of(team) != active || team >= int(g_.team_flags.size()) || + &engine.state != &g_ || &engine.game != &game_ || &engine.rand != &rand_) { + error = "Der Eingriff ist veraltet oder gehört nicht zum aktiven Manager."; + return false; + } + const bool current_match = std::any_of(engine.groups.begin(), engine.groups.end(), [this, team](const MatchGroup& group) { + for (int match = 0; match < group.matches(); ++match) { + const uint32_t bit = uint32_t(1) << match; + if ((group.kickoff_void_mask & bit) || (group.void_mask() & bit)) continue; + const int home = group.fixtures.at(size_t(match) * 2); + const int away = group.fixtures.at(size_t(match) * 2 + 1); + if (std::find(g_.live_matches.begin(), g_.live_matches.end(), home) != g_.live_matches.end() && + (team == home || team == away)) return true; + } + return false; + }); + if (!current_match) { + error = "Die Mannschaft spielt in der aktuellen Partie nicht."; + return false; + } + const auto range = squad_range(team); + const bool first_field = request.first_row >= 0 && request.first_row < 11; + const bool second_field = request.second_row >= 0 && request.second_row < 11; + const bool same_zone_exchange = first_field == second_field; + if (request.first_row < 0 || request.second_row < 0 || + size_t(request.first_row) >= range.count || size_t(request.second_row) >= range.count || + request.first_row == request.second_row || + range.first + range.count > g_.squad_slots.size()) { + error = "Die Spielerzeilen sind für den Live-Tausch ungültig."; + return false; + } + const uint16_t outgoing = g_.squad_slots[range.first + size_t(request.first_row)]; + const uint16_t incoming = g_.squad_slots[range.first + size_t(request.second_row)]; + const uint16_t same_zone_role = first_field ? 0x8000 : 0x4000; + if (outgoing != request.first_slot || incoming != request.second_slot || + (outgoing & 0x0fff) != request.first_player || + (incoming & 0x0fff) != request.second_player || + (same_zone_exchange ? ((outgoing & 0xc000) != same_zone_role || (incoming & 0xc000) != same_zone_role) : + (first_field ? (!(outgoing & 0x8000) || !(incoming & 0x4000)) : + (!(incoming & 0x8000) || !(outgoing & 0x4000)))) || + request.first_player < 0 || request.second_player < 0) { + error = "Die Kaderauswahl hat sich inzwischen geändert."; + return false; + } + if (size_t(request.first_player) >= g_.players.size() || size_t(request.second_player) >= g_.players.size()) { + error = "Die Spielerkennung liegt außerhalb des Kaders."; + return false; + } + const Player& first_player = g_.players.at(size_t(request.first_player)); + const Player& second_player = g_.players.at(size_t(request.second_player)); + const auto injury_status = [](const Player& p) { return int(p.w364 >> 16 & 0x1f); }; + // PitchScreen checks both selected players before it distinguishes same-zone + // tactical exchanges from field/bench substitutions. + if (((first_player.w35c >> 27) == 0 && injury_status(first_player) != 0) || + ((second_player.w35c >> 27) == 0 && injury_status(second_player) != 0)) { + error = "source_notice:0xaf13c"; + return false; + } + if (!same_zone_exchange) { + const int field_row = first_field ? request.first_row : request.second_row; + const int bench_row = first_field ? request.second_row : request.first_row; + const int field_player = first_field ? request.first_player : request.second_player; + const int bench_player = first_field ? request.second_player : request.first_player; + const Player& field = g_.players.at(size_t(field_player)); + const Player& bench = g_.players.at(size_t(bench_player)); + const int field_status = int(field.w364 >> 16 & 0x1f); + const int bench_status = int(bench.w364 >> 16 & 0x1f); + if (field_status != 0 && (field.w35c >> 27) == 0) { + error = "source_notice:0xaf140"; + return false; + } + if (bench_status != 0) { + error = "source_notice:0xaf144"; + return false; + } + const int used = int(g_.team_flags.at(size_t(team)) >> 5 & 7); + const int max_substitutions = source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CareerSession_DispatchLiveSubstitution_ExecutableField); + if (used >= max_substitutions) { + error = "source_notice:0xaf150"; + return false; + } + const bool foreign_limit = g_.memory.has(::bmh::layout::ForeignPlayerLimitEnabled) ? g_.memory.u8(::bmh::layout::ForeignPlayerLimitEnabled) != 0 : exe_.u8(::bmh::layout::ForeignPlayerLimitEnabled) != 0; + if (foreign_limit) { + int foreign_on_field = 0; + for (size_t row = 0; row < range.count; ++row) { + const uint16_t slot = g_.squad_slots.at(range.first + row); + if (!(slot & 0x8000) || (slot & 0x0fff) == 0x0fff) continue; + if (modern::nationality(g_, slot & 0x0fff) != 0) ++foreign_on_field; + } + foreign_on_field -= modern::nationality(g_, field_player) != 0; + foreign_on_field += modern::nationality(g_, bench_player) != 0; + if (foreign_on_field >= 4) { + error = "source_notice:0xaf148"; + return false; + } + } + if (bench.w364 & 0x1000) { + error = "source_notice:0xaf14c"; + return false; + } + } + + // Source updates the squad before leaving the child menu; BuildSideRecords3 belongs + // to the single parent-menu completion callback. + ModernState staged_state = g_; + if (same_zone_exchange) { + const size_t first = range.first + size_t(request.first_row); + const size_t second = range.first + size_t(request.second_row); + const size_t board = size_t(active) * 0x840; + if (board + (size_t(std::max(request.first_row, request.second_row)) + 1) * 0x58 > + staged_state.tactics.size()) { + error = "Die taktischen Spielerdaten sind unvollständig."; + return false; + } + auto* a = staged_state.tactics.data() + board + size_t(request.first_row) * 0x58; + auto* b = staged_state.tactics.data() + board + size_t(request.second_row) * 0x58; + const uint8_t ax = a[0x41], ay = a[0x42], bx = b[0x41], by = b[0x42]; + staged_state.squad_slots[first] = uint16_t((incoming & 0x1fff) | (outgoing & 0xc000)); + staged_state.squad_slots[second] = uint16_t((outgoing & 0x1fff) | (incoming & 0xc000)); + std::swap_ranges(a, a + 0x58, b); + a[0x41] = ax; a[0x42] = ay; b[0x41] = bx; b[0x42] = by; + // GatedByParamLive (the desk-card remap) is gated by param_2==0; a live + // marked exchange changes the selected rows but leaves player_cards alone. + } else { + const int field_row = first_field ? request.first_row : request.second_row; + const int bench_row = first_field ? request.second_row : request.first_row; + const auto staged_range = squad_range(team); + const size_t field_at = staged_range.first + size_t(field_row); + const size_t bench_at = staged_range.first + size_t(bench_row); + const uint16_t field_slot = staged_state.squad_slots.at(field_at); + const uint16_t bench_slot = staged_state.squad_slots.at(bench_at); + const int used = int(staged_state.team_flags.at(size_t(team)) >> 5 & 7); + if (!(field_slot & 0x8000) || !(bench_slot & 0x4000) || + (bench_slot & 0x0fff) == 0x0fff || used >= source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CareerSession_DispatchLiveSubstitution_ExecutableField) || + (staged_state.players.at(bench_slot & 0x0fff).w364 & 0x1000)) { + error = "Die Auswechslung erfüllt die Source-Bedingungen nicht."; + return false; + } + const size_t first = std::min(field_at, bench_at), second = std::max(field_at, bench_at); + const size_t board = size_t(active) * 0x840; + if (board + (size_t(bench_row) + 1) * 0x58 > staged_state.tactics.size()) { + error = "Die taktischen Spielerdaten sind unvollständig."; + return false; + } + auto* a = staged_state.tactics.data() + board + size_t(field_row) * 0x58; + auto* b = staged_state.tactics.data() + board + size_t(bench_row) * 0x58; + const uint8_t fx = a[0x41], fy = a[0x42], bx = b[0x41], by = b[0x42]; + b[0] = uint8_t(minute); // EndPhase passes minute + 1 as PitchScreen param_2; source stores param_2 - 1. + staged_state.squad_slots[first] = bench_slot; + staged_state.squad_slots[second] = field_slot; + std::swap_ranges(a, a + 0x58, b); + a[0x41] = fx; a[0x42] = fy; b[0x41] = bx; b[0x42] = by; + staged_state.squad_slots[bench_at] &= 0x1fff; + staged_state.squad_slots[field_at] &= 0x1fff; + staged_state.players.at(bench_slot & 0x0fff).w364 |= 0x1000; + staged_state.squad_slots[field_at] |= 0x8000; + staged_state.squad_slots[bench_at] |= 0x4000; + staged_state.team_flags.at(size_t(team)) = uint16_t( + (staged_state.team_flags.at(size_t(team)) & 0xff1f) | uint16_t(used + 1) << 5); + } + g_ = std::move(staged_state); + ++revision; + live_intervention_->current_revision = revision; + return true; +} + +LiveSubstitutionResult ModernSession::dispatch_live_substitution_result( + const ui::LineupRequest& request, int minute, int source_mode, + MatchEngine& engine, uint64_t& revision) { + std::string error; + if (dispatch_live_substitution(request, minute, source_mode, engine, revision, error)) + return {LiveSubstitutionStatus::applied, 0, request.manager_slot, {}}; + constexpr std::string_view prefix = "source_notice:"; + if (error.compare(0, prefix.size(), prefix) == 0) { + uint32_t address = 0; + try { address = uint32_t(std::stoul(error.substr(prefix.size()), nullptr, 16)); } + catch (...) { return {LiveSubstitutionStatus::rejected, 0, request.manager_slot, + "Invalid internal Source notice address."}; } + return {LiveSubstitutionStatus::source_notice, address, request.manager_slot, {}}; + } + return {LiveSubstitutionStatus::rejected, 0, request.manager_slot, std::move(error)}; +} + +bool ModernSession::dispatch_live_tactic(const ui::TacticsRequest& request, int minute, + int source_mode, MatchEngine& engine, uint64_t& revision, std::string& error) { + error.clear(); + if (minute <= 2 || source_mode != 8 || request.kind != ui::TacticsRequestKind::set_tactic) { + error = "Die Taktikänderung ist in dieser Spielminute nicht verfügbar."; + return false; + } + const int manager = request.manager_slot; + const int team = request.runtime_club; + if (!live_intervention_ || live_intervention_->minute != minute || + live_intervention_->source_mode != source_mode || live_intervention_->manager != manager || + live_intervention_->team != team || live_intervention_->current_revision != revision || + request.revision != revision || revision == std::numeric_limits::max() || + manager < 0 || manager >= int(g_.manager_teams.size()) || team < 0 || + team >= int(g_.team_flags.size()) || team != g_.manager_teams[size_t(manager)] || + g_.manager_of(team) != manager || &engine.state != &g_ || &engine.game != &game_ || &engine.rand != &rand_) { + error = "Die Taktikanfrage ist veraltet oder gehört nicht zum aktiven Manager."; + return false; + } + bool selected_match = false; + for (const MatchGroup& group : engine.groups) { + for (int match = 0; match < group.matches(); ++match) { + const uint32_t bit = uint32_t(1) << match; + if ((group.kickoff_void_mask & bit) || (group.void_mask() & bit)) continue; + const int home = group.fixtures.at(size_t(match) * 2); + const int away = group.fixtures.at(size_t(match) * 2 + 1); + if (std::find(g_.live_matches.begin(), g_.live_matches.end(), home) != g_.live_matches.end() && + (team == home || team == away)) selected_match = true; + } + } + if (!selected_match) { + error = "Die Mannschaft spielt nicht in der aktuell ausgewählten Partie."; + return false; + } + if (request.index < 0 || request.index >= 8 || request.desired_value < 0 || + request.desired_value > exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField + request.index)) { + error = "Ungültige Taktikeinstellung."; + return false; + } + const bool live_option = (g_.memory.has(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) ? g_.memory.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) : exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3)) != 0; + if (live_option && exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField2 + request.index) == 0) { + error = "Diese Taktikeinstellung ist nicht verfügbar."; + return false; + } + if ((request.index == 0 && request.desired_assistant_attitude != std::optional(0)) || + (request.index != 0 && request.desired_assistant_attitude)) { + error = "Ungültige Assistenteneinstellung."; + return false; + } + const size_t record = size_t(manager) * 0xb0c; + const size_t option = size_t(manager) * 5 + 2; + if (g_.manager_records.size() < record + 0xb0c || g_.manager_options.size() <= option) { + error = "Die Taktikdaten sind unvollständig."; + return false; + } + // RerateTeam commits each click to the manager record while the menu stays + // open; EndPhase invokes BuildSideRecords3 exactly once after menu exit. + g_.manager_records[record + 0xd2 + size_t(request.index)] = uint8_t(request.desired_value); + if (request.index == 0) g_.manager_options[option] = 0; + ++revision; + live_intervention_->current_revision = revision; + return true; +} + +bool ModernSession::dispatch_pitch(const ui::PitchRequest& request, uint64_t& revision, + std::string& error) { + if (request.kind == ui::PitchRequestKind::swap_players) { + if (request.runtime_club < 0 || request.runtime_club >= int(g_.team_flags.size()) || + size_t(request.runtime_club + 1) * 2 > g_.club_heap_78.size() || + request.indoor != g_.indoor) { + error = "Der Hallen-/Außenmodus der Spielfeldanfrage ist veraltet."; + return false; + } + ui::LineupRequest lineup; + lineup.kind = ui::LineupRequestKind::swap_players; + lineup.manager_slot = request.manager_slot; lineup.runtime_club = request.runtime_club; + lineup.revision = request.revision; + lineup.first_row = request.row; lineup.first_player = request.player_id; lineup.first_slot = request.slot; + lineup.second_row = request.second_row; lineup.second_player = request.second_player; + lineup.second_slot = request.second_slot; + return dispatch_lineup(lineup, revision, error); + } + if (request.kind != ui::PitchRequestKind::move_player && + request.kind != ui::PitchRequestKind::set_automatic_weight && + request.kind != ui::PitchRequestKind::apply_formation && + request.kind != ui::PitchRequestKind::save_formation && + request.kind != ui::PitchRequestKind::open_set_piece_editor && + request.kind != ui::PitchRequestKind::close_set_piece_editor && + request.kind != ui::PitchRequestKind::set_piece_taker && + request.kind != ui::PitchRequestKind::auto_set_piece_takers && + request.kind != ui::PitchRequestKind::set_player_order && + request.kind != ui::PitchRequestKind::select_pitch_page && + request.kind != ui::PitchRequestKind::set_player_marking) { + error = "Diese Spielfeldaktion ist noch nicht verfügbar."; + return false; + } + // PitchRequest has runtime ownership and a revision, not a caller-supplied + // stable-club token. Cross-check the live mapping and record just as for the + // semantic desk setters, including their tracked phase/modal exclusions. + const int count = g_.memory.has(::bmh::layout::ManagerCount) ? int(g_.memory.u8(::bmh::layout::ManagerCount)) : -1; + if (count < 1 || count > 4 || g_.manager_teams.size() != size_t(count) || + request.manager_slot < 0 || request.manager_slot >= count) { + error = "Die Managerdaten der Spielfeldaktion sind unvollständig."; + return false; + } + DeskSettingIdentity identity{request.manager_slot, request.runtime_club, std::nullopt, request.revision}; + if (request.runtime_club >= 0 && size_t(request.runtime_club) < g_.club_ids.size()) + identity.stable_club_identity = int(g_.club_ids[size_t(request.runtime_club)]); + // PitchScreen exposes the prepared Pitch view during initial setup as well as + // during manager desks. A verified line-up owner in the still-empty turn loop + // is sufficient authority there; ordinary automation/ticket settings remain + // desk-only. Keep all nested desk mutations blocked while allowing this Source + // line-up window before the first desk has been created. + const bool live_context = live_intervention_ && live_intervention_->source_mode == 2 && + request.manager_slot == live_intervention_->manager && + request.runtime_club == live_intervention_->team && + request.revision == live_intervention_->current_revision && request.revision == revision; + const bool desk_phase = turn_driver_.stage == TurnDriver::Stage::MatchdayDesks || + turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk; + const bool initial_lineup_phase = turn_driver_.stage == TurnDriver::Stage::Empty && + lineup_entry_manager_ == request.manager_slot && lineup_entry_club_ == request.runtime_club; + if (!desk_phase && !initial_lineup_phase && !live_context) { error = "desk_setting_unavailable"; return false; } + if (!live_context && (pending_offer_dispatch_active_ || market_dispatch_active_ || calendar_advance_active_ || + transfer_offer_editor_ || manager_join_ || contract_quote_ || stadium_.investment || + stadium_.tip || stadium_.periphery_quote)) { + error = "desk_setting_unavailable"; return false; + } + if (live_context) { + const int manager = live_intervention_->manager; + const int team = live_intervention_->team; + const size_t rec = size_t(manager) * 0xb0c; + if (request.indoor != g_.indoor || manager < 0 || manager >= int(g_.manager_teams.size()) || + g_.manager_teams[size_t(manager)] != team || g_.manager_of(team) != manager || + size_t(team) >= g_.club_ids.size() || rec + 0xb0c > g_.manager_records.size() || + (int(g_.manager_records[rec + 0x290]) | int(g_.manager_records[rec + 0x291]) << 8) != team) { + error = "Die Spielfeldaktion gehört nicht zum aktiven Live-Manager."; return false; + } + } else if (!validate_desk_setting_owner(identity, revision, error, false)) return false; + const size_t badge = size_t(request.runtime_club) * 2; + const int mode = g_.memory.has(::bmh::layout::GameMode) ? int(g_.memory.u8(::bmh::layout::GameMode)) : int(exe_.u8(::bmh::layout::GameMode)); + if (request.runtime_club >= int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) || g_.lineups_frozen || + mode < 1 || mode > 3 || g_.manager_options[size_t(request.manager_slot) * 5] > 8 || + request.indoor != g_.indoor || + (!live_context && (lineup_entry_manager_ != request.manager_slot || + lineup_entry_club_ != request.runtime_club)) || badge + 1 >= g_.club_heap_78.size()) { + error = "Diese Spielfeldaktion ist nicht für die vorbereitete Aufstellung freigegeben."; + return false; + } + if ((request.kind == ui::PitchRequestKind::apply_formation || + request.kind == ui::PitchRequestKind::save_formation) && request.new_weights != request.old_weights) { + error = "Die Gewichtung der Aufstellungsanfrage wurde geändert."; + return false; + } + const auto selected_live_opponent = [&](int opponent) { + if (!live_context || opponent < 0 || opponent >= int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField))) return false; + return std::any_of(live_intervention_->groups.begin(), live_intervention_->groups.end(), + [&](const MatchGroup& group) { + for (int match = 0; match < group.matches(); ++match) { + const uint32_t bit = uint32_t(1) << match; + if ((group.kickoff_void_mask & bit) || (group.void_mask() & bit)) continue; + const int home = group.fixtures.at(size_t(match) * 2); + const int away = group.fixtures.at(size_t(match) * 2 + 1); + if (std::find(g_.live_matches.begin(), g_.live_matches.end(), home) != g_.live_matches.end() && + ((home == request.runtime_club && away == opponent) || + (away == request.runtime_club && home == opponent))) return true; + } + return false; + }); + }; + const auto selected_source_opponent = [&](int opponent) { + if (live_context) return selected_live_opponent(opponent); + const auto prepared = prepared_lineup_opponent(request.manager_slot, + request.runtime_club, request.revision); + return prepared && *prepared == opponent; + }; + if (request.kind == ui::PitchRequestKind::select_pitch_page && request.page_control == 4 && + (request.indoor || g_.indoor || !selected_source_opponent(request.opponent_team))) { + error = "Die Manndeckungsseite ist für diese Partie nicht verfügbar."; + return false; + } + if (request.kind == ui::PitchRequestKind::set_player_marking && + (request.indoor || g_.indoor || !selected_source_opponent(request.opponent_team))) { + error = "Die Manndeckung gehört nicht zur aktuellen Außenspielpartie."; + return false; + } + try { + ModernState staged = g_; + bool accepted = false; + const size_t manager_rec = size_t(request.manager_slot) * 0xb0c; + static constexpr size_t set_piece_offsets[] = {0xafc,0xafe,0xb08}; + std::array current_set_piece{}; + for(size_t i=0;i<3;++i){const size_t at=manager_rec+set_piece_offsets[i]; + current_set_piece[i]=uint16_t(staged.manager_records.at(at)|uint16_t(staged.manager_records.at(at+1))<<8);} + const uint32_t display_at=uint32_t(::bmh::layout::CareerSession_AnyOf_ExecutableField+request.manager_slot*2); + const bool editor_action=request.kind==ui::PitchRequestKind::open_set_piece_editor|| + request.kind==ui::PitchRequestKind::close_set_piece_editor|| + request.kind==ui::PitchRequestKind::set_piece_taker|| + request.kind==ui::PitchRequestKind::auto_set_piece_takers; + if(request.kind==ui::PitchRequestKind::select_pitch_page&& + (!staged.memory.has(display_at)||request.expected_display_word!=staged.memory.u16(display_at)|| + request.expected_set_piece_values!=current_set_piece|| + request.expected_set_piece_signature!=uint16_t(staged.manager_records.at(manager_rec+0xb0a)|uint16_t(staged.manager_records.at(manager_rec+0xb0b))<<8)|| + request.expected_mode!=mode||request.indoor!=staged.indoor||request.page_control<0||request.page_control>4)){ + error="Der Seitenwechsel am Spielfeld ist veraltet oder ungültig.";return false; + } + if (request.kind == ui::PitchRequestKind::set_player_marking) { + if (!staged.memory.has(display_at) || + request.expected_display_word != staged.memory.u16(display_at) || + (request.expected_display_word & 0x0040) == 0 || staged.indoor || + request.opponent_team < 0 || !selected_source_opponent(request.opponent_team) || + size_t(request.opponent_team) >= staged.team_flags.size()) { + error = "Die Manndeckungsanfrage ist veraltet oder nicht auf der Source-Seite aktiv."; + return false; + } + const SquadRange own = squad_range(request.runtime_club); + const SquadRange opponent = squad_range(request.opponent_team); + const size_t own_board = size_t(request.manager_slot) * 0x840; + if (own.count < 11 || opponent.count < 11 || own.first + 11 > staged.squad_slots.size() || + opponent.first + 11 > staged.squad_slots.size() || own_board + 11 * 0x58 > staged.tactics.size()) { + error = "Die Mannschaftstaktik enthält keine vollständigen Spielerzeilen."; + return false; + } + if (request.opponent_row < 1 || request.opponent_row >= 11 || + staged.squad_slots.at(opponent.first + size_t(request.opponent_row)) != request.opponent_slot || + (request.opponent_slot & 0xc000) != 0x8000 || + (request.opponent_slot & 0x0fff) != request.opponent_player || + request.opponent_player < 0 || size_t(request.opponent_player) >= staged.players.size()) { + error = "Der ausgewählte Gegenspieler gehört nicht mehr zur gegnerischen Feldaufstellung."; + return false; + } + bool clear = request.row == -1 && request.player_id == -1; + if (clear) { + if (request.expected_marking_player_id != uint16_t(request.opponent_player)) { + error = "Die zu löschende Manndeckung ist veraltet."; + return false; + } + } else { + if (request.row < 0 || request.row >= 11 || + staged.squad_slots.at(own.first + size_t(request.row)) != request.slot || + (request.slot & 0xc000) != 0x8000 || (request.slot & 0x0fff) != request.player_id || + request.player_id < 0 || size_t(request.player_id) >= staged.players.size()) { + error = "Der ausgewählte eigene Feldspieler gehört nicht mehr zur Aufstellung."; + return false; + } + const size_t own_row_at = own_board + size_t(request.row) * 0x58; + const uint16_t current = uint16_t(staged.tactics.at(own_row_at + 0x44) | + uint16_t(staged.tactics.at(own_row_at + 0x45)) << 8); + if (current != request.expected_marking_player_id) { + error = "Die bestehende Manndeckung wurde inzwischen geändert."; + return false; + } + } + } + if(editor_action && (!staged.memory.has(display_at)||request.expected_set_piece_values!=current_set_piece|| + request.expected_display_word!=staged.memory.u16(display_at)||request.expected_mode!=mode||request.indoor!=staged.indoor|| + request.expected_set_piece_signature!=uint16_t(staged.manager_records.at(manager_rec+0xb0a)|uint16_t(staged.manager_records.at(manager_rec+0xb0b))<<8)|| + uint16_t(staged.manager_records.at(manager_rec+0xb0a)|uint16_t(staged.manager_records.at(manager_rec+0xb0b))<<8)!=0x3253)){ + error="Der Schützenauftrag ist veraltet oder unvollständig.";return false; + } + const bool editor_open=staged.memory.has(display_at)&&(staged.memory.u16(display_at)&0x80)!=0; + // The low-80 native bit survives Padded when the whole Pitch view + // returns. Screen-local editor runtime is reset on each new view, so a + // Source Schütze entry is valid even when the retained word already has + // bit80; mutations and editor-page exits still require that active bit. + if((request.kind==ui::PitchRequestKind::close_set_piece_editor|| + request.kind==ui::PitchRequestKind::set_piece_taker|| + request.kind==ui::PitchRequestKind::auto_set_piece_takers)&&!editor_open){ + error="Der Schützenauftrag passt nicht zum aktuellen Anzeigestatus.";return false; + } + if(request.kind==ui::PitchRequestKind::set_player_order){ + if(request.expected_mode!=mode||request.expected_display_word!=staged.memory.u16(display_at)|| + request.expected_set_piece_values!=current_set_piece|| + request.expected_set_piece_signature!=uint16_t(staged.manager_records.at(manager_rec+0xb0a)|uint16_t(staged.manager_records.at(manager_rec+0xb0b))<<8)|| + request.row<0||request.row>=11||request.order_aspect<0||request.order_aspect>3|| + mode==1||!staged.memory.has(display_at)||(staged.memory.u16(display_at)&0x0070)!=0x0020|| + request.new_order_value<2||request.new_order_value>40|| + request.new_order_value==request.expected_order_value){ + error="Der Anweisungsauftrag ist ungültig.";return false; + } + const size_t row_at=size_t(request.manager_slot)*0x840+size_t(request.row)*0x58; + if(row_at+6>staged.tactics.size()|| + (staged.squad_slots.at(squad_range(request.runtime_club).first+size_t(request.row))!=request.slot)|| + (request.slot&0x0fff)!=request.player_id|| + staged.tactics[row_at+2+size_t(request.order_aspect)]!=request.expected_order_value){ + error="Die Anweisungszeile wurde inzwischen geändert.";return false; + } + } + switch (request.kind) { + case ui::PitchRequestKind::set_automatic_weight: + accepted = set_pitch_automatic_weight_source(staged, request.manager_slot, request.runtime_club, + request.weight_index, request.old_weights, request.new_weights); + break; + case ui::PitchRequestKind::move_player: + accepted = move_pitch_player_source(staged, request.manager_slot, request.runtime_club, + request.row, request.player_id, request.slot, request.old_depth, request.old_lane, + request.new_depth, request.new_lane); + break; + case ui::PitchRequestKind::apply_formation: + accepted = apply_pitch_formation_source(staged, request.manager_slot, request.runtime_club, + request.formation, request.old_weights); + break; + case ui::PitchRequestKind::save_formation: + accepted = save_pitch_formation_source(staged, request.manager_slot, request.runtime_club, + request.formation, request.old_weights, request.formation_positions); + break; + case ui::PitchRequestKind::open_set_piece_editor: { + const uint16_t expected=uint16_t((request.expected_display_word&0xff00)| + ((request.expected_display_word&0x008f)|0x0080)); + accepted=request.new_display_word==expected&& + normalize_pitch_set_piece_source(staged,request.manager_slot,request.runtime_club); + if(accepted)staged.memory.set16(display_at,expected); + break; + } + case ui::PitchRequestKind::close_set_piece_editor: { + const uint16_t expected=uint16_t(request.expected_display_word&~uint16_t(0x80)); + accepted=(request.expected_display_word&0x80)!=0&&request.new_display_word==expected; + if(accepted)staged.memory.set16(display_at,expected); + break; + } + case ui::PitchRequestKind::set_piece_taker: + accepted=request.set_piece_selector>=2&&request.set_piece_selector<=4&& + request.expected_set_piece_value==current_set_piece[size_t(request.set_piece_selector-2)]&& + set_pitch_set_piece_taker_source(staged,request.manager_slot,request.runtime_club, + request.set_piece_selector,request.row,request.player_id,request.slot,request.expected_set_piece_value); + break; + case ui::PitchRequestKind::auto_set_piece_takers: + accepted=auto_pitch_set_piece_takers_source(staged,request.manager_slot,request.runtime_club, + request.expected_set_piece_values); + break; + case ui::PitchRequestKind::set_player_order: + accepted=set_player_order_source(staged,request.manager_slot,request.runtime_club,request.row, + request.player_id,request.order_aspect,request.new_order_value); + break; + case ui::PitchRequestKind::set_player_marking: { + const size_t board = size_t(request.manager_slot) * 0x840; + for (size_t row = 0; row < 11; ++row) { + const size_t at = board + row * 0x58 + 0x44; + const uint16_t marker = uint16_t(staged.tactics.at(at) | uint16_t(staged.tactics.at(at + 1)) << 8); + if (marker == uint16_t(request.opponent_player)) { + staged.tactics[at] = 0xff; + staged.tactics[at + 1] = 0x0f; + } + } + if (request.row >= 0) { + const size_t at = board + size_t(request.row) * 0x58 + 0x44; + staged.tactics[at] = uint8_t(request.opponent_player); + staged.tactics[at + 1] = uint8_t(uint16_t(request.opponent_player) >> 8); + } + accepted = true; + break; + } + case ui::PitchRequestKind::select_pitch_page: { + const uint16_t old=request.expected_display_word; + uint16_t next=old; + switch(request.page_control){ + case 0: next=uint16_t((old&~uint16_t(0x80))^0x0003); break; // Data toggles its source word. + case 1: next=uint16_t(old^0x000c); break; // Team is the original inner-loop toggle. + case 2: next=uint16_t(((old&~uint16_t(0x0080))&0x008f)|0x0010); break; + case 3: next=uint16_t(((old&~uint16_t(0x0080))&0x008f)|0x0020); break; + case 4: next=uint16_t(((old&~uint16_t(0x0080))&0x008f)|0x0040); break; + default: break; + } + accepted=staged.memory.has(display_at)&&request.new_display_word==next&& + !((request.page_control==3)&&mode==1); + if(accepted)staged.memory.set16(display_at,next); + break; + } + default: break; + } + if (!accepted) { + error = "Die Spielfeldaktion ist veraltet oder in dieser Aufstellung nicht verfügbar."; + return false; + } + g_ = std::move(staged); + } catch (const std::exception&) { + // Keep pitch requests transactional if a malformed native projection throws. + error = "Diese Aufstellung kann im aktuellen Spielmodus noch nicht übernommen werden."; + return false; + } + ++revision; + if (live_context) live_intervention_->current_revision = revision; + error.clear(); + return true; +} + +bool ModernSession::dispatch_live_pitch(const ui::PitchRequest& request, int minute, int source_mode, + MatchEngine& engine, uint64_t& revision, std::string& error) { + if (!live_intervention_ || live_intervention_->minute != minute || + live_intervention_->source_mode != source_mode || source_mode != 2 || + live_intervention_->manager != request.manager_slot || + live_intervention_->team != request.runtime_club || + live_intervention_->current_revision != revision || request.revision != revision || + &engine.state != &g_ || &engine.game != &game_ || &engine.rand != &rand_) { + error = "Die Spielfeldaktion gehört zu keinem aktiven Live-Menü."; + return false; + } + if (request.kind == ui::PitchRequestKind::swap_players) { + ui::LineupRequest swap; + swap.kind = ui::LineupRequestKind::swap_players; + swap.manager_slot = request.manager_slot; swap.runtime_club = request.runtime_club; + swap.revision = request.revision; + swap.first_row = request.row; swap.first_player = request.player_id; swap.first_slot = request.slot; + swap.second_row = request.second_row; swap.second_player = request.second_player; + swap.second_slot = request.second_slot; + return dispatch_live_substitution(swap, minute, source_mode, engine, revision, error); + } + // PitchScreen's live param_2 is nonzero: these formation and weight controls + // exist only in its param_2==0 initial-preparation path. + if (request.kind == ui::PitchRequestKind::set_automatic_weight || + request.kind == ui::PitchRequestKind::apply_formation || + request.kind == ui::PitchRequestKind::save_formation) { + error = "Diese Aufstellungsoption ist außerhalb der Vorbereitungsphase nicht verfügbar."; + return false; + } + return dispatch_pitch(request, revision, error); +} + +LiveSubstitutionResult ModernSession::dispatch_live_pitch_result(const ui::PitchRequest& request, + int minute, int source_mode, MatchEngine& engine, uint64_t& revision) { + if (request.kind == ui::PitchRequestKind::swap_players) { + ui::LineupRequest swap; + swap.kind = ui::LineupRequestKind::swap_players; + swap.manager_slot = request.manager_slot; swap.runtime_club = request.runtime_club; + swap.revision = request.revision; + swap.first_row = request.row; swap.first_player = request.player_id; swap.first_slot = request.slot; + swap.second_row = request.second_row; swap.second_player = request.second_player; + swap.second_slot = request.second_slot; + return dispatch_live_substitution_result(swap, minute, source_mode, engine, revision); + } + std::string error; + const bool applied = dispatch_live_pitch(request, minute, source_mode, engine, revision, error); + return {applied ? LiveSubstitutionStatus::applied : LiveSubstitutionStatus::rejected, + 0, request.manager_slot, std::move(error)}; +} + +bool ModernSession::dispatch_pitch_swap(const ui::PitchRequest& request, uint64_t& revision, + std::string& error) { + if (request.kind != ui::PitchRequestKind::swap_players) { + error = "Diese Spielfeldaktion ist kein Spielerwechsel."; + return false; + } + return dispatch_pitch(request, revision, error); +} + +ui::PreparationState ModernSession::preparation_projection(uint64_t revision) const { + return preparation_projection(g_, revision); +} + +std::optional ModernSession::prepared_lineup_opponent(int manager_slot, int runtime_club, + uint64_t revision) const { + if (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks || g_.indoor || + manager_slot < 0 || manager_slot >= int(g_.manager_teams.size()) || + manager_slot != lineup_entry_manager_ || runtime_club != lineup_entry_club_ || + !g_.memory.has(::bmh::layout::ActiveManager) || + int(g_.memory.u8(::bmh::layout::ActiveManager)) != manager_slot || + g_.manager_teams[size_t(manager_slot)] != runtime_club || + runtime_club == no_team() || runtime_club < 0 || + runtime_club >= int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) || g_.manager_of(runtime_club) != manager_slot || + size_t(manager_slot) >= source_desk_callargs_.size()) + return std::nullopt; + + const ui::DeskMatchCallargs& source = source_desk_callargs_[size_t(manager_slot)]; + const int opponent = source.opponent; + if (opponent < 0 || opponent == runtime_club || opponent >= int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) || + source.competition == 32 || source.competition == 33 || source.competition == 34) + return std::nullopt; + uint32_t competitions = modern::day_competitions(g_, turn_driver_.calendar_entry); + if (competitions == 0x800000) competitions = 0; + const int default_competition = competitions != 0 ? 34 : 33; + ModernState manager_view = g_; + manager_view.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager_slot)); + const ui::DeskState projected = ui::desk_from_game(manager_view, exe_, revision, + &turn_driver_.groups, default_competition); + if (projected.manager_slot != manager_slot || projected.runtime_club != runtime_club || + !projected.next_opponent || *projected.next_opponent != opponent || + !projected.next_competition || *projected.next_competition != source.competition) + return std::nullopt; + const SquadRange rival_roster = squad_range(opponent); + if (rival_roster.count < 11 || rival_roster.first + rival_roster.count > g_.squad_slots.size()) + return std::nullopt; + + // The captured DayCompetitions2 callargs already encode Source's group order and + // overwrite rules. Confirm that exact pair still exists in this Matchday; + // never substitute another fixture if it has become void or unsupported. + bool current_pair = false; + for (const MatchGroup& group : turn_driver_.groups) { + if (group.fixtures.size() < size_t(group.matches()) * 2) continue; + const int type = group.desc.empty() ? -1 : group.desc.at(0); + int mapped_competition = -1, league = -1; + if (type == 0) { + if (group.desc.size() < 0xd0) continue; + league = int(le32(group.desc, 0xcc)); + if (league >= 0 && league < 9) + mapped_competition = int(exe_.u8(::bmh::layout::LeagueCalendarBits + uint32_t(league))); + } else if (type > 0) { + mapped_competition = type + 4; + } + for (int match = 0; match < group.matches(); ++match) { + const int home = group.fixtures.at(size_t(match) * 2); + const int away = group.fixtures.at(size_t(match) * 2 + 1); + if (!((home == runtime_club && away == opponent) || + (away == runtime_club && home == opponent))) continue; + bool valid = mapped_competition == source.competition; + const uint32_t bit = uint32_t(1) << match; + valid = valid && !(group.kickoff_void_mask & bit) && !(group.void_mask() & bit); + if (valid && type == 0) { + bool has_result = false; + uint8_t raw_result = 0xcc; + if (size_t(match) < group.results.size()) { + has_result = true; + raw_result = group.results[size_t(match)]; + } else if (league >= 0 && league < int(g_.league_rounds.size())) { + const int round = int(g_.league_rounds[size_t(league)]); + const size_t result_at = size_t(league) * 0x17c + size_t(round) * 10 + size_t(match); + if (round >= 0 && result_at < g_.results.size()) { + has_result = true; + raw_result = g_.results[result_at]; + } + } + if (has_result && raw_result != 0xcc) valid = false; + } + // MatchdayNeedsManagerDesks overwrites the per-manager callargs in group order. + // The last matching pair therefore decides whether this exact + // callarg is still a supported, unplayed fixture. + current_pair = valid; + } + } + return current_pair ? std::optional(opponent) : std::nullopt; +} + +ui::PreparationState ModernSession::preparation_projection(const ModernState& state, uint64_t revision) const { + auto result = ui::preparation_from_game(state, exe_, revision); + result.desktop = desktop_projection(state, revision); + if (lineup_entry_manager_ == result.lineup.manager_slot && + lineup_entry_club_ == result.lineup.runtime_club) { + result.lineup.entry_prepared = true; + if (result.pitch) { + const auto opponent = prepared_lineup_opponent(result.lineup.manager_slot, + result.lineup.runtime_club, revision); + if (opponent) + result.pitch = ui::pitch_extras_from_game(state, exe_, revision, *opponent); + } + } + if (result.bank) { + result.bank->last_tip = last_stock_tip_; + result.bank->property_notice = last_property_notice_; + result.bank->credit_notice = last_credit_notice_; + } + if (result.stadium) { + const int team = result.stadium->runtime_club; + const int stable = int(state.club_ids.at(size_t(team))); + const bool owned = stadium_.manager == result.stadium->manager_slot && + stadium_.club == team && stadium_.stable_club == stable && stadium_.revision == revision; + *result.stadium = ui::stadium_from_game(state, exe_, revision, owned ? stadium_.price_percent : 100); + auto& stadium = *result.stadium; + stadium.source = result.desktop.source; + stadium.club_name = result.desktop.club_name; + stadium.stable_club_identity = stable; + stadium.plain_background = source_runtime_byte(state, club_modal_runtime_, exe_, ::bmh::layout::PlainBackground) != 0; + stadium.decorated_stadium_header = !stadium.plain_background; + stadium.compact_dialog_frame = source_runtime_byte(state, club_modal_runtime_, exe_, ::bmh::layout::CompactDialogFrame) != 0; + stadium.solid_panel_background = source_runtime_byte(state, club_modal_runtime_, exe_, ::bmh::layout::SolidPanelBackground) != 0; + stadium.gradient_text = source_runtime_byte(state, club_modal_runtime_, exe_, ::bmh::layout::TextGradientDisabled) == 0 && + source_runtime_byte(state, club_modal_runtime_, exe_, ::bmh::layout::TextGradientMode) == 2; + stadium.source_level = state.level; + stadium.season_tickets = uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x2ac)) | + uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x2ad)) << 8; + const int source_team = int16_t(uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x290)) | + uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x291)) << 8); + const int source_league = source_team > 0x164 ? 0 : team_league(source_team); + if (source_league < 0 || size_t(source_league) >= state.league_rounds.size()) + throw FormatError("stadium source league is outside the live league table"); + stadium.live_league_round = state.league_rounds.at(size_t(source_league)); + stadium.ticket_refund_rate = std::bit_cast(exe_.u32(::bmh::layout::CareerSession_FormatError_RuntimeField5 + uint32_t(source_league) * 4)); + stadium.investments_enabled = state.memory.u8(::bmh::layout::GameMode) != 1; + for (size_t i = 0; i < stadium.investments.size(); ++i) { + stadium.investments[i].original_label = texts_[734 + i]; + if (!stadium.investments_enabled) stadium.investments[i].available = false; + } + if (owned) { + stadium.opened = stadium_.opened; + stadium.scope = stadium_.scope; stadium.sequence = stadium_.sequence; + if (stadium_.data_open) + stadium.data = ui::stadium_data_from_game(state, exe_, stadium.manager_slot, stadium_.data_flags); + stadium.selected_investment = stadium_.investment; + if (stadium_.option_index >= 0) stadium.selected_option = stadium_.option_index; + stadium.investment_text_variant = stadium_.text_variant; + stadium.action_feedback = stadium_.feedback; + if (stadium_.tip) { + PendingOfferQuestion question; + question.manager = stadium_.manager; question.source_flags = 0x204; + question.original_message = message_text(state, ::bmh::layout::CareerSession_FormatError_TextPointer8) + + format_number(state, stadium_.tip->percent, 1) + message_text(state, ::bmh::layout::CareerSession_FormatError_TextPointer9); + stadium.construction_tip_dialog = ui::pending_offer_question_dialog(state, question); + stadium.construction_tip_price = stadium_.tip->offered_price; + } + if (stadium_.periphery_quote) { + stadium.quoted_object = stadium_.periphery_quote->first; + stadium.quoted_price = stadium_.periphery_quote->second; + PendingOfferQuestion question; + question.manager = stadium_.manager; + question.source_flags = 1; // ConstructionPricePercent -> PresentManagerDialog: ordinary JA/NEIN question. + question.original_message = message_text(state, ::bmh::layout::CareerSession_FormatError_TextPointer6) + + format_number(state, stadium.quoted_price, 0x106) + message_text(state, ::bmh::layout::CareerSession_FormatError_TextPointer7); + stadium.periphery_quote_dialog = ui::pending_offer_question_dialog(state, question); + stadium.periphery_quote_dialog->compact_dialog_frame = stadium.compact_dialog_frame; + } + if (stadium_.block_expansion) { + const auto& draft = *stadium_.block_expansion; + ui::StadiumBlockExpansionEditor editor; + editor.quote = draft.quote; + editor.total_target_places = draft.total_target_places; + editor.desired_features = draft.desired_features; + editor.header_text_variant = draft.header_text_variant; + editor.offer = draft.tip; + const uint32_t current = uint32_t(draft.quote.current_capacity_thousands) * 1000; + const uint32_t added = draft.total_target_places - current; + editor.current_places_text = format_number(state, int32_t(current), 5); + editor.new_places_text = format_number(state, int32_t(added), 5); + editor.target_places_text = format_number(state, int32_t(draft.total_target_places), 5); + const auto cost_text = [&](uint32_t amount) { + return format_number(state, int32_t(amount), 0x181) + exe_.cstring(::bmh::layout::CareerSession_FormatNumber_ExecutableField); + }; + editor.per_thousand_cost_text = format_number(state, int32_t(draft.quote.price_per_1000), 0x181); + editor.new_places_cost_text = cost_text(draft.quote.new_places_cost); + editor.seats_cost_text = cost_text(draft.quote.seats_cost); + editor.roof_cost_text = cost_text(draft.quote.roof_cost); + editor.total_cost_text = cost_text(draft.quote.base_price); + editor.discount_text = exe_.cstring(::bmh::layout::CareerSession_FormatNumber_TextPointer) + + format_number(state, 100 - stadium_.price_percent, 1) + exe_.cstring(::bmh::layout::CareerSession_FormatNumber_ExecutableField2); + stadium.block_expansion = std::move(editor); + } + if (stadium_.block_expansion && stadium_.block_expansion->tip) { + PendingOfferQuestion question; + question.manager = stadium_.manager; + question.source_flags = 0x204; + question.original_message = message_text(state, ::bmh::layout::CareerSession_FormatError_TextPointer8) + + format_number(state, stadium_.block_expansion->tip->percent, 1) + + message_text(state, ::bmh::layout::CareerSession_FormatError_TextPointer9); + stadium.construction_tip_dialog = ui::pending_offer_question_dialog(state, question); + stadium.construction_tip_dialog->compact_dialog_frame = stadium.compact_dialog_frame; + stadium.construction_tip_price = stadium_.block_expansion->tip->offered_price; + } + } + } + return result; +} + +bool ModernSession::dispatch_training(const ui::TrainingRequest& request, uint64_t& revision, + std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + if (request.manager_slot != active || request.manager_slot < 0 || request.manager_slot > 3 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) { + error = "stale_manager_or_revision"; + return false; + } + + try { + const ui::TrainingState current = ui::training_from_game(g_, exe_, revision); + if (current.manager_slot != request.manager_slot || current.runtime_club != request.runtime_club) { + error = "stale_manager_or_revision"; + return false; + } + const size_t slot = size_t(request.manager_slot); + const size_t rec = slot * 0xb0c; + const size_t option_at = slot * 5 + 4; + if (g_.manager_records.size() < rec + 0xb0c || g_.manager_options.size() <= option_at) { + error = "invalid_training_state"; + return false; + } + + auto valid_plan = [](const std::array& types, const std::array& areas) { + int type_sum = 0, fitness = 0, skills = 0; + for (uint8_t value : types) { if (value < 1 || value > 3) return false; type_sum += value; } + for (size_t i = 0; i < areas.size(); ++i) { + const uint8_t value = areas[i]; + if (value < 1 || value > 3) return false; + if (i < 2) fitness += value; else skills += value; + } + return type_sum <= 8 && fitness <= 4 && skills <= 18; + }; + if (!valid_plan(request.desired_types, request.desired_areas)) { + error = "invalid_training_plan"; + return false; + } + + ui::TrainingRequestKind kind = request.kind; + auto types = current.types; + auto areas = current.areas; + uint8_t automation = current.automation; + bool run_automatic = false; + // NeedsInitialization initializes an uninitialized screen via Initialize; + // the four subordinate toggles exist only while the global flag is on. + // NeedsInitialization2 calls that same deterministic routine after an enabled + // automation toggle. Manual field edits only write their field and clear + // the matching assistant flag; they do not run training or draw RNG. + switch (kind) { + case ui::TrainingRequestKind::initialize: + if (!current.needs_initialization() || request.index != -1 || request.value != -1 || + request.player_id != -1 || request.desired_types != types || request.desired_areas != areas || + request.desired_automation != 0x9f) { + error = "invalid_training_initialization"; + return false; + } + automation = 0x9f; + run_automatic = true; + break; + case ui::TrainingRequestKind::set_type: + if (current.needs_initialization() || request.index < 0 || request.index >= int(types.size()) || + request.value < 1 || request.value > 3 || request.player_id != -1 || + request.value == types[size_t(request.index)]) { + error = "invalid_training_type"; + return false; + } + types[size_t(request.index)] = uint8_t(request.value); + automation = uint8_t(automation & ~uint8_t(1u << 1)); + break; + case ui::TrainingRequestKind::set_area: + if (current.needs_initialization() || request.index < 0 || request.index >= int(areas.size()) || + request.value < 1 || request.value > 3 || request.player_id != -1 || + request.value == areas[size_t(request.index)]) { + error = "invalid_training_area"; + return false; + } + areas[size_t(request.index)] = uint8_t(request.value); + automation = uint8_t(automation & ~uint8_t(1u << 2)); + break; + case ui::TrainingRequestKind::set_player_intensity: + case ui::TrainingRequestKind::set_player_focus: { + if (current.needs_initialization() || request.index < 0 || request.index >= current.squad_capacity || + request.player_id < 0 || request.player_id > 0x0ffe) { + error = "invalid_training_player"; + return false; + } + const auto player = std::find_if(current.players.begin(), current.players.end(), [&](const auto& p) { + return p.row == request.index && p.player_id == request.player_id; + }); + const SquadRange squad = squad_range(request.runtime_club); + if (player == current.players.end() || squad.count != size_t(current.squad_capacity) || + squad.first + size_t(request.index) >= g_.squad_slots.size() || + (g_.squad_slots[squad.first + size_t(request.index)] & 0x0fff) != request.player_id) { + error = "stale_training_player"; + return false; + } + if (kind == ui::TrainingRequestKind::set_player_intensity) { + if (request.value < 1 || request.value > 3 || request.value == player->intensity) { + error = "invalid_training_intensity"; + return false; + } + automation = uint8_t(automation & ~uint8_t(1u << 3)); + } else if (request.value < 0 || request.value > 7 || request.value != (player->focus + 1) % 8) { + error = "invalid_training_focus"; + return false; + } + break; + } + case ui::TrainingRequestKind::set_automation: { + if (current.needs_initialization() || request.index < 0 || request.index > 4 || + (request.value != 0 && request.value != 1) || request.player_id != -1) { + error = "invalid_training_automation"; + return false; + } + if (request.index != 0 && !(current.automation & 1)) { + error = "training_automation_group_hidden"; + return false; + } + const uint8_t mask = uint8_t(1u << request.index); + automation = uint8_t(automation ^ mask); + if (((automation & mask) != 0) != (request.value != 0)) { + error = "stale_training_automation"; + return false; + } + run_automatic = (automation & 1) != 0; + break; + } + case ui::TrainingRequestKind::none: + default: + error = "unsupported_training_request"; + return false; + } + + if (request.desired_types != types || request.desired_areas != areas || + request.desired_automation != automation) { + error = "stale_training_projection"; + return false; + } + + ModernState staged = g_; + std::copy(types.begin(), types.end(), staged.manager_records.begin() + rec + 0xc5); + std::copy(areas.begin(), areas.end(), staged.manager_records.begin() + rec + 0xc9); + staged.manager_options[option_at] = automation; + if (kind == ui::TrainingRequestKind::set_player_intensity || + kind == ui::TrainingRequestKind::set_player_focus) { + const size_t board = slot * 0x840 + size_t(request.index) * 0x58 + 0x0a; + if (board >= staged.tactics.size()) { + error = "invalid_training_board"; + return false; + } + if (kind == ui::TrainingRequestKind::set_player_intensity) + staged.tactics[board] = uint8_t((staged.tactics[board] & 0xfc) | request.value); + else + staged.tactics[board] = uint8_t((staged.tactics[board] & 0x03) | (request.value << 2)); + } + if (run_automatic) modern::auto_training(staged, request.manager_slot); + g_ = std::move(staged); + ++revision; + error.clear(); + return true; + } catch (const std::exception&) { + error = "invalid_training_state"; + return false; + } +} + +void ModernSession::capture_source_desk_callargs() { + source_desk_callargs_.clear(); + const auto stage = turn_driver_.stage; + if (stage != TurnDriver::Stage::MatchdayDesks && + stage != TurnDriver::Stage::SeasonEndDesk) + return; + uint32_t competitions = 0; + int default_competition = 32; + const std::vector* groups = nullptr; + if (stage == TurnDriver::Stage::MatchdayDesks) { + competitions = modern::day_competitions(g_, turn_driver_.calendar_entry); + if (competitions == 0x800000) competitions = 0; + default_competition = competitions != 0 ? 34 : 33; + groups = &turn_driver_.groups; + } + // DayCompetitions2 initializes the full four-slot callarg arrays before joining + // any manager desk: FF opponents, competition 33/34 (or 32 at season end). + source_desk_callargs_.assign(4, ui::DeskMatchCallargs{default_competition, -1}); + for (size_t slot = 0; slot < g_.manager_teams.size(); ++slot) { + if (slot >= source_desk_callargs_.size()) + throw FormatError("desk: too many manager slots while capturing Source callargs"); + if (!groups) continue; + ModernState manager_view = g_; + if (!manager_view.memory.has(::bmh::layout::ActiveManager)) + throw FormatError("desk: active manager field is missing while capturing Source callargs"); + manager_view.memory.set8(::bmh::layout::ActiveManager, uint8_t(slot)); + const ui::DeskState source = ui::desk_from_game( + manager_view, exe_, turn_driver_.revision, groups, default_competition); + source_desk_callargs_[slot] = {source.next_competition.value_or(default_competition), + source.next_opponent.value_or(-1)}; + } +} + +ui::DeskState ModernSession::desktop_projection(uint64_t revision) const { + return desktop_projection(g_, revision); +} + +ui::DeskState ModernSession::desktop_projection(const ModernState& state, uint64_t revision) const { + std::optional source_default; + if (turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk) { + source_default = 32; + } else if (turn_driver_.stage == TurnDriver::Stage::MatchdayDesks) { + uint32_t competitions = modern::day_competitions(state, turn_driver_.calendar_entry); + if (competitions == 0x800000) competitions = 0; + source_default = competitions != 0 ? 34 : 33; + } else { + // An unsupported/empty saved cursor is not evidence that the Source + // dispatcher produced its no-fixture default. Keep those fields unknown. + return ui::desk_from_game(state, exe_, revision); + } + const int slot = int(state.memory.u8(::bmh::layout::ActiveManager)); + const ui::DeskMatchCallargs defaults{source_default.value_or(34), -1}; + const ui::DeskMatchCallargs* callargs = &defaults; + if (slot >= 0 && size_t(slot) < source_desk_callargs_.size()) + callargs = &source_desk_callargs_[size_t(slot)]; + return ui::desk_from_game(state, exe_, revision, &turn_driver_.groups, source_default, callargs); +} + +void ModernSession::configure_autosave_directory(const std::filesystem::path& directory) { + if (autosave_directory_ && *autosave_directory_ == directory) return; + if (calendar_advance_active_) throw FormatError("autosave directory change during active turn"); + autosave_directory_ = directory; + turn_driver_.desk_autosave = [this](const ModernState& state, WatcomRandom& random) { + write_desk_autosave(state, random); + }; +} + +std::string ModernSession::take_autosave_error() { + return std::exchange(autosave_error_, {}); +} + +void ModernSession::write_desk_autosave(const ModernState& state, WatcomRandom& random) { + // OpenBMH deviates from the original: native saves do not consume gameplay randomness for encryption. + if (content::find(data_directory_)) { + native_autosave_pending_ = bool(autosave_directory_); + return; + } + std::filesystem::path temporary; + try { + if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_)) + throw FormatError("autosave directory unavailable"); + // CareerSession_Name_TextPointer is the Original TEXTD filename, not the manual browser name. + const std::filesystem::path name(texts_.strings.at((::bmh::layout::CareerSession_Name_TextPointer - ::bmh::layout::TextPointerTable) / 4)); + if (name.empty() || name != name.filename() || name.extension() != ".FBM") + throw FormatError("invalid Original autosave filename"); + const auto target = *autosave_directory_ / name; + if (std::filesystem::is_symlink(std::filesystem::symlink_status(target)) || + std::filesystem::is_directory(target)) throw FormatError("autosave target unavailable"); + WatcomRandom staged = random; + const auto saved = modern::make_savegame(state, staged); + temporary = target; + temporary += ".tmp-" + std::to_string(saved.id2); + if (std::filesystem::exists(std::filesystem::symlink_status(temporary))) { + temporary.clear(); + throw FormatError("autosave temporary target already exists"); + } + modern::write_savegame(temporary, saved); + if (std::filesystem::is_symlink(std::filesystem::symlink_status(target)) || + std::filesystem::is_directory(target)) throw FormatError("autosave target changed"); + std::filesystem::rename(temporary, target); + temporary.clear(); + random = staged; + } catch (const std::exception& e) { + autosave_error_ = e.what(); + if (!temporary.empty()) { + std::error_code ignored; + std::filesystem::remove(temporary, ignored); + } + } +} + +cli::Json ModernSession::native_session_context() const { + cli::Json::Array runtime, callargs, managers; + for (const auto &[address, value] : club_modal_runtime_) + runtime.emplace_back(cli::Json::Object{{"address", int64_t(address)}, {"value", int(value)}}); + for (const auto &args : source_desk_callargs_) + callargs.emplace_back(cli::Json::Array{args.competition, args.opponent}); + for (const auto &manager : managers_) + managers.emplace_back(cli::Json::Array{manager.slot, manager.master_club, manager.runtime_club}); + return cli::Json::Object{{"schema", "classic-session@1.0"}, + {"runtime", std::move(runtime)}, + {"desk_callargs", std::move(callargs)}, + {"managers", std::move(managers)}}; +} +void ModernSession::restore_native_session_context(const cli::Json &root) { + const auto field = [&](const char *name) -> const cli::Json & { + if (!root.object() || !root.object()->contains(name)) + throw FormatError("Native session field missing"); + return root.object()->at(name); + }; + if (!field("schema").string() || *field("schema").string() != "classic-session@1.0") + throw FormatError("Unsupported native session"); + const auto array = [](const cli::Json &j, size_t maximum) -> const cli::Json::Array & { + if (!j.array() || j.array()->size() > maximum) + throw FormatError("Invalid native session array"); + return *j.array(); + }; + const auto integer = [](const cli::Json &j, int64_t low, int64_t high) -> int64_t { + if (!j.integer() || *j.integer() < low || *j.integer() > high) + throw FormatError("Invalid native session integer"); + return *j.integer(); + }; + std::map runtime; + for (const auto &row : array(field("runtime"), 8192)) { + if (!row.object() || !row.object()->contains("address") || !row.object()->contains("value")) + throw FormatError("Invalid runtime byte"); + const auto at = uint32_t(integer(row.object()->at("address"), 0, UINT32_MAX)); + if (!club_modal_runtime_.contains(at) || + !runtime.emplace(at, uint8_t(integer(row.object()->at("value"), 0, 255))).second) + throw FormatError("Unknown or duplicated runtime byte"); + } + if (runtime.size() != club_modal_runtime_.size()) + throw FormatError("Incomplete native runtime bytes"); + std::vector callargs; + for (const auto &row : array(field("desk_callargs"), 4)) { + const auto &fields = array(row, 2); + if (fields.size() != 2) + throw FormatError("Invalid desk arguments"); + callargs.push_back({int(integer(fields[0], -1, 255)), int(integer(fields[1], -1, 4095))}); + } + std::vector managers; + for (const auto &row : array(field("managers"), 4)) { + const auto &fields = array(row, 3); + if (fields.size() != 3) + throw FormatError("Invalid manager mapping"); + managers.push_back({int(integer(fields[0], 0, 3)), int(integer(fields[1], 0, 4095)), + int(integer(fields[2], 0, 4095))}); + } + club_modal_runtime_ = std::move(runtime); + source_desk_callargs_ = std::move(callargs); + managers_ = std::move(managers); +} +void ModernSession::flush_native_autosave() { + if (!std::exchange(native_autosave_pending_, false)) + return; + try { + if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_)) + throw FormatError("Autosave directory unavailable"); + const auto resource = content::find(data_directory_); + if (!resource) + throw FormatError("Native content unavailable"); + content::save_career(*autosave_directory_ / "AUTOSAVE.obs", *resource->content, g_, rand_, game_, + turn_driver_, true, native_session_context()); + } catch (const std::exception &e) { + autosave_error_ = e.what(); + } +} + +bool ModernSession::save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error) { + if (advertising_renewal_dispatch_active_) { error="save_blocked_during_advertising_renewal"; return false; } + if(balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_|| + top_scorers_owner_||top_scorers_dispatch_active_ || stadium_.block_expansion||other_games_owner_||other_games_dispatch_active_){error="strengths_active";return false;} + if(balance_draft_||balance_dispatch_active_||league_pairings_draft_||league_pairings_dispatch_active_){error="league_pairings_active";return false;} + if (transfer_offer_editor_) { error = "transfer_offer_editor_active"; return false; } + if (pending_offer_dispatch_active_) { error = "pending_offer_decision_active"; return false; } + if (market_dispatch_active_) { error = "transfer_market_decision_active"; return false; } + if (career_complete()) { error = "career_complete"; return false; } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + std::string extension = path.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + if (manager_slot != active || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() || + extension != (content::find(data_directory_) ? ".obs" : ".fbm") || path.filename().empty()) { + error = "invalid_save_request"; return false; + } + std::error_code ec; + if (!std::filesystem::is_directory(path.parent_path(), ec) || ec) { + error = "save_directory_unavailable"; return false; + } + const auto status = std::filesystem::symlink_status(path, ec); + if (!ec && std::filesystem::is_symlink(status)) { error = "save_target_is_symlink"; return false; } + ec.clear(); + const bool exists = std::filesystem::exists(path, ec); + if (ec || (exists && !overwrite)) { error = exists ? "overwrite_confirmation_required" : "save_target_unavailable"; return false; } + try { + if (const auto resource = content::find(data_directory_)) { + content::save_career(path, *resource->content, g_, rand_, game_, turn_driver_, overwrite, + native_session_context()); + return true; + } + WatcomRandom staged_rand = rand_; + const Savegame save = modern::make_savegame(g_, staged_rand); + modern::write_savegame(path, save); + rand_ = staged_rand; + return true; + } catch (const std::exception&) { + error = "save_write_failed"; return false; + } +} + +bool ModernSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uint64_t& revision, + std::string& error) { + constexpr uint32_t kLayouts = ::bmh::layout::Desktops; + constexpr size_t kLayoutBytes = 0x360; + constexpr int kDeskItemCount = 54; + if (request.file_kind != ui::SaveLoadFileKind::menu_layout || + request.origin_item_id < 0 || request.origin_item_id >= kDeskItemCount) { + error = "invalid_menu_layout_origin"; return false; + } + if (request.revision != revision || revision == UINT64_MAX || request.path.filename().empty() || + request.manager_slot < 0 || request.manager_slot > 3 || + !g_.memory.has(::bmh::layout::ActiveManager) || int(g_.memory.u8(::bmh::layout::ActiveManager)) != request.manager_slot) { + error = "stale_menu_layout_owner"; return false; + } + if (calendar_advance_active_ || live_intervention_ || career_complete() || + (turn_driver_.stage != TurnDriver::Stage::Empty && + turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk) || + pending_offer_dispatch_active_ || market_dispatch_active_ || transfer_offer_editor_ || + manager_join_ || contract_quote_ || advertising_renewal_dispatch_active_ || + balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || opportunities_owner_ || + opportunities_dispatch_active_ || league_pairings_draft_ || league_pairings_dispatch_active_ || + league_family_owner_ || league_family_teaminfo_active_ || other_games_owner_ || + other_games_dispatch_active_ || stadium_.block_expansion || stadium_.investment || + stadium_.tip || stadium_.periphery_quote) { + error = "menu_layout_unavailable_during_active_flow"; return false; + } + std::string extension = request.path.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), + [](unsigned char c) { return char(std::tolower(c)); }); + if (extension != (content::find(data_directory_) ? ".oblayout" : ".men")) { + error = "invalid_menu_layout_extension"; + return false; + } + const size_t active_base = size_t(request.manager_slot) * 0xb0c; + if (active_base + 0xb0c > g_.manager_records.size() || + size_t(request.manager_slot) >= g_.manager_teams.size() || + (int(g_.manager_records[active_base + 0x290]) | + int(g_.manager_records[active_base + 0x291]) << 8) != g_.manager_teams[size_t(request.manager_slot)]) { + error = "menu_layout_manager_record_mismatch"; return false; + } + if (!g_.memory.has(kLayouts + uint32_t(request.manager_slot) * uint32_t(kLayoutBytes) + + uint32_t(kLayoutBytes - 1))) { + error = "menu_layout_memory_unavailable"; return false; + } + // CopyN returns the matching record index. In the native MEN file, + // the final bar cell (source value 72) resolves to record 53; DeskDate + // dispatches that index to the menu-layout chooser. + const uint32_t base = kLayouts + uint32_t(request.manager_slot) * uint32_t(kLayoutBytes); + const int source_item = g_.memory.u8(base + 53u * 16u + 12u) == 72 ? 53 : -1; + if (source_item != request.origin_item_id) { error = "menu_layout_source_handle_unavailable"; return false; } + + const auto validate_payload = [&](const Bytes& bytes) -> bool { + if (bytes.size() != kLayoutBytes) { error = "menu_layout_wrong_size"; return false; } + // Bound the forward traversal before asking the desk projector to + // validate geometry, kinds, and remaining source fields. Native layouts + // may contain valid custom back-links; Source load does not normalize them. + std::array seen{}; + const int head = bytes[5]; + // CopyN permits an empty linked drawer (head == 0). + if (head == 0) return true; + if (head < 1 || head >= kDeskItemCount) { error = "menu_layout_invalid_head"; return false; } + int item = head; + for (int steps = 0; steps < kDeskItemCount; ++steps) { + if (item <= 0 || item >= kDeskItemCount || seen[size_t(item)]) { + error = "menu_layout_invalid_chain"; return false; + } + seen[size_t(item)] = true; + const size_t at = size_t(item) * 16; + item = bytes[at + 5]; + if (item == 0) return true; + if (item == 0xff) { error = "menu_layout_invalid_chain_terminator"; return false; } + } + error = "menu_layout_chain_cycle"; return false; + }; + + if (request.action == ui::SaveLoadAction::load) { + Bytes payload; + try { + payload = content::find(data_directory_) + ? content::load_preferences(request.path, "layout", kLayoutBytes) + : read_file(request.path); + } catch (const std::exception &) { + error = "menu_layout_read_failed"; + return false; + } + if (!validate_payload(payload)) return false; + ModernState staged = g_; + for (size_t i = 0; i < kLayoutBytes; ++i) + staged.memory.set8(base + uint32_t(i), payload[i]); + try { + (void)desktop_projection(staged, revision + 1); + } catch (const std::exception&) { error = "menu_layout_projection_invalid"; return false; } + g_ = std::move(staged); + ++revision; + error.clear(); + return true; + } + if (request.action != ui::SaveLoadAction::save) { + error = "invalid_menu_layout_action"; + return false; + } + + std::error_code ec; + if (!std::filesystem::is_directory(request.path.parent_path(), ec) || ec) { + error = "menu_layout_directory_unavailable"; return false; + } + ec.clear(); + const auto status = std::filesystem::symlink_status(request.path, ec); + if (!ec && std::filesystem::is_symlink(status)) { error = "menu_layout_target_is_symlink"; return false; } + ec.clear(); + const bool exists = std::filesystem::exists(request.path, ec); + if (ec || (exists && !request.overwrite)) { + error = exists ? "menu_layout_overwrite_confirmation_required" : "menu_layout_target_unavailable"; + return false; + } + Bytes payload(kLayoutBytes); + for (size_t i = 0; i < kLayoutBytes; ++i) payload[i] = g_.memory.u8(base + uint32_t(i)); + if (!validate_payload(payload)) return false; + try { + if (content::find(data_directory_)) { + content::save_preferences(request.path, "layout", payload, request.overwrite); + ++revision; + error.clear(); + return true; + } + std::ofstream file(request.path, std::ios::binary | std::ios::trunc); + if (!file) { error = "menu_layout_write_failed"; return false; } + file.write(reinterpret_cast(payload.data()), std::streamsize(payload.size())); + file.flush(); + if (!file) { error = "menu_layout_write_failed"; return false; } + } catch (const std::exception&) { error = "menu_layout_write_failed"; return false; } + ++revision; + error.clear(); + return true; +} + +bool ModernSession::dispatch_training_camp(const ui::TrainingCampRequest& request, uint64_t& revision, + std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (request.manager_slot < 0 || size_t(request.manager_slot) >= g_.manager_teams.size() || + request.manager_slot != int(g_.memory.u8(::bmh::layout::ActiveManager)) || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) { + error = "stale_manager_or_revision"; + return false; + } + const size_t rec = size_t(request.manager_slot) * 0xb0c; + if (request.kind == ui::TrainingCampRequestKind::set_focus) { + const std::array current{ + g_.manager_records.at(rec + 0xc1), g_.manager_records.at(rec + 0xc2), + g_.manager_records.at(rec + 0xc3), g_.manager_records.at(rec + 0xc4)}; + if (request.focus == current) { + error = "focus_unchanged"; + return false; + } + if (!modern::set_training_camp_focus(g_, request.manager_slot, request.focus)) { + error = "invalid_focus_request"; + return false; + } + ++revision; + return true; + } + if (request.kind == ui::TrainingCampRequestKind::book) { + if (request.resort < 0 || request.resort >= kTrainingCampResorts) { + error = "invalid_resort"; + return false; + } + const std::array current{ + g_.manager_records.at(rec + 0xc1), g_.manager_records.at(rec + 0xc2), + g_.manager_records.at(rec + 0xc3), g_.manager_records.at(rec + 0xc4)}; + if (request.focus != current) { + error = "stale_focus"; + return false; + } + switch (modern::training_camp_booking_block(g_, request.manager_slot)) { + case TrainingCampBookingBlock::booked_this_week: error = "booked_this_week"; return false; + case TrainingCampBookingBlock::visit_limit: error = "visit_limit"; return false; + case TrainingCampBookingBlock::invalid_request: error = "invalid_request"; return false; + case TrainingCampBookingBlock::none: break; + } + if (!modern::book_training_camp(g_, request.manager_slot, request.resort, rand_)) { + error = "insufficient_funds"; + return false; + } + ++revision; + return true; + } + error = "unsupported_training_camp_request"; + return false; +} + +bool ModernSession::dispatch_bank(const ui::BankRequest& request, uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + error.clear(); + if (revision == std::numeric_limits::max()) { + error = "revision_exhausted"; return false; + } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + if (request.manager_slot != active || + request.manager_slot < 0 || size_t(request.manager_slot) >= g_.manager_teams.size() || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) { + error = "stale_manager_or_revision"; return false; + } + const size_t rec = size_t(request.manager_slot) * 0xb0c; + std::optional property_notice; + std::optional credit_notice; + const auto read_signed = [&](size_t offset) { + const uint32_t v = uint32_t(g_.manager_records.at(rec + offset)) | + uint32_t(g_.manager_records.at(rec + offset + 1)) << 8 | + uint32_t(g_.manager_records.at(rec + offset + 2)) << 16 | + uint32_t(g_.manager_records.at(rec + offset + 3)) << 24; + return int32_t(v); + }; + if (request.kind == ui::BankRequestKind::move_to_deposit) { + if (!request.amount || request.asset_index != -1 || request.count != 0 || + int64_t(request.amount > 0 ? request.amount : -int64_t(request.amount)) > 99999999) { + error = "invalid_amount"; return false; + } + const int64_t available = request.amount > 0 ? read_signed(0x314) : read_signed(0x318); + if (available < 0 || int64_t(request.amount > 0 ? request.amount : -int64_t(request.amount)) > available) { + error = "amount_unavailable"; return false; + } + modern::move_to_deposit(g_, request.manager_slot, request.amount); + } else if (request.kind == ui::BankRequestKind::buy_shares || request.kind == ui::BankRequestKind::sell_shares || + request.kind == ui::BankRequestKind::stock_tip) { + if (request.asset_index < 0 || request.asset_index >= kStocks || + g_.stocks.size() < size_t(kStocks) * 0x5c) { error = "invalid_stock"; return false; } + const size_t at = size_t(request.asset_index) * 0x5c; + const int price = int(uint16_t(g_.stocks.at(at + 0x4e) | uint16_t(g_.stocks.at(at + 0x4f)) << 8)); + if (request.kind == ui::BankRequestKind::buy_shares) { + if (request.count <= 0 || request.count > 9999 || price <= 0 || + request.count > modern::max_shares_to_buy(g_, request.manager_slot, request.asset_index)) { + error = "invalid_share_count"; return false; + } + const int64_t raw = int64_t(price) * request.count; + const int64_t total = raw + raw * 15 / 1000; + if (total > int64_t(read_signed(0x314)) + read_signed(0x31c)) { + error = "insufficient_funds"; return false; + } + if (!modern::buy_shares(g_, request.manager_slot, request.asset_index, request.count)) { + error = "investment_limit"; return false; + } + } else if (request.kind == ui::BankRequestKind::sell_shares) { + const size_t held_at = at + 0x50 + size_t(request.manager_slot) * 2; + const int held = int(uint16_t(g_.stocks.at(held_at) | uint16_t(g_.stocks.at(held_at + 1)) << 8)); + if (request.count <= 0 || request.count > held) { error = "invalid_share_count"; return false; } + modern::sell_shares(g_, request.manager_slot, request.asset_index, request.count); + } else { + if (request.count != 0 || request.amount != 0) { error = "invalid_tip_request"; return false; } + last_stock_tip_ = modern::stock_tip(g_, request.manager_slot, request.asset_index, rand_); + } + } else if (request.kind == ui::BankRequestKind::buy_fund || request.kind == ui::BankRequestKind::sell_fund) { + if (request.amount != 0 || request.asset_index < 0 || request.asset_index >= kFunds || request.count <= 0 || request.count > 10 || + g_.memory.u32(::bmh::layout::FundBlock + uint32_t(request.asset_index) * 0x1c) == 0) { + error = "invalid_fund_request"; return false; + } + const uint32_t fund_at = ::bmh::layout::FundBlock + uint32_t(request.asset_index) * 0x1c; + const uint16_t held = g_.memory.u16(fund_at + 0x14 + uint32_t(request.manager_slot) * 2); + if (request.kind == ui::BankRequestKind::buy_fund) { + if (request.count > modern::max_fund_units(g_, request.manager_slot, request.asset_index)) { + error = "invalid_fund_count"; return false; + } + const int32_t additional_cost = modern::buy_fund_units(g_, request.manager_slot, request.asset_index, request.count, game_); + if (request.asset_index != 0) { + const std::string text = message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer2) + format_number(g_, additional_cost, 0x101) + + message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer); + property_notice = ui::BankState::PropertyNotice{request.asset_index, additional_cost, ui::original_to_utf8(text)}; + } + } else { + if (request.count > held) { error = "invalid_fund_count"; return false; } + modern::sell_fund_units(g_, request.manager_slot, request.asset_index, request.count); + } + } else if (request.kind == ui::BankRequestKind::bank_credit) { + if (request.amount != 0 || request.asset_index != -1 || request.count != 0 || request.credit_edits.empty()) { + error = "invalid_credit_request"; return false; + } + if (request.credit_counterparty != 0) { + // Source case 5 scans configured human managers, excluding the borrower. + // A runtime national-manager entry is not an additional human lender. + const int configured = int(g_.memory.u8(::bmh::layout::ManagerCount)); + if (request.credit_counterparty < 1 || request.credit_counterparty > 4) { + error = "invalid_credit_request"; return false; + } + const int lender = request.credit_counterparty - 1; + if (configured < 1 || configured > 4 || request.manager_slot >= configured || + lender < 0 || lender >= configured || lender == request.manager_slot) { + error = "invalid_credit_request"; return false; + } + } + const auto result = modern::commit_bank_credit(g_, exe_, request.manager_slot, + request.expected_credit, request.credit_edits, request.accept_credit_fees, request.credit_counterparty); + if (result.status != BankCreditStatus::accepted) { + error = result.status == BankCreditStatus::no_change ? "credit_no_change" : + result.status == BankCreditStatus::stale_request ? "stale_credit_request" : + result.status == BankCreditStatus::confirmation_required ? "credit_confirmation_required" : + "invalid_credit_request"; + return false; + } + if (result.refund != 0) { + // "Die Bank" (CareerSession_Int32T_TextPointer3) or, in case 5, the lender's name (record +0xa8) + const int lender = request.credit_counterparty - 1; + std::string who = message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer3); + if (lender >= 0) { + who.clear(); + for (size_t i = 0; i < 26; ++i) { + const uint8_t ch = g_.manager_records.at(size_t(lender) * 0xb0c + 0xa8 + i); + if (!ch) break; + who += char(ch); + } + } + const std::string text = who + message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer4) + + format_number(g_, result.refund, 0x101) + message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer5); + credit_notice = ui::BankState::CreditNotice{result.refund, ui::original_to_utf8(text)}; + } + } else { + error = "unsupported_bank_request"; return false; + } + last_property_notice_ = std::move(property_notice); + last_credit_notice_ = std::move(credit_notice); + ++revision; + return true; +} + +bool ModernSession::stadium_tip_deadline_expired() const { + if (!stadium_.opened || (!stadium_.tip && + (!stadium_.block_expansion || !stadium_.block_expansion->tip))) return false; + const auto byte = [this](uint32_t address) { + if (g_.memory.has(address)) return g_.memory.u8(address); + const auto found = club_modal_runtime_.find(address); + return found == club_modal_runtime_.end() ? exe_.u8(address) : found->second; + }; + const auto word = [&byte](uint32_t address) { + uint32_t value = 0; + for (unsigned i = 0; i < 4; ++i) value |= uint32_t(byte(address + i)) << (8 * i); + return value; + }; + return word(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2) != 0 && int32_t(word(::bmh::layout::CareerSession_FormatError_ExecutableField2)) < 1; +} + +bool ModernSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, uint64_t& revision, std::string& error, + const ConstructionNoticeHook& notice_presenter, + const SeasonTicketCompensationNoticeHook& compensation_presenter) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + auto request = supplied_request; + // Existing CLI periphery callers predate the UI scope envelope. Restrict + // this compatibility adapter to their four original operations and an + // entirely absent envelope; investments and close remain strictly owned. + const bool legacy_periphery = !request.stable_club_identity && request.scope == 0 && request.sequence == 0 && + (request.kind == ui::StadiumRequestKind::open || request.kind == ui::StadiumRequestKind::quote_periphery || + request.kind == ui::StadiumRequestKind::decline_periphery || request.kind == ui::StadiumRequestKind::build_periphery); + if (legacy_periphery && active >= 0 && active <= 3 && size_t(active) < g_.manager_teams.size() && + request.runtime_club >= 0 && size_t(request.runtime_club) < g_.club_ids.size()) { + request.stable_club_identity = int(g_.club_ids[size_t(request.runtime_club)]); + if (request.kind != ui::StadiumRequestKind::open) { + request.scope = stadium_.scope; request.sequence = stadium_.sequence; + } + } + const bool block_action = is_block_expansion_action(request.kind); + if (!block_action && (request.block_slot != -1 || request.block_total_places != 0 || + request.block_features != 0 || request.expected_block_quote)) { + error = "unexpected_block_expansion_fields"; return false; + } + if (request.manager_slot != active || active < 0 || active > 3 || + size_t(active) >= g_.manager_teams.size() || request.runtime_club != g_.manager_teams[size_t(active)] || + request.runtime_club < 0 || request.runtime_club >= no_team() || + size_t(request.runtime_club) >= g_.club_ids.size() || + request.stable_club_identity != std::optional(int(g_.club_ids[size_t(request.runtime_club)])) || + request.revision != revision || revision == UINT64_MAX || !g_.memory.has(::bmh::layout::GameMode)) { + error = "stale_manager_or_revision"; return false; + } + const size_t record = size_t(active) * 0xb0c; + if (record + 0xb0c > g_.manager_records.size() || + (int(g_.manager_records[record + 0x290]) | int(g_.manager_records[record + 0x291]) << 8) != request.runtime_club) { + error = "invalid_stadium_owner"; return false; + } + const int mode = g_.memory.u8(::bmh::layout::GameMode); + if (mode < 1 || mode > 3) { error = "invalid_stadium_mode"; return false; } + if (request.kind == ui::StadiumRequestKind::open) { + const bool legacy_reentry = legacy_periphery && !stadium_.data_open && !stadium_.investment && !stadium_.tip && + !stadium_.block_expansion; + if ((stadium_.opened && !legacy_reentry) || request.scope != 0 || request.sequence != 0 || request.object != -1 || + request.option != -1 || request.price != 0 || request.accept_tip || next_stadium_scope_ == UINT64_MAX) { + error = "invalid_stadium_open"; return false; + } + } else if (!stadium_.opened || stadium_.manager != active || stadium_.club != request.runtime_club || + stadium_.stable_club != *request.stable_club_identity || stadium_.mode != mode || + stadium_.revision != revision || request.scope != stadium_.scope || + request.sequence != stadium_.sequence || stadium_.sequence == UINT64_MAX) { + error = "stale_stadium_scope"; return false; + } + auto before = stadium_checkpoint(); + const uint64_t before_revision = revision; + try { + const auto apply = [&]() -> bool { + const auto invalid = [&error](const char* reason) { error = reason; return false; }; + const auto plain = [&request](int object = -1) { + return request.object == object && request.option == -1 && request.price == 0 && !request.accept_tip; + }; + const auto clear_investment = [this] { + stadium_.investment.reset(); stadium_.selection_status.reset(); stadium_.option.reset(); stadium_.tip.reset(); + stadium_.option_index = -1; stadium_.text_variant = -1; + }; + StadiumInvestmentConstants constants; + for (unsigned i = 0; i < 8; ++i) { + constants.price[i] = exe_.u32(::bmh::layout::CareerSession_DispatchStadium_RuntimeField + i * 4); + constants.weeks[i] = exe_.u8(::bmh::layout::CareerSession_DispatchStadium_RuntimeField2 + (14 + i) * 5); + } + const auto options = [&](StadiumInvestment investment) { + return modern::stadium_investment_options_source(g_, active, investment, stadium_.price_percent, constants); + }; + const auto selected_valid = [&]() { + if (!stadium_.investment || !stadium_.option || stadium_.option_index < 0) return false; + const auto current = options(*stadium_.investment); + return size_t(stadium_.option_index) < current.size() && + current[size_t(stadium_.option_index)] == *stadium_.option; + }; + if (request.kind == ui::StadiumRequestKind::open) { + StadiumRuntime opened; + opened.opened = true; opened.manager = active; opened.club = request.runtime_club; + opened.stable_club = *request.stable_club_identity; opened.mode = mode; + opened.scope = next_stadium_scope_++; + opened.price_percent = modern::construction_price_percent(g_, active, game_); + if (opened.price_percent < 1 || opened.price_percent > 427) return invalid("invalid_stadium_discount"); + stadium_ = std::move(opened); + return true; + } + if (request.kind == ui::StadiumRequestKind::close) { + if (stadium_.data_open || !plain() || stadium_.investment || stadium_.periphery_quote || stadium_.tip || + stadium_.block_expansion) + return invalid("invalid_stadium_close"); + stadium_.opened = false; stadium_.periphery_quote.reset(); clear_investment(); + stadium_.feedback.clear(); return true; + } + const bool data_action = request.kind == ui::StadiumRequestKind::open_data || + request.kind == ui::StadiumRequestKind::toggle_data_curve || + request.kind == ui::StadiumRequestKind::toggle_data_scale || + request.kind == ui::StadiumRequestKind::set_data_ticket_price || + request.kind == ui::StadiumRequestKind::close_data; + if (data_action) { + if (stadium_.investment || stadium_.periphery_quote || stadium_.tip || stadium_.block_expansion || + request.option != -1 || request.price != 0 || request.accept_tip) + return invalid("invalid_stadium_data_context"); + if (request.kind == ui::StadiumRequestKind::open_data) { + if (stadium_.data_open || request.object != -1) return invalid("invalid_stadium_data_open"); + const uint32_t flags_at = ::bmh::layout::Flags + uint32_t(active) * 3 + 1; + if (!g_.memory.has(flags_at)) return invalid("missing_stadium_data_flags"); + stadium_.data_flags = g_.memory.u8(flags_at); + // Build the pure projection before accepting modal ownership. + (void)ui::stadium_data_from_game(g_, exe_, active, stadium_.data_flags); + stadium_.data_open = true; + } else { + if (!stadium_.data_open) return invalid("stadium_data_not_open"); + if (request.kind == ui::StadiumRequestKind::toggle_data_curve) { + if (request.object < 0 || request.object > 5) return invalid("invalid_stadium_data_curve"); + stadium_.data_flags ^= uint8_t(1u << request.object); + } else if (request.kind == ui::StadiumRequestKind::toggle_data_scale) { + if (request.object < 0 || request.object > 1) return invalid("invalid_stadium_data_scale"); + stadium_.data_flags ^= 0xc0; // Either ABS or REL button toggles both Source bits. + } else if (request.kind == ui::StadiumRequestKind::set_data_ticket_price) { + if (request.object < 10 || request.object > 25) return invalid("invalid_stadium_data_ticket"); + g_.manager_records[record + 0x26e] = uint8_t(request.object); + (void)ui::stadium_data_from_game(g_, exe_, active, stadium_.data_flags); + } else { + if (request.object != -1) return invalid("invalid_stadium_data_close"); + g_.memory.set8(::bmh::layout::Flags + uint32_t(active) * 3 + 1, stadium_.data_flags); + stadium_.data_open = false; + } + } + stadium_.feedback.clear(); + return true; + } + if (stadium_.data_open) return invalid("stadium_data_active"); + if (mode == 1 && !legacy_periphery && + (request.kind == ui::StadiumRequestKind::quote_periphery || + request.kind == ui::StadiumRequestKind::build_periphery || + request.kind == ui::StadiumRequestKind::decline_periphery)) + return invalid("stadium_periphery_disabled"); + if (request.kind == ui::StadiumRequestKind::quote_periphery) { + if (stadium_.investment || stadium_.periphery_quote || stadium_.block_expansion || request.object < 0 || + request.object >= 14 || !plain(request.object)) return invalid("invalid_periphery_offer"); + const size_t object = size_t(request.object); + const uint8_t level = g_.manager_records[record + object]; + if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0)) + return invalid("periphery_unavailable"); + const int32_t price = modern::periphery_offer(g_, request.object, game_); + if (price <= 0) return invalid("invalid_periphery_price"); + stadium_.periphery_quote = std::make_pair(request.object, price); + stadium_.feedback.clear(); return true; + } + if (request.kind == ui::StadiumRequestKind::decline_periphery || + request.kind == ui::StadiumRequestKind::build_periphery) { + if (stadium_.investment || stadium_.block_expansion || !stadium_.periphery_quote || + request.option != -1 || request.accept_tip || + request.object != stadium_.periphery_quote->first || request.price != stadium_.periphery_quote->second) + return invalid("stale_periphery_offer"); + if (request.kind == ui::StadiumRequestKind::build_periphery) { + const size_t object = size_t(request.object); + const uint8_t level = g_.manager_records[record + object]; + if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0)) + return invalid("periphery_unavailable"); + // ConstructionPricePercent consumes this genuine JA even when PayConstruction's + // payment fails. The Source presenter runs before the quote + // is cleared; payment/sponsor effects are not rolled back. + const bool built = modern::build_periphery(g_, active, request.object, + uint32_t(request.price), rand_, notice_presenter); + stadium_.feedback = built || notice_presenter ? std::string{} : message_text(g_, ::bmh::layout::Advertising_FormatError_TextPointer18); + } + stadium_.periphery_quote.reset(); + if (request.kind == ui::StadiumRequestKind::decline_periphery) stadium_.feedback.clear(); + return true; + } + + // A–H uses its own quote/commit domain and remains available in + // Source mode 1, where facilities are disabled. All request fields + // outside the typed block envelope must stay neutral. + if (block_action) { + if (request.object != -1 || request.option != -1 || request.price != 0 || + (request.kind != ui::StadiumRequestKind::expansion_answer_tip && request.accept_tip)) + return invalid("invalid_block_expansion_envelope"); + StadiumBlockExpansionConstants block_constants; + for (unsigned i = 0; i < 8; ++i) { + block_constants.price_per_1000[i] = exe_.u32(::bmh::layout::CareerSession_DispatchStadium_RuntimeField + (i + 8) * 4); + block_constants.weeks[i] = exe_.u8(::bmh::layout::CareerSession_DispatchStadium_RuntimeField2 + (i + 22) * 5); + block_constants.max_places[i] = uint32_t(exe_.u8(::bmh::layout::CareerSession_Invalid_RuntimeField + i)) * 1000; + } + const auto quote_block = [&](StadiumBlockSlot slot, uint32_t total, uint8_t features) { + return modern::quote_stadium_block_expansion(g_, active, slot, total, features, + stadium_.price_percent, block_constants); + }; + if (request.kind == ui::StadiumRequestKind::expansion_select) { + if (stadium_.investment || stadium_.periphery_quote || stadium_.block_expansion || + request.block_slot < 0 || request.block_slot >= 8 || request.block_total_places != 0 || + request.block_features != 0 || request.expected_block_quote) + return invalid("invalid_block_expansion_selection"); + const auto slot = static_cast(request.block_slot); + const uint8_t raw = g_.manager_records.at(record + 0x44 + size_t(request.block_slot)); + const uint32_t current = uint32_t(g_.manager_records.at(record + 0x4c + size_t(request.block_slot))) * 1000; + auto quote = quote_block(slot, current, uint8_t(raw & kBlockFeatures)); + if (!quote) return invalid("block_expansion_unavailable"); + StadiumRuntime::BlockExpansion draft; + draft.quote = *quote; + draft.total_target_places = current; + draft.desired_features = uint8_t(raw & kBlockFeatures); + game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + draft.header_text_variant = game_.range(3, 10); // Front, once on editor entry. + stadium_.block_expansion = std::move(draft); + stadium_.feedback.clear(); + return true; + } + + if (!stadium_.block_expansion || stadium_.investment || stadium_.periphery_quote || + request.block_slot < 0 || request.block_slot >= 8 || + request.block_slot != int(stadium_.block_expansion->quote.slot) || + !request.expected_block_quote || *request.expected_block_quote != stadium_.block_expansion->quote) + return invalid("stale_block_expansion_quote"); + auto& draft = *stadium_.block_expansion; + if (draft.tip) { + const auto& tip = *draft.tip; + const bool valid_tip = tip.decision == StandBlockOfferDecision::Pending && + tip.base_price == draft.quote.base_price && tip.base_days == draft.quote.base_weeks && + tip.price == tip.base_price && tip.percent >= 6 && tip.percent <= 14 && + tip.offered_price == uint32_t(uint64_t(tip.base_price) * uint32_t(100 + tip.percent) / 100); + if (!valid_tip) return invalid("stale_block_expansion_tip"); + } + auto fresh = quote_block(draft.quote.slot, draft.total_target_places, draft.desired_features); + if (!fresh || *fresh != draft.quote) + return invalid("block_expansion_source_changed"); + + const auto matches_draft = [&] { + return request.block_total_places == draft.total_target_places && + request.block_features == draft.desired_features; + }; + switch (request.kind) { + case ui::StadiumRequestKind::expansion_set_total: { + if (draft.tip || request.block_features != draft.desired_features) + return invalid("stale_block_expansion_draft"); + auto next_quote = quote_block(draft.quote.slot, request.block_total_places, draft.desired_features); + if (!next_quote) return invalid("invalid_block_expansion_total"); + draft.total_target_places = request.block_total_places; + draft.quote = *next_quote; + stadium_.feedback.clear(); + return true; + } + case ui::StadiumRequestKind::expansion_toggle_feature: { + const uint8_t changed = uint8_t(request.block_features ^ draft.desired_features); + if (draft.tip || request.block_total_places != draft.total_target_places || + (request.block_features & uint8_t(~kBlockFeatures)) != 0 || + (changed != kBlockSeat && changed != kBlockRoof) || + (request.block_features & uint8_t(draft.quote.current_raw_flags & kBlockFeatures)) != + uint8_t(draft.quote.current_raw_flags & kBlockFeatures)) + return invalid("invalid_block_expansion_feature"); + auto next_quote = quote_block(draft.quote.slot, draft.total_target_places, request.block_features); + if (!next_quote) return invalid("invalid_block_expansion_feature"); + draft.desired_features = request.block_features; + draft.quote = *next_quote; + stadium_.feedback.clear(); + return true; + } + case ui::StadiumRequestKind::expansion_cancel: + if (draft.tip || !matches_draft()) return invalid("stale_block_expansion_cancel"); + stadium_.block_expansion.reset(); + stadium_.feedback.clear(); + return true; + case ui::StadiumRequestKind::expansion_confirm: { + if (draft.tip || !matches_draft()) return invalid("stale_block_expansion_confirm"); + if (draft.quote.base_price == 0) { + stadium_.block_expansion.reset(); + stadium_.feedback.clear(); + return true; + } + auto tip = modern::prepare_stand_block_offer(draft.quote.base_price, draft.quote.base_weeks, rand_); + if (tip.offered_price > uint32_t(INT32_MAX)) + return invalid("block_expansion_tip_price_overflow"); + draft.tip = tip; + stadium_.feedback.clear(); + return true; + } + case ui::StadiumRequestKind::expansion_answer_tip: { + if (!draft.tip || !matches_draft() || request.accept_tip && + uint64_t(draft.tip->base_price) * uint32_t(100 + draft.tip->percent) > + uint64_t(INT32_MAX)) + return invalid("invalid_block_expansion_tip_answer"); + StandBlockOffer resolved = *draft.tip; + modern::resolve_stand_block_offer(resolved, request.accept_tip, rand_); + const bool built = modern::build_stadium_block_expansion(g_, active, draft.quote.slot, + block_constants, draft.quote, resolved, rand_, notice_presenter, compensation_presenter); + stadium_.block_expansion.reset(); + stadium_.feedback = built || notice_presenter ? std::string{} : message_text(g_, ::bmh::layout::Advertising_FormatError_TextPointer18); + return true; + } + default: + return invalid("unsupported_block_expansion_request"); + } + } + if (mode == 1) return invalid("stadium_investments_disabled"); + if (request.kind == ui::StadiumRequestKind::select_investment) { + if (stadium_.investment || stadium_.periphery_quote || stadium_.block_expansion || request.object < 0 || + request.object >= 8 || !plain(request.object)) return invalid("invalid_investment_selection"); + const auto investment = static_cast(request.object); + const auto current = options(investment); + if (current.empty()) return invalid("investment_unavailable"); + game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + stadium_.text_variant = game_.range(3, 10); // Front: exactly once at dialog entry. + stadium_.investment = investment; stadium_.selection_status = current.front().current_status; + stadium_.option_index = -1; stadium_.option.reset(); // Source iVar5=-1 until an explicit tier click. + stadium_.feedback.clear(); return true; + } + if (request.kind == ui::StadiumRequestKind::cancel_investment) { + if (!stadium_.investment || stadium_.tip || !plain(int(*stadium_.investment))) + return invalid("stale_investment_selection"); + clear_investment(); stadium_.feedback.clear(); return true; // Initial Abbruch precedes W(6,14). + } + if (request.kind == ui::StadiumRequestKind::select_investment_option) { + if (!stadium_.investment || stadium_.tip || request.object != int(*stadium_.investment) || + request.option < 0 || request.accept_tip || !stadium_.selection_status || + g_.manager_records[record + 0x3c + size_t(*stadium_.investment)] != *stadium_.selection_status) + return invalid("stale_investment_selection"); + const auto current = options(*stadium_.investment); + if (size_t(request.option) >= current.size() || request.price != int32_t(current[size_t(request.option)].base_price)) + return invalid("stale_investment_price"); + stadium_.option_index = request.option; stadium_.option = current[size_t(request.option)]; + return true; // Pure tier choice: neither Source generator advances. + } + if (request.kind == ui::StadiumRequestKind::confirm_investment) { + if (stadium_.tip || !selected_valid() || request.object != int(*stadium_.investment) || + request.option != stadium_.option_index || request.accept_tip || + request.price != int32_t(stadium_.option->base_price)) return invalid("stale_investment_selection"); + stadium_.tip = modern::prepare_stand_block_offer(stadium_.option->base_price, stadium_.option->base_weeks, rand_); + if (stadium_.tip->offered_price > uint32_t(INT32_MAX)) return invalid("invalid_investment_tip_price"); + return true; + } + if (request.kind == ui::StadiumRequestKind::answer_construction_tip) { + if (!stadium_.tip || !selected_valid() || request.object != int(*stadium_.investment) || + request.option != stadium_.option_index || request.price != int32_t(request.accept_tip ? + stadium_.tip->offered_price : stadium_.tip->base_price)) return invalid("stale_construction_tip"); + auto resolved = *stadium_.tip; + modern::resolve_stand_block_offer(resolved, request.accept_tip, rand_); + const bool built = modern::build_stadium_investment_source(g_, active, *stadium_.investment, + stadium_.price_percent, constants, *stadium_.option, resolved, rand_, notice_presenter); + // A genuine PayConstruction/BookMoney2 refusal consumes the answer and + // retains the sponsor share clearing and Source W draws. + // Interactive callers have already shown Source's timed funds + // notice; headless legacy callers retain their text feedback. + clear_investment(); + stadium_.feedback = built || notice_presenter ? std::string{} : message_text(g_, ::bmh::layout::Advertising_FormatError_TextPointer18); + return true; + } + return invalid("unsupported_stadium_request"); + }; + if (!apply()) { restore_stadium_checkpoint(std::move(before)); return false; } + ++revision; ++stadium_.sequence; stadium_.revision = revision; + error.clear(); return true; + } catch (...) { + restore_stadium_checkpoint(std::move(before)); revision = before_revision; throw; + } +} + +bool ModernSession::dispatch_toto(const ui::TotoRequest& request, uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + if (request.kind != ui::TotoRequestKind::submit || request.manager_slot != active || request.manager_slot < 0 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) { + error = "stale_manager_or_revision"; return false; + } + if (g_.memory.u8(::bmh::layout::CareerSession_DispatchToto_RuntimeField) != 11) { error = "toto_coupon_requires_eleven_matches"; return false; } + if (!modern::submit_pools_coupon(g_, request.manager_slot, request.stake, request.tips)) { + error = "invalid_toto_coupon"; return false; + } + ++revision; + return true; +} + +} // namespace bmh::modern::app + +namespace bmh::modern::app { + +PendingOfferHooks ModernSession::pending_hooks_for_dispatch(PendingOfferHooks hooks) const { + // Presenters own answers and notice delivery, never allocator provenance. + hooks.human_buyer_allocator_gate = turn_driver_.transfer_allocator_context; + return hooks; +} + +void ModernSession::install_default_hooks() { + // InstallDefaultHooks pauses at the Original contracts screen when a term expires. + // Never synthesize a two-year renewal here: callers must install the real + // interactive ContractExpiryPresenter or month_change stops without a decision. + g_.contract_screen = {}; + g_.loan_return_screen = {}; + g_.loan_return_offer_screen = {}; +} + +void ModernSession::set_contract_expiry_presenter(ContractExpiryPresenter presenter) { + // Clear any previously installed presenter before replacing it. The only + // fallback is an explicit unsupported expiry, never a synthesized decision. + auto loan_return_hook = std::move(g_.loan_return_screen); + auto loan_offer_hook = std::move(g_.loan_return_offer_screen); + install_default_hooks(); + g_.loan_return_screen = std::move(loan_return_hook); + g_.loan_return_offer_screen = std::move(loan_offer_hook); + contract_expiry_presenter_installed_ = bool(presenter); + if (!presenter) return; + g_.contract_screen = [this, presenter = std::move(presenter)](GameState& base_state, int manager, int row) { + auto& g = static_cast(base_state); + return presenter(g, rand_, manager, row); + }; +} + +void ModernSession::set_loan_return_presenter(LoanReturnPresenter presenter) { + auto contract_hook = std::move(g_.contract_screen); + auto loan_offer_hook = std::move(g_.loan_return_offer_screen); + install_default_hooks(); + g_.contract_screen = std::move(contract_hook); + g_.loan_return_offer_screen = std::move(loan_offer_hook); + loan_return_presenter_installed_ = bool(presenter); + if (!presenter) return; + g_.loan_return_screen = [this, presenter = std::move(presenter)]( + GameState& base_state, int manager, const std::string& question) { + auto& g = static_cast(base_state); + return presenter(g, rand_, manager, question); + }; +} + +void ModernSession::set_loan_return_offer_presenter(LoanReturnOfferPresenter presenter, + HumanBuyerSaleHooks sale_hooks) { + auto contract_hook = std::move(g_.contract_screen); + auto loan_question_hook = std::move(g_.loan_return_screen); + install_default_hooks(); + g_.contract_screen = std::move(contract_hook); + g_.loan_return_screen = std::move(loan_question_hook); + loan_return_offer_presenter_installed_ = bool(presenter); + if (!presenter) return; + g_.loan_return_offer_screen = [this, presenter = std::move(presenter), + sale_hooks = std::move(sale_hooks)]( + GameState& base_state, GameRandom& game, WatcomRandom& rand, int manager, + int source_slot, int list_entry, const HumanBuyerSaleHooks&) mutable { + auto& g = static_cast(base_state); + auto staged_runtime = club_modal_runtime_; + auto services = staged_club_modal_services(g, game, rand, staged_runtime); + auto hooks = sale_hooks; + switch (turn_driver_.transfer_allocator_context) { + case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + const int result = presenter(g, game, rand, services, manager, source_slot, list_entry, hooks); + if (result >= 0) club_modal_runtime_ = std::move(staged_runtime); + return result; + }; +} + +} // namespace bmh::modern::app diff --git a/src/modern/app/modern_session.hpp b/src/modern/app/modern_session.hpp new file mode 100644 index 0000000..edb7a06 --- /dev/null +++ b/src/modern/app/modern_session.hpp @@ -0,0 +1,1090 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// The engine side of the UI's career handoff (src/ui/flow.hpp, ENGINE_BINDING.md). +// +// The original starts a career at program start (game/career.hpp): the data files are +// loaded, every player gets new values and InitializeCareer runs up to the options dialog. +// The UI then shows the options and one dialog per manager; after each confirmed +// manager ConfirmManager sets him up, which may move clubs to other places - the UI gets +// the new club order (SelectionContext) for the next dialog. After the last manager the +// first season is prepared and the desk shown. +// +// ModernSession owns the engine state of that sequence. It never draws numbers for +// rendering; every random draw belongs to one of the steps above. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "formats/m3d.hpp" +#include "formats/textd.hpp" +#include "game/random.hpp" +#include "modern/game/desk_actions.hpp" +#include "modern/game/stadium_blocks.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/turn_driver.hpp" +#include "modern/game/club_info.hpp" +#include "modern/game/club_player_detail.hpp" +#include "game/pending_offer.hpp" +#include "modern/game/poach.hpp" +#include "game/human_buyer_sale.hpp" +#include "modern/game/weekly.hpp" +#include "ui/flow.hpp" +#include "ui/desk_state.hpp" +#include "ui/league_table.hpp" +#include "ui/league_table_range_dialog.hpp" +#include "ui/league_pairings.hpp" +#include "ui/balance_plan.hpp" +#include "ui/top_scorers_state.hpp" +#include "ui/tactics.hpp" +#include "ui/opportunities.hpp" +#include "ui/other_games_state.hpp" + +namespace bmh::modern::app { + +ui::OutgoingTransferEditorState loan_return_offer_editor_projection( + const ModernState&, const TransferOfferEditorState&, uint64_t revision, bool gradient); + +// KB6 commits retain their concrete field even though they also refresh the quote. +TransferOfferEditorState edit_transfer_offer_from_ui(ModernState&, const TransferOfferEditorState&, + const ui::OutgoingTransferRequest&, GameRandom&, WatcomRandom&); + +// The original interactive post-desk path needs its own answer producer. +// Existing headless callers retain their prior unpresented driver contract. +enum class PendingOfferEntryPolicy { legacy_unpresented, normal_interactive }; + +// Source SubmitTransferBidSourceHumanBuyer direct purchases have a separate owner and cleanup contract +// from both special pending offers and automatic weekly auctions. +enum class HumanBuyerMarketEntryPolicy { legacy_unpresented, normal_interactive }; + +enum class LiveSubstitutionStatus { rejected, applied, source_notice }; +struct LiveSubstitutionResult { + LiveSubstitutionStatus status = LiveSubstitutionStatus::rejected; + uint32_t source_text_address = 0; + int manager_slot = -1; + std::string error; +}; + +// Synchronous capability facade shared by live club modals and a staged KB31 +// TeamInfo transaction. It exposes no calendar/save/outer revision operations. +struct ClubModalServices { + bool transactional = true; + std::function state; + std::function enter_club; + std::function change_category; + std::function redraw_player; + std::function national_action; + std::function pending_offers; + std::function runtime_byte; + std::function set_runtime_byte; +}; +using TransferOfferTeamInfoPresenter = std::function; +using TransferOfferPlayerInfoPresenter = std::function; + +// Semantic desk settings for frontends without MEN drawer/layout controls. +struct DeskSettingIdentity { + int manager_slot = -1, runtime_club = -1; + std::optional stable_club_identity; + uint64_t revision = 0; +}; +struct TicketPriceRequest { + DeskSettingIdentity identity; + int price = 0; // Original admission range8..25. +}; +enum class DeskAutomation { Formation, Substitution, Tactics, Marking, Training }; +struct AutomationRequest { + DeskSettingIdentity identity; + DeskAutomation automation = DeskAutomation::Substitution; + bool enabled = false; + // Formation on selects an explicit available saved slot1..8; off has no slot. + // Other automation settings must omit this field. + std::optional formation; +}; + +class ModernSession { + friend class TransferActions; +public: + struct LineupCheckpoint { + ModernState state; + int manager = -1; + int club = -1; + }; + // Loads the data files and runs the program start up to the options dialog. The Watcom + // generator starts at `watcom_seed` (the original: srand() with the clock). + ModernSession(const std::filesystem::path& data, uint32_t watcom_seed); + + // The order of the clubs as the next manager dialog shows them: runtime club id -> + // master database index (ui::SelectionContext::club_order). + ui::SelectionContext selection_context(uint64_t revision) const; + std::vector manager_choices(uint64_t revision) const; + bool begin_manager_join(const ui::DeskRequest&, const ui::SetupOptions&, uint64_t revision, std::string& error); + bool confirm_manager_join(const ui::ManagerChoice&, std::string& error); + ui::SelectionContext manager_join_context() const; + bool manager_join_complete() const; + void cancel_manager_join() { manager_join_.reset(); } + struct ManagerJoinCheckpoint { + ModernState state; + WatcomRandom rand; + GameRandom game; + TurnDriver driver; + std::vector managers; + std::vector desk_callargs; + }; + ManagerJoinCheckpoint manager_join_checkpoint() const { + return {g_, rand_, game_, turn_driver_, managers_, source_desk_callargs_}; + } + void restore_manager_join_checkpoint(ManagerJoinCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); rand_ = checkpoint.rand; game_ = checkpoint.game; + turn_driver_ = std::move(checkpoint.driver); managers_ = std::move(checkpoint.managers); + source_desk_callargs_ = std::move(checkpoint.desk_callargs); + manager_join_.reset(); + } + bool commit_manager_join(ui::CareerInitializationResult&, uint64_t& revision, std::string& error); + + // A confirmed manager (in confirmation order). The options are taken over before the + // first one. Returns false with `error` set if the engine cannot do it. + bool confirm_manager(const ui::SetupOptions& options, const ui::ManagerChoice& choice, std::string& error); + int confirmed() const { return int(managers_.size()); } + + // After the last manager: the first season up to the first desk. + bool finish(ui::CareerInitializationResult& result, std::string& error); + std::optional enter_club_information(int team, std::string& error); + std::optional change_club_information_category(int team, int requested, + std::string& error); + std::optional redraw_club_player_detail( + const ClubPlayerDetailSelection&, std::string& error); + std::optional dispatch_club_player_national_action( + const ClubPlayerDetailSelection&, std::string& error); + // Synchronous manual DispatchClubPlayerPendingOffers batch. Hooks present the staged state; + // unsupported/throwing decisions discard the state and both RNGs together. + std::optional dispatch_club_player_pending_offers( + const ClubPlayerDetailSelection&, uint64_t expected_revision, + const PendingOfferHooks&, uint64_t& revision, std::string& error); + + // Ordinary market actions run on a full Native/RNG copy. Only a supported + // result with valid dependent projections becomes the live state. + std::optional dispatch_transfer_market( + const ui::TransferMarketRequest&, const HumanBuyerSaleHooks&, + uint64_t& revision, std::string& error); + + struct TransferMarketPreviewDispatch { + ui::PreparationState preparation; + ui::TransferMarketPreview quote; + }; + // TransferMarketScreen belongs to pointer input, never to rendering. Stage the optional + // W fallback and validate the owned projection before publishing it. + std::optional preview_transfer_market( + const ui::TransferMarketRequest&, uint64_t& revision, std::string& error); + + struct TransferOfferEditorDispatch { + ui::PreparationState preparation; + ui::OutgoingTransferEditorState editor; + TransferActionResult action; + }; + std::optional open_transfer_offer( + const ui::TransferMarketRequest&, uint64_t& revision, std::string& error); + std::optional dispatch_transfer_offer( + const ui::OutgoingTransferRequest&, const HumanBuyerSaleHooks&, + uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}, + const TransferOfferPlayerInfoPresenter& player_info = {}); + // Poaching (Abwerben, transfer screen button 4): the checks and the special list row of + // src/game/poach.hpp, then the ordinary offer editor on that row (decided at once, see + // dispatch_transfer_offer). Without `editor` the attempt ended with the original's + // messages in `start` (some still count as an attempt and are committed). + struct PoachDispatch { + PoachStart start; + std::optional editor; + }; + std::optional open_poach(int manager_slot, int squad_slot, uint64_t& revision, std::string& error); + // FriendlyMatchScreen(param1=1) owns a separate staged selection, not the normal + // LeagueScreenShown Table family. Return the actual squad selection delivered by + // ClubPlayerDetailFromGame's >25-tick long press, or nullopt when Table is cancelled. + using PoachPlayerSelector = std::function( + ModernSession& selection_session, ClubModalServices&, int manager_slot, + uint64_t& selection_revision, const Image& transfer_backdrop)>; + using PoachUiAccept = std::function; + bool close_poach_table_selection(const ui::LeagueFamilyRequest&, std::string& error); + bool dispatch_poach_ui(const ui::TransferMarketRequest&, const Image&, + const PoachPlayerSelector&, const PoachUiAccept&, uint64_t& revision, std::string& error); + ClubModalServices live_club_modal_services(uint64_t& revision); + struct LeaguePairingsDraft { + ModernState state; + GameRandom game; + WatcomRandom rand; + std::map runtime,original_runtime; + LeaguePairingsOwner owner; + ui::LeaguePairingsIdentity identity; + Bytes original_stream; + uint32_t original_rand_seed=0; + int32_t original_game_seed=0; + uint64_t original_rand_calls=0,original_game_calls=0; + std::optional active_packet; + // Only the active presentation context is borrowed from the driver; + // retain its original descriptors/fixtures/profiles to reject a stale + // redraw or nested return instead of changing packet ownership silently. + std::vector>> original_active_groups; + std::vector original_referee_profiles; + }; + struct LeagueFamilyOwner { + enum class TableDispatchPhase : uint8_t { ready, range_start, range_end, forecast_pending_present }; + ui::StrengthsIdentity identity; + uint8_t child = 0; // Source selector: 1 table, 2 pairings, 3 strengths. + bool friendly_opponent = false; // Direct FriendlyMatchScreen(2,0), without outer LeagueScreenShown close. + Bytes native; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + std::map runtime; + struct TableOwner { + int first_round = 0, end_round = 0; + uint8_t aggregation_flags = 4; + int normal_mode = 0; + TableDispatchPhase phase = TableDispatchPhase::ready; + int pending_start_round = 0; + int previous_start_round = 0, previous_end_round = 0; + uint16_t display_word_override = 0; + uint8_t runtime_font_id = 0; + std::string retained_range_label_source_bytes; + int dialog_x = 140, dialog_y = 80; + ui::LeagueTableState page; + std::optional forecast_page; + std::optional forecast_game_after; + bool forecast_present_pending = false; + bool operator==(const TableOwner& other) const { + const bool same_rng = forecast_game_after.has_value() == other.forecast_game_after.has_value() && + (!forecast_game_after || (forecast_game_after->seed() == other.forecast_game_after->seed() && + forecast_game_after->calls() == other.forecast_game_after->calls())); + return first_round == other.first_round && end_round == other.end_round && + aggregation_flags == other.aggregation_flags && normal_mode == other.normal_mode && + phase == other.phase && pending_start_round == other.pending_start_round && + previous_start_round == other.previous_start_round && previous_end_round == other.previous_end_round && + display_word_override == other.display_word_override && runtime_font_id == other.runtime_font_id && + retained_range_label_source_bytes == other.retained_range_label_source_bytes && + dialog_x == other.dialog_x && dialog_y == other.dialog_y && page == other.page && + forecast_page == other.forecast_page && same_rng && + forecast_present_pending == other.forecast_present_pending; + } + }; + std::optional table; + bool operator==(const LeagueFamilyOwner&) const = default; + }; + using TableDispatchPhase = LeagueFamilyOwner::TableDispatchPhase; + struct LeagueTableDispatch { + ui::LeagueTableState page; + ui::StrengthsIdentity identity; + TableDispatchPhase phase = TableDispatchPhase::ready; + std::optional dialog; + }; + struct LeaguePairingsCheckpoint { + ModernState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional draft; + std::optional family; + uint64_t next_family_id = 1; + }; + struct LeaguePairingsDispatch { + bool closed=false; + ui::LeaguePairingsState page; + ui::PreparationState preparation; + }; + std::optional open_league_pairings(const ui::DeskRequest&,uint64_t revision,std::string& error); + std::optional dispatch_league_pairings(const ui::LeaguePairingsRequest&, + uint64_t& revision,std::string& error,const TransferOfferTeamInfoPresenter& team_info={}); + LeaguePairingsCheckpoint league_pairings_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,league_pairings_draft_,league_family_owner_,next_league_family_id_}; + } + void restore_league_pairings_checkpoint(LeaguePairingsCheckpoint checkpoint) { + g_=std::move(checkpoint.state);game_=checkpoint.game;rand_=checkpoint.rand; + club_modal_runtime_=std::move(checkpoint.runtime);league_pairings_draft_=std::move(checkpoint.draft); + league_family_owner_=std::move(checkpoint.family);next_league_family_id_=checkpoint.next_family_id; + } + const std::optional& league_pairings_owner() const {return league_pairings_draft_;} + struct BalanceDraft { + struct NoticeGate { uint8_t compact_dialog_frame=0,notice_gate_disabled=0,presentation_blocked=0; bool enabled() const { return notice_gate_disabled==0&&(compact_dialog_frame!=0||presentation_blocked==0); } }; + ModernState state; + GameRandom game; + WatcomRandom rand; + std::map runtime, original_runtime; + ui::BalanceState page; + Bytes original_stream; + uint32_t original_rand_seed=0; + int32_t original_game_seed=0; + uint64_t original_rand_calls=0, original_game_calls=0; + bool warning=false; + NoticeGate notice_gate; + }; + struct BalanceCheckpoint { + ModernState state; GameRandom game; WatcomRandom rand; + std::map runtime; + std::optional draft; + uint64_t next_scope=0; + }; + struct BalanceDispatch { bool closed=false, warning=false; ui::BalanceState page; ui::PreparationState preparation; }; + std::optional open_balance_plan(const ui::DeskRequest&, uint64_t revision, + const Image& underlay, std::string& error); + std::optional dispatch_balance_plan(const ui::BalanceRequest&, uint64_t& revision, + std::string& error); + BalanceCheckpoint balance_checkpoint() const { return {g_,game_,rand_,club_modal_runtime_,balance_draft_,next_balance_scope_}; } + void restore_balance_checkpoint(BalanceCheckpoint c) { g_=std::move(c.state);game_=c.game;rand_=c.rand;club_modal_runtime_=std::move(c.runtime);balance_draft_=std::move(c.draft);next_balance_scope_=c.next_scope; } + bool balance_active() const { return bool(balance_draft_)||balance_dispatch_active_; } + std::map club_modal_runtime_checkpoint() const { return club_modal_runtime_; } + void restore_club_modal_runtime(std::map runtime) { club_modal_runtime_=std::move(runtime); } + const std::optional& transfer_offer_owner() const { return transfer_offer_editor_; } + void restore_transfer_offer_owner(std::optional owner, uint64_t revision) { + transfer_offer_editor_ = std::move(owner); transfer_offer_revision_ = revision; + } + + struct StrengthsOwner { + ui::StrengthsState page; + Bytes native; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + std::map runtime; + }; + struct LeagueFamilyCheckpoint { + ModernState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional family; + std::optional strengths; + std::optional pairings; + uint64_t next_strengths_scope=1,next_family_id=1; + }; + struct StrengthsCheckpoint { + ModernState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional owner; + uint64_t next_scope = 1; + std::optional family; + uint64_t next_family_id = 1; + }; + struct StrengthsDispatch { + bool closed = false; + ui::StrengthsState page; + ui::PreparationState preparation; + }; + // Semantic entry has no MEN/open-widget requirement. Every submitted identity + // and both expected saved words are validated again against the live session. + std::optional strengths_open_request(uint64_t revision) const; + std::optional begin_league_family(ui::StrengthsIdentity,uint8_t child, + uint64_t revision,std::string& error); + std::optional begin_friendly_opponent_table(uint64_t revision,std::string& error); + // Resolves the clicked physical row through normal working ranks after KI. + std::optional resolve_friendly_table_opponent(const ui::LeagueFamilyRequest&,uint64_t revision, + std::string& error) const; + std::optional acknowledge_friendly_own_club( + const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + std::optional finish_friendly_opponent_table(const ui::LeagueFamilyRequest&, + uint64_t& revision,std::string& error); + bool advance_league_family(const ui::LeagueFamilyRequest&,ui::StrengthsIdentity,uint8_t target, + uint64_t revision,std::string& error); + std::optional league_family_owner() const { return league_family_owner_; } + LeagueFamilyCheckpoint league_family_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,league_family_owner_,strengths_owner_,league_pairings_draft_, + next_strengths_scope_,next_league_family_id_}; + } + void restore_league_family_checkpoint(LeagueFamilyCheckpoint c) { + g_=std::move(c.state);game_=c.game;rand_=c.rand;club_modal_runtime_=std::move(c.runtime); + league_family_owner_=std::move(c.family);strengths_owner_=std::move(c.strengths); + league_pairings_draft_=std::move(c.pairings);next_strengths_scope_=c.next_strengths_scope; + next_league_family_id_=c.next_family_id; + } + std::optional close_league_family(const ui::LeagueFamilyRequest&, + uint64_t& revision,std::string& error); + bool suspend_strengths_for_family(const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + bool suspend_pairings_for_family(const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + bool select_league_family_page(const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + std::optional current_league_table_dispatch(std::string& error) const; + std::optional dispatch_league_table_control( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error); + std::optional dispatch_league_table_range_reply( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error); + std::optional acknowledge_league_forecast_present( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error); + std::optional dispatch_family_table_team_info( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error, + const TransferOfferTeamInfoPresenter&, + const std::optional* poach_selection = nullptr); + bool refresh_family_after_child(const ui::StrengthsIdentity& prior,uint8_t child, + ui::StrengthsIdentity next,uint64_t revision,std::string& error); + bool prepare_league_family_child(const ui::StrengthsIdentity&,uint8_t child, + uint64_t revision,std::string& error); + std::optional dispatch_strengths(const ui::StrengthsRequest&, + uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info = {}, + bool family_transition = false); + StrengthsCheckpoint strengths_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,strengths_owner_,next_strengths_scope_,league_family_owner_,next_league_family_id_}; + } + void restore_strengths_checkpoint(StrengthsCheckpoint checkpoint) { + g_=std::move(checkpoint.state); game_=checkpoint.game; rand_=checkpoint.rand; + club_modal_runtime_=std::move(checkpoint.runtime); strengths_owner_=std::move(checkpoint.owner); + next_strengths_scope_=checkpoint.next_scope;league_family_owner_=std::move(checkpoint.family); + next_league_family_id_=checkpoint.next_family_id; + } + const std::optional& strengths_owner() const { return strengths_owner_; } + + struct TopScorersOwner { + ui::TopScorersState page; + Bytes native; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + }; + struct TopScorersCheckpoint { + ModernState state; + GameRandom game; + WatcomRandom rand; + std::optional owner; + uint64_t next_scope = 1; + }; + struct TopScorersDispatch { + bool closed = false; + ui::TopScorersState page; + ui::PreparationState preparation; + }; + std::optional open_top_scorers(const ui::DeskRequest&, uint64_t revision, + const Image& underlay, std::string& error); + std::optional dispatch_top_scorers(const ui::TopScorersRequest&, + uint64_t& revision, std::string& error); + TopScorersCheckpoint top_scorers_checkpoint() const { + return {g_,game_,rand_,top_scorers_owner_,next_top_scorers_scope_}; + } + void restore_top_scorers_checkpoint(TopScorersCheckpoint c) { + g_=std::move(c.state);game_=c.game;rand_=c.rand; + top_scorers_owner_=std::move(c.owner);next_top_scorers_scope_=c.next_scope; + } + bool top_scorers_active() const { return bool(top_scorers_owner_) || top_scorers_dispatch_active_; } + const std::optional& top_scorers_owner() const { return top_scorers_owner_; } + + struct OpportunitiesOwner { ui::OpportunitiesState page; Bytes native; GameRandom game; WatcomRandom rand; bool national_source_case=false; }; + struct OpportunitiesCheckpoint { ModernState state; GameRandom game; WatcomRandom rand; std::optional owner; uint64_t next_scope=1; }; + struct OpportunitiesDispatch { bool closed=false; ui::OpportunitiesState page; ui::PreparationState preparation; }; + std::optional open_opportunities(const ui::DeskRequest&,uint64_t,const Image&,std::string&, + bool national_source_case=false,int stable_identity=-1); + std::optional dispatch_opportunities(const ui::OpportunitiesRequest&,uint64_t&,std::string&); + OpportunitiesCheckpoint opportunities_checkpoint() const { return {g_,game_,rand_,opportunities_owner_,next_opportunities_scope_}; } + void restore_opportunities_checkpoint(OpportunitiesCheckpoint c) { g_=std::move(c.state);game_=c.game;rand_=c.rand;opportunities_owner_=std::move(c.owner);next_opportunities_scope_=c.next_scope; } + bool opportunities_active() const { return bool(opportunities_owner_)||opportunities_dispatch_active_; } + bool apply_statistics_preference(const ui::DeskRequest&, int manager_slot, uint8_t expected_flags, + uint8_t target_flags, uint64_t& revision, std::string& error); + + struct OtherGamesSelection { + // Process-global Source selectors: the ordinary desk entry does not clear + // Season_SeasonTransition_RuntimeField/CareerSession_FormatError_RuntimeField8 when the active manager changes. + int competition = 0, linked_page = 0; + }; + struct OtherGamesOwner { + ui::OtherGamesState page; + ui::DeskRequest desk_owner; + int round = -1, participant_offset = 0; + OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail; + Bytes native; + std::map runtime; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + }; + struct OtherGamesCheckpoint { + ModernState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional owner; + OtherGamesSelection selection; + uint64_t next_scope = 1; + }; + struct OtherGamesDispatch { + bool closed = false; + ui::OtherGamesState page; + ui::PreparationState preparation; + }; + std::optional open_other_games( + const ui::DeskRequest&, uint64_t& revision, const Image& underlay, std::string& error); + std::optional dispatch_other_games( + const ui::OtherGamesRequest&, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}); + OtherGamesCheckpoint other_games_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,other_games_owner_,other_games_selection_,next_other_games_scope_}; + } + void restore_other_games_checkpoint(OtherGamesCheckpoint c) { + g_=std::move(c.state);game_=c.game;rand_=c.rand;club_modal_runtime_=std::move(c.runtime); + other_games_owner_=std::move(c.owner);other_games_selection_=c.selection; + next_other_games_scope_=c.next_scope; + } + bool other_games_active() const { return bool(other_games_owner_) || other_games_dispatch_active_; } + const std::optional& other_games_owner() const { return other_games_owner_; } + + // Accept the desk's kickoff request and advance the shared engine turn cursor. + TurnAdvanceResult dispatch_kickoff(const ui::DeskRequest& request, uint64_t& revision, + std::string& error); + + // Fresh coherent preparation views for one controller revision, after a desk action. + ui::PreparationState preparation_projection(uint64_t revision) const; + + // Validates camp request context before any action; advances revision only on change. + bool dispatch_training(const ui::TrainingRequest&, uint64_t& revision, std::string& error); + bool dispatch_training_camp(const ui::TrainingCampRequest&, uint64_t& revision, std::string& error); + bool dispatch_bank(const ui::BankRequest&, uint64_t& revision, std::string& error); + struct BankCheckpoint { + ModernState state; + WatcomRandom rand; + GameRandom game; + std::optional last_tip; + std::optional property_notice; + std::optional credit_notice; + }; + BankCheckpoint bank_checkpoint() const { return {g_, rand_, game_, last_stock_tip_, last_property_notice_, last_credit_notice_}; } + void restore_bank_checkpoint(BankCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); + rand_ = checkpoint.rand; game_ = checkpoint.game; + last_stock_tip_ = checkpoint.last_tip; + last_property_notice_ = std::move(checkpoint.property_notice); + last_credit_notice_ = std::move(checkpoint.credit_notice); + } + bool dispatch_stadium(const ui::StadiumRequest&, uint64_t& revision, std::string& error, + const ConstructionNoticeHook& notice_presenter = {}, + const SeasonTicketCompensationNoticeHook& compensation_presenter = {}); + struct StadiumRuntime { + struct BlockExpansion { + StadiumBlockExpansionQuote quote; + uint32_t total_target_places = 0; + uint8_t desired_features = 0; + int header_text_variant = -1; + std::optional tip; + }; + bool opened = false; + bool data_open = false; + uint8_t data_flags = 0x40; + int manager = -1, club = -1, stable_club = -1, mode = -1; + uint64_t scope = 0, sequence = 0, revision = 0; + int price_percent = 100; + std::optional> periphery_quote; + std::optional investment; + std::optional selection_status; + int option_index = -1, text_variant = -1; + std::optional option; + std::optional tip; + std::optional block_expansion; + std::string feedback; + }; + struct StadiumCheckpoint { + ModernState state; + WatcomRandom rand; + GameRandom game; + StadiumRuntime stadium; + uint64_t next_scope; + }; + StadiumCheckpoint stadium_checkpoint() const { return {g_, rand_, game_, stadium_, next_stadium_scope_}; } + void restore_stadium_checkpoint(StadiumCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); rand_ = checkpoint.rand; game_ = checkpoint.game; + stadium_ = std::move(checkpoint.stadium); next_stadium_scope_ = checkpoint.next_scope; + } + bool stadium_tip_deadline_expired() const; + bool dispatch_toto(const ui::TotoRequest&, uint64_t& revision, std::string& error); + bool dispatch_tactics(const ui::TacticsRequest&, uint64_t& revision, std::string& error); + bool dispatch_lineup(const ui::LineupRequest&, uint64_t& revision, std::string& error); + // Source PitchScreen live-match path: apply one user-picked field/bench + // exchange and re-rate the side while TurnDriver is paused after a minute. + bool dispatch_live_substitution(const ui::LineupRequest&, int minute, int source_mode, + MatchEngine&, uint64_t& revision, std::string& error); + LiveSubstitutionResult dispatch_live_substitution_result(const ui::LineupRequest&, int minute, + int source_mode, MatchEngine&, uint64_t& revision); + bool dispatch_live_tactic(const ui::TacticsRequest&, int minute, int source_mode, + MatchEngine&, uint64_t& revision, std::string& error); + bool dispatch_live_pitch(const ui::PitchRequest&, int minute, int source_mode, + MatchEngine&, uint64_t& revision, std::string& error); + LiveSubstitutionResult dispatch_live_pitch_result(const ui::PitchRequest&, int minute, + int source_mode, MatchEngine&, uint64_t& revision); + // Source EndPhase's configured keyboard slots 0/1 (G/T) suspend the current + // match-minute loop and open LeagueScreenShown or CupGroupOverviewEffects. The caller must only create + // this request from that synchronous observer; group_index is fixed to 0, + // the first Native descriptor selected by CareerSessionRuntimeField5 (not the current DeskPosition tick). + enum class LiveOverviewKind : uint8_t { league_table, league_pairings, league_strengths, cup_other_games }; + struct LiveOverviewRequest { + int key_slot = -1; // Source Main_FileScreen_RuntimeField slot: 0=G/table, 1=T/pairings. + int minute = -1; + int group_index = -1; + int manager_slot = -1; + int runtime_team = -1; + uint64_t revision = 0; + uint64_t sequence = 0; + bool operator==(const LiveOverviewRequest&) const = default; + }; + struct LiveOverviewProjection { + LiveOverviewKind kind = LiveOverviewKind::league_table; + LiveOverviewRequest owner; + ui::StrengthsIdentity family_identity; // G uses the existing full Table-family controls. + std::optional table; + std::optional pairings; + std::optional strengths; + std::optional cup; + }; + using LiveOverviewAction = std::variant; + struct LiveOverviewDispatch { + LiveOverviewKind kind = LiveOverviewKind::league_table; + bool closed = false; + ui::StrengthsIdentity family_identity; + TableDispatchPhase table_phase = TableDispatchPhase::ready; + std::optional table_dialog; + std::optional table; + std::optional pairings; + std::optional strengths; + std::optional cup; + std::optional preparation; + }; + std::optional open_live_overview(const LiveOverviewRequest&, + MatchEngine&, uint64_t& revision, const Image& underlay, std::string& error); + std::optional dispatch_live_overview(const LiveOverviewAction&, + MatchEngine&, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}); + bool live_overview_active() const { return bool(live_overview_owner_); } + // Only available inside the installed phase presenter. Uses the same Source + // viewer/action owners as keyboard overviews, before the engine's single ACK. + std::optional open_phase_results(uint64_t& revision, + const Image& underlay, std::string& error); + std::optional dispatch_phase_results(const LiveOverviewAction&, + uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}); + // Source EndPhase key slot 2 suspends the live-minute observer in SettingsSourceRefusal. + // The request is accepted only during that synchronous observer; Session allocates + // the returned sequence, so callers must retain the returned owner verbatim. + struct LiveSettingsRequest { + int minute = -1; + int manager_slot = -1; + int runtime_team = -1; + uint64_t revision = 0; + uint64_t sequence = 0; + bool operator==(const LiveSettingsRequest&) const = default; + }; + struct LiveSettingsWrite { + uint64_t owner_sequence = 0; + ui::SettingsWriteRequest write; + }; + struct LiveSettingsFile { uint64_t owner_sequence = 0; ui::SaveLoadRequest request; }; + struct LiveSettingsCloseRequest { LiveSettingsRequest owner; }; + using LiveSettingsAction = std::variant; + struct LiveSettingsProjection { LiveSettingsRequest owner; ui::SettingsState state; }; + struct LiveSettingsDispatch { LiveSettingsRequest owner; bool closed = false; ui::SettingsState state; }; + std::optional open_live_settings(const LiveSettingsRequest&, + MatchEngine&, uint64_t& revision, std::string& error); + std::optional dispatch_live_settings(const LiveSettingsAction&, + MatchEngine&, uint64_t& revision, std::string& error); + bool live_settings_active() const { return bool(live_settings_owner_); } + struct DeskSettingsOwner { + uint64_t sequence = 0, revision = 0; + int manager_slot = -1, source_item_id = -1; + bool operator==(const DeskSettingsOwner&) const = default; + }; + struct DeskSettingsWrite { uint64_t owner_sequence = 0; ui::SettingsWriteRequest write; }; + struct DeskSettingsFile { uint64_t owner_sequence = 0; ui::SaveLoadRequest request; }; + struct DeskSettingsClose { DeskSettingsOwner owner; }; + using DeskSettingsAction = std::variant; + struct DeskSettingsProjection { DeskSettingsOwner owner; ui::SettingsState state; }; + struct DeskSettingsDispatch { DeskSettingsOwner owner; bool closed = false; ui::SettingsState state; }; + struct DeskSettingsCheckpoint { + ModernState state; + std::map runtime; + std::optional owner; + uint8_t initial_h8 = 0; + uint64_t next_scope = 1, revision = 0; + }; + std::optional open_desk_settings(const ui::DeskRequest&, + uint64_t& revision, std::string& error); + std::optional dispatch_desk_settings(const DeskSettingsAction&, + uint64_t& revision, std::string& error); + DeskSettingsCheckpoint desk_settings_checkpoint(uint64_t revision) const; + void restore_desk_settings_checkpoint(DeskSettingsCheckpoint, uint64_t& revision); + bool desk_settings_active() const { return bool(desk_settings_owner_); } + bool begin_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine&, uint64_t& revision, std::string& error); + bool begin_live_event_intervention(const LiveMatchEvent&, MatchEngine&, + uint64_t& revision, std::string& error); + bool finish_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine&, uint64_t& revision, std::string& error); + bool finish_live_event_intervention(const LiveMatchEvent&, MatchEngine&, + uint64_t& revision, std::string& error); + void abort_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine&, uint64_t& revision); + // Semantic Pitch actions bind the live manager/club, prepared entry and revision. + // The four Source helpers are deterministic; rejected actions do not commit. + bool dispatch_pitch(const ui::PitchRequest&, uint64_t& revision, std::string& error); + bool dispatch_pitch_swap(const ui::PitchRequest&, uint64_t& revision, std::string& error); + // The Source desk callargs are the only authority for an ordinary upcoming + // opponent. The revision binds the returned display projection; write requests + // are independently checked against the controller's current revision. + std::optional prepared_lineup_opponent(int manager_slot, int runtime_club, + uint64_t revision) const; + LineupCheckpoint lineup_checkpoint() const { return {g_, lineup_entry_manager_, lineup_entry_club_}; } + void restore_lineup_checkpoint(LineupCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); + lineup_entry_manager_ = checkpoint.manager; + lineup_entry_club_ = checkpoint.club; + } + bool dispatch_mailbox(const ui::MailboxActionRequest&, uint64_t& revision, std::string& error); + std::optional pending_mailbox_notification(uint64_t revision) const; + bool acknowledge_mailbox_close(const ui::MailboxCloseRequest&, uint64_t revision, + std::string& error); + uint32_t mailbox_notification_checkpoint() const { + return g_.memory.has(::bmh::layout::MailboxRecipientMask) ? g_.memory.u32(::bmh::layout::MailboxRecipientMask) : 0; + } + void restore_mailbox_notification_checkpoint(uint32_t mask) { + if (g_.memory.has(::bmh::layout::MailboxRecipientMask)) g_.memory.set32(::bmh::layout::MailboxRecipientMask, mask); + } + bool dispatch_settings(const ui::SettingsWriteRequest&, uint64_t& revision, std::string& error); + bool dispatch_contract(const ui::ContractRequest&, uint64_t& revision, + ui::ContractActionResult&, std::string& error); + bool dispatch_advertising(const ui::AdvertisingRequest&, uint64_t& revision, std::string& error, + AdvertisingSpendingResult* spending_result = nullptr); + // CheckAdvertisingRenewal: renewing a contract whose months ran out (game/desk_actions.hpp). The + // check draws the sponsor's random number and returns the question or settles the + // refusal; the answer applies the manager's choice. Both bind the active manager and + // the revision (and advance it). + std::optional check_advertising_renewal(int manager_slot, int display_slot, uint64_t& revision, + std::string& error); + bool answer_advertising_renewal(int manager_slot, int contract_slot, bool renew, uint64_t& revision, std::string& error); + enum class AdvertisingRenewalPresentation { abort, renew, decline, acknowledged }; + using AdvertisingRenewalPresenter = std::function; + std::optional dispatch_advertising_renewal( + const ui::AdvertisingRequest&, uint64_t& revision, std::string& error, + const AdvertisingRenewalPresenter& presenter); + struct AdvertisingActionResult { + AdvertisingSpendingResult spending; + std::optional renewal; + }; + using AdvertisingAcknowledge = std::function; + // Frontends supply an observed intent, never a live-state refresh of an old + // offer. Acknowledgement is inside the transaction (SDL projection can fail). + bool apply_advertising(const ui::AdvertisingRequest&, uint64_t& revision, + std::string& error, const AdvertisingAcknowledge& acknowledge = {}, + const AdvertisingRenewalPresenter& presenter = {}); + bool accept_advertising_selection(const ui::AdvertisingState& observed, int display_slot, + int raw_offer, uint64_t request_id, uint64_t& revision, std::string& error); + bool set_advertising_budget(const ui::AdvertisingState& observed, int target_slot, + uint32_t amount, uint64_t request_id, uint64_t& revision, std::string& error, + AdvertisingSpendingResult& result); + struct AdvertisingCheckpoint { + ModernState state; + uint64_t last_request_id = 0; + WatcomRandom rand; + GameRandom game; + }; + AdvertisingCheckpoint advertising_checkpoint() const { return {g_, last_advertising_request_id_, rand_, game_}; } + void restore_advertising_checkpoint(AdvertisingCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); + last_advertising_request_id_ = checkpoint.last_request_id; + rand_ = checkpoint.rand; + game_ = checkpoint.game; + } + void clear_contract_quote() { contract_quote_.reset(); } + bool dispatch_desk_widget(const ui::DeskRequest&, uint64_t& revision, std::string& error); + bool dispatch_desktop_layout(const ui::DeskRequest&, uint64_t& revision, std::string& error); + bool dispatch_ticket_price(const TicketPriceRequest&, uint64_t& revision, std::string& error); + bool dispatch_automation(const AutomationRequest&, uint64_t& revision, std::string& error); + ui::DeskState desktop_projection(uint64_t revision) const; + bool save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error); + void configure_autosave_directory(const std::filesystem::path& directory); + std::string take_autosave_error(); + // Source DispatchMenuLayout: read/write the active manager's raw 0x360-byte .MEN layout. + // This operation never serializes a ModernSession or consumes either RNG. + bool dispatch_menu_layout(const ui::SaveLoadRequest&, uint64_t& revision, std::string& error); + + // Load an existing V2.24 save without applying new-career options or startup RNG. + ModernSession(const std::filesystem::path &data, uint32_t watcom_seed, + const std::filesystem::path &save_path, bool importing_legacy = false); + + const ModernState& state() const { return g_; } + ModernState& state() { return g_; } + const TurnResultSnapshot& last_turn_results() const { return turn_driver_.last_results; } + // Owned presentation for the event completed by the last accepted kickoff. + // Empty on a manager handoff or a calendar event without fixtures. + const std::optional& completed_matchday_results() const { return completed_results_; } + // The manager's intervention during a matchday (see TurnDriver::live_minute). + void set_live_minute(decltype(TurnDriver::live_minute) hook) { turn_driver_.live_minute = std::move(hook); } + void set_original_sound(decltype(TurnDriver::original_sound) hook) { turn_driver_.original_sound = std::move(hook); } + void set_live_event(decltype(TurnDriver::live_event) hook) { turn_driver_.live_event = std::move(hook); } + void set_live_reality(decltype(TurnDriver::live_reality) hook) { turn_driver_.live_reality = std::move(hook); } + void set_phase_results(decltype(TurnDriver::phase_results) hook); + void set_live_ball(decltype(TurnDriver::live_ball) hook) { turn_driver_.live_ball = std::move(hook); } + void set_live_chance(decltype(TurnDriver::live_chance) hook) { turn_driver_.live_chance = std::move(hook); } + void set_live_shot(decltype(TurnDriver::live_shot) hook) { turn_driver_.live_shot = std::move(hook); } + void set_live_set_piece(decltype(TurnDriver::live_set_piece) hook) { turn_driver_.live_set_piece = std::move(hook); } + void set_live_booking(decltype(TurnDriver::live_booking) hook) { turn_driver_.live_booking = std::move(hook); } + void set_live_shootout(decltype(TurnDriver::live_shootout) hook) { turn_driver_.live_shootout = std::move(hook); } + // Temporary synchronous presenter for InstallDefaultHooks, invoked by the monthly + // board walk. The supplied random stream is the session's live Watcom stream. + // Frontends install this only while an interactive kickoff is running. + using ContractExpiryPresenter = std::function; + void set_contract_expiry_presenter(ContractExpiryPresenter presenter); + using LoanReturnPresenter = std::function; + void set_loan_return_presenter(LoanReturnPresenter presenter); + using LoanReturnOfferPresenter = std::function; + void set_loan_return_offer_presenter(LoanReturnOfferPresenter presenter, + HumanBuyerSaleHooks sale_hooks = {}); + SportschauSourceOptions sportschau_source_options() const; + void set_sportschau_presentation_hooks(SportschauPresentationHooks hooks) { + turn_driver_.sportschau = std::move(hooks); + } + const SportschauPresentationHooks& sportschau_presentation_hooks() const { + return turn_driver_.sportschau; + } + void set_season_pause(decltype(TurnDriver::season_pause) hook) { turn_driver_.season_pause = std::move(hook); } + void set_season_promotion(SeasonPromotionHook hook) { turn_driver_.season_promotion = std::move(hook); } + void set_season_cup_draw(SeasonCupDrawHook hook) { turn_driver_.season_cup_draw = std::move(hook); } + void set_season_tax(SeasonTaxHooks hooks) { turn_driver_.season_tax = std::move(hooks); } + void set_season_highscore(decltype(TurnDriver::season_highscore) hook) { turn_driver_.season_highscore = std::move(hook); } + // Borrowed only during the synchronous post-desk transaction. Its modal + // presenters receive the staged state rather than the session's live state. + void set_pending_offer_hooks(PendingOfferHooks hooks) { pending_offer_hooks_ = std::move(hooks); } + const PendingOfferHooks& pending_offer_hooks() const { return pending_offer_hooks_; } + void set_pending_offer_entry_policy(PendingOfferEntryPolicy policy) { pending_offer_entry_policy_ = policy; } + PendingOfferEntryPolicy pending_offer_entry_policy() const { return pending_offer_entry_policy_; } + // Synchronous original offer chooser. Installed only while the app advances; + // the modal presenter cannot dispatch another desk action or save a partial turn. + void set_transfer_offer_selector(std::function hook) { + g_.transfer_offer_selector = std::move(hook); + } + void set_transfer_decision_observer(std::function hook) { + g_.transfer_decision_observer = std::move(hook); + } + GameRandom& game() { return game_; } + WatcomRandom& rand() { return rand_; } + uint64_t session_id() const { return session_id_; } + bool career_complete() const { return turn_driver_.stage == TurnDriver::Stage::CareerComplete; } + + // Portable host driver capabilities replace SOUND.CFG runtime latches; they + // are never inferred from a saved switch or written into an FBM on entry. + void configure_sound_capabilities(bool music, bool effects) { + sound_capabilities_ = ui::SettingsSoundCapabilities{music, effects}; + } + ui::SettingsState settings_projection(int manager, uint64_t revision) const { + return ui::settings_from_game(state(), manager, revision, exe_, sound_capabilities_); + } +private: + std::optional sound_capabilities_; + std::optional autosave_directory_; + std::string autosave_error_; + void write_desk_autosave(const ModernState&, WatcomRandom&); + bool native_autosave_pending_ = false; + void flush_native_autosave(); + cli::Json native_session_context() const; + void restore_native_session_context(const cli::Json &); + bool live_source_identity(const ui::StrengthsIdentity&) const; + bool validate_desk_setting_owner(const DeskSettingIdentity&, uint64_t revision, std::string& error, + bool require_desk_phase = true) const; + bool apply_desk_setting(int manager, bool price, int index, int value, std::string& error); + ui::PreparationState preparation_projection(const ModernState&, uint64_t revision) const; + ui::DeskState desktop_projection(const ModernState&, uint64_t revision) const; + bool pending_offer_dispatch_active_ = false; + bool market_dispatch_active_ = false; + bool league_pairings_dispatch_active_=false; + bool league_family_teaminfo_active_=false; + bool poach_table_selection_=false; // Only the isolated50775(param1=1) selection Session. + bool strengths_dispatch_active_=false; + bool top_scorers_dispatch_active_=false; + bool opportunities_dispatch_active_=false; + bool other_games_dispatch_active_=false; + uint64_t next_other_games_scope_=1; + std::optional other_games_owner_; + OtherGamesSelection other_games_selection_; + bool balance_dispatch_active_=false; + uint64_t next_balance_scope_=1; + std::optional balance_draft_; + uint64_t next_strengths_scope_=1; + std::optional strengths_owner_; + std::optional league_family_owner_; + uint64_t next_league_family_id_=1; + uint64_t next_top_scorers_scope_=1; + std::optional top_scorers_owner_; + uint64_t next_opportunities_scope_=1; + std::optional opportunities_owner_; + uint64_t league_pairings_scope_=0; + std::optional league_pairings_draft_; + std::optional validate_normal_pairings_group( + const ModernState&,LeaguePairingsOwner&,const std::map&) const; + std::optional transfer_offer_editor_; + std::optional poach_; // the open poaching attempt (its editor is transfer_offer_editor_) + uint64_t transfer_offer_revision_ = 0; + bool calendar_advance_active_ = false; + PendingOfferHooks pending_offer_hooks_; + PendingOfferEntryPolicy pending_offer_entry_policy_ = PendingOfferEntryPolicy::legacy_unpresented; + std::map club_modal_runtime_; + void initialize_club_modal_runtime(); + ClubModalServices staged_club_modal_services(ModernState&,GameRandom&,WatcomRandom&, + std::map&); + PendingOfferHooks pending_hooks_for_dispatch(PendingOfferHooks) const; + void capture_source_desk_callargs(); + uint64_t last_advertising_request_id_ = 0; + bool advertising_renewal_dispatch_active_ = false; + // Engine hooks for screens the app does not have yet. The contracts screen + // (InstallDefaultHooks, desk menu 27): until it exists, the assistant renews an ended + // contract for two years at the market salary (see the definition). + void install_default_hooks(); + void apply_options(const ui::SetupOptions& options); + int runtime_club(int master) const; + int runtime_club(const ModernState&, int master) const; + ui::SelectionContext selection_context_for(const ModernState&, uint64_t revision) const; + struct ManagerJoinDraft { + ModernState state; + WatcomRandom rand; + GameRandom game; + ui::SetupOptions options; + ui::DeskRequest origin; + std::vector choices; + Bytes original_stream; + uint32_t original_rand_seed = 0; + int32_t original_game_seed = 0; + uint64_t original_rand_calls = 0, original_game_calls = 0, context_revision = 0; + }; + std::optional manager_join_; + + std::filesystem::path data_directory_; + LeImage exe_; + // Source MatchEventsDisabled belongs to the loaded program image, not the Native FBM. + // Both session constructors explicitly initialize this owned runtime input. + Database db_; + TextDb texts_; + ModernState g_; + GameRandom game_{0}; + WatcomRandom rand_; + TurnDriver turn_driver_; + // DayCompetitions2 callargs are event-local. A join retains the old slots and + // gets Source's default arrays for its new slot until the next event. + std::vector source_desk_callargs_; + std::string saved_turn_error_; + std::optional completed_results_; + int lineup_entry_manager_ = -1, lineup_entry_club_ = -1; + struct LiveInterventionCheckpoint { + ModernState state; + std::vector groups; + GameRandom game{0}; + WatcomRandom rand; + int minute = 0, source_mode = 0, manager = -1, team = -1; + bool source_event = false; + LiveMatchEvent event; + uint64_t initial_revision = 0, current_revision = 0; + }; + std::optional live_intervention_; + struct LiveOverviewOwner { + bool phase_result = false; + LiveOverviewRequest request; + LiveOverviewKind kind = LiveOverviewKind::league_table; + ui::StrengthsIdentity family_identity; + int source_competition = -1; + Bytes original_native; + uint32_t original_rand_seed = 0; + int32_t original_game_seed = 0; + uint64_t original_rand_calls = 0, original_game_calls = 0; + std::vector>> active_groups; + std::vector referees; + }; + std::optional live_overview_owner_; + const PhaseResultRequest* phase_result_request_ = nullptr; // borrowed synchronous boundary only + std::optional open_running_overview(const LiveOverviewRequest&, + MatchEngine&, uint64_t& revision, const Image& underlay, std::string& error, + bool phase_result); + uint64_t next_live_overview_scope_ = 1; + struct LiveSettingsOwner { + LiveSettingsRequest request; + Bytes native; + std::vector expected_buttons; + bool expected_live_desk_disabled = false, expected_live_scene_visible = false; + std::map expected_runtime; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + std::vector>> active_groups; + std::vector referees; + }; + std::optional live_settings_owner_; + uint64_t next_live_settings_scope_ = 1; + bool live_settings_dispatch_active_ = false; + struct DeskSettingsOwnerState { + DeskSettingsOwner owner; + uint8_t initial_h8 = 0; // ApplySettingsFile captures CareerSession_DispatchStrengths_ExecutableField before SettingsSourceRefusal. + Bytes native; + std::map expected_runtime; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + }; + std::optional desk_settings_owner_; + uint64_t next_desk_settings_scope_ = 1; + bool desk_settings_dispatch_active_ = false; + bool apply_settings_file(const ui::SaveLoadRequest&, int manager_slot, int origin_item_id, + ModernState& staged, bool& loaded, std::string& error) const; + uint64_t session_id_ = 0; + std::vector managers_; + std::optional last_stock_tip_; + std::optional last_property_notice_; + std::optional last_credit_notice_; + StadiumRuntime stadium_; + uint64_t next_stadium_scope_ = 1; + struct ContractQuoteRecord { + uint64_t quote_id = 0, request_id = 0, revision = 0; + int manager_slot = -1, runtime_club = -1, row = -1, player_id = -1; + std::array demands{}; + }; + // Snapshot every mutable Session owner around the synchronous modal. The callback + // may hold a reference to this session; a changed fingerprint rejects the answer, + // and the full copy is restored before the staged Core result can be committed. + struct AdvertisingSessionCheckpoint { + ModernState state; GameRandom game; WatcomRandom rand; + TurnDriver driver; std::vector desk_callargs; + std::string saved_turn_error; std::optional completed_results; + int lineup_manager=-1, lineup_club=-1; std::vector managers; + std::optional stock_tip; + std::optional property_notice; + std::optional credit_notice; + StadiumRuntime stadium; uint64_t next_stadium_scope=1; + std::optional contract_quote; uint64_t next_contract_quote_id=1; + uint64_t last_contract_request_id=0; bool options_applied=false; + bool pending_offer_active=false, market_active=false, pairings_active=false, + family_teaminfo_active=false, strengths_active=false, top_scorers_active=false, + other_games_active=false, balance_active=false, calendar_active=false; + uint64_t next_other_games_scope=1; std::optional other_games_owner; + OtherGamesSelection other_games_selection; + uint64_t next_balance_scope=1; std::optional balance; + uint64_t next_strengths_scope=1; std::optional strengths; + std::optional family; uint64_t next_family_id=1; + uint64_t next_top_scorers_scope=1; std::optional top_scorers; + uint64_t pairings_scope=0; std::optional pairings; + std::optional transfer_editor; std::optional poach; + uint64_t transfer_offer_revision=0; PendingOfferHooks pending_hooks; + PendingOfferEntryPolicy pending_policy=PendingOfferEntryPolicy::legacy_unpresented; + std::map runtime; uint64_t last_request_id=0; + std::optional manager_join; + uint64_t revision=0, session_id=0; + }; + AdvertisingSessionCheckpoint advertising_session_checkpoint(uint64_t revision) const; + void restore_advertising_session_checkpoint(AdvertisingSessionCheckpoint); + bool advertising_session_unchanged(const AdvertisingSessionCheckpoint&, uint64_t revision) const; + std::optional contract_quote_; + uint64_t next_contract_quote_id_ = 1; + uint64_t last_contract_request_id_ = 0; + bool contract_expiry_presenter_installed_ = false; + bool loan_return_presenter_installed_ = false; + bool loan_return_offer_presenter_installed_ = false; + bool options_applied_ = false; +}; + +} // namespace bmh::modern::app diff --git a/src/modern/game/balance_plan.cpp b/src/modern/game/balance_plan.cpp new file mode 100644 index 0000000..b206492 --- /dev/null +++ b/src/modern/game/balance_plan.cpp @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/environment.hpp" +#include "modern/game/balance_plan.hpp" + +#include +#include + +#include "modern/game/prediction.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "modern/game/week.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecordSize = 0xb0c; +constexpr uint32_t kPlanTicketPrice = ::bmh::layout::PlanTicketPrice; // one byte per manager +// BalancePlanRuntimeField: months left in the business year by calendar month (July: 12, June: 1) +constexpr int8_t kMonthsLeft[13] = {0, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7}; +// BalancePlanRuntimeField2: which rows can be changed; BalancePlanRuntimeField3: the class of the maximum +// (BalancePlanRuntimeField4: 30 million, 25, 100000, 2 million) +constexpr uint8_t kEditable[0x16] = {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1}; +constexpr uint8_t kMaximumClass[0x16] = {0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 3, 3, 0, 3, 3, 0, 0, 0, 1, 2, 1}; +constexpr int32_t kMaximum[4] = {30000000, 25, 100000, 2000000}; +// BalancePlanRuntimeField5: monthly running costs of the stadium facilities (BMHExeXa) +constexpr uint16_t kFacilityCost[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600, + 2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000}; +// BalancePlanRuntimeField6: monthly income of the first six facilities (FacilityIncome) +constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000}; +// BalancePlanRuntimeField7: catering income per visitor of the facilities 0-13 (BookMoney) +constexpr uint8_t kPerVisitor[14] = {0, 10, 10, 3, 5, 15, 3, 3, 3, 3, 2, 2, 2, 2}; +// Rec32: price units of the six funds (BMH.exe+MonthRuntimeField10) +constexpr int32_t kShareUnits[6] = {15, 18, 21, 24, 27, 30}; + +int32_t rec32(const ModernState& g, int m, size_t o) { + const size_t at = size_t(m) * kRecordSize + o; + const auto& r = g.manager_records; + return int32_t(uint32_t(r.at(at)) | uint32_t(r.at(at + 1)) << 8 | uint32_t(r.at(at + 2)) << 16 | uint32_t(r.at(at + 3)) << 24); +} +void set_rec32(ModernState& g, int m, size_t o, int32_t v) { + for (int i = 0; i < 4; i++) g.manager_records.at(size_t(m) * kRecordSize + o + size_t(i)) = uint8_t(uint32_t(v) >> (8 * i)); +} +uint8_t rec8(const ModernState& g, int m, size_t o) { return g.manager_records.at(size_t(m) * kRecordSize + o); } +int32_t mem32(const ModernState& g, uint32_t a) { return g.memory.has(a + 3) ? int32_t(g.memory.u32(a)) : 0; } +int32_t wrap(int64_t v) { return int32_t(uint32_t(uint64_t(v))); } + +// Add32: the level of a facility (facility 0: its size step) +uint32_t facility_level(const ModernState& g, int m, int k) { + const uint8_t v = rec8(g, m, size_t(k)); + return k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xff : 1; +} + +// DailyInterest2(0): the interest of one day without booking it - negative is income +// (balance 1 %, fixed deposit 2 % a year), positive an expense (overdraft 12 %, beyond the +// credit line 18 %). The divisor is -36500. +int32_t daily_interest_preview(const ModernState& g, int m) { + constexpr int32_t kAnnual = -0x8e94; + const int32_t balance = rec32(g, m, 0x314), deposit = rec32(g, m, 0x318), credit = rec32(g, m, 0x31c); + int32_t result = 0; + if (balance < 0) { + const int32_t with_credit = wrap(int64_t(balance) + credit); + if (with_credit < 0) result = wrap(int64_t(with_credit) * 0x12) / kAnnual; + int32_t below = wrap(-int64_t(credit)); + if (below < balance) below = balance; + result = wrap(int64_t(result) + wrap(int64_t(below) * 0xc) / kAnnual); + } else { + result = balance / kAnnual; + } + return wrap(int64_t(result) + wrap(int64_t(deposit / 10000) * 20000) / kAnnual); +} + +// SharesAndLoans(manager, flags, months): flags 1 the dividends of the manager's funds and +// the loans he gave to other managers (income), 2 the loans he took (expense, negative); +// flag 4 multiplies by the months (loans: at most their remaining months). +int32_t shares_and_loans(const ModernState& g, int m, int flags, int months) { + int32_t sum = 0; + if (flags & 1) { + for (int k = 0; k < 6; k++) { + const uint32_t unit = g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c) * uint32_t(kShareUnits[k]) / 10000; + sum = wrap(int64_t(sum) + int64_t(unit * g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c))); + } + if (flags & 4) sum = wrap(int64_t(sum) * months); + } + const int managers = g.memory.u8(::bmh::layout::ManagerCount); + for (int c = 0; c <= managers; c++) { + uint32_t row = uint32_t(c) * 0x18 + uint32_t(m) * 0x78; + int32_t amount = mem32(g, ::bmh::layout::Loans + row + 8); + if (amount != 0 && (flags & 2)) { + if (!(flags & 4)) { + sum = wrap(int64_t(sum) - amount); + } else { + int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10)); + sum = wrap(int64_t(sum) - int64_t(std::min(left, months)) * amount); + } + } + if (c == 0) continue; + row = uint32_t(m + 1) * 0x18 + uint32_t(c - 1) * 0x78; + amount = mem32(g, ::bmh::layout::Loans + row + 8); + if (amount != 0 && (flags & 1)) { + if (!(flags & 4)) { + sum = wrap(int64_t(sum) + amount); + } else { + int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10)); + sum = wrap(int64_t(sum) + int64_t(std::min(left, months)) * amount); + } + } + } + return sum; +} + +// MonthlyPay(manager, 0xb): a month of the squad's pay - bonus base (+0x4e), salary +// (+0x50) and the bonus each player can expect (ContractOffer with the fitness correction) +// for the predicted final rank (Void5 mode 4). Changes scratch tables: `g` is a copy. +int32_t monthly_pay(ModernState& g, int m, uint8_t flags = 0xb) { + const int team = g.manager_teams.at(size_t(m)); + std::array buf{}; + const int predicted = modern::table_prediction(g, team, 4, buf); + const int rank = predicted == 0 ? 0xb : predicted + 1; + const SquadRange range = squad_range(team); + int32_t sum = 0; + for (int s = 0; s < 0x18; s++) { + const size_t slot = size_t(m) * 0x840 + size_t(s) * 0x58; + if (g.tactics.at(slot + 0x3d) == 0xff) continue; + const int32_t bonus = int32_t((g.tactics.at(slot + 0x4e) | g.tactics.at(slot + 0x4f) << 8) & 0x7fff); + const int32_t salary = int32_t(uint32_t(g.tactics.at(slot + 0x50)) | uint32_t(g.tactics.at(slot + 0x51)) << 8 | + uint32_t(g.tactics.at(slot + 0x52)) << 16 | uint32_t(g.tactics.at(slot + 0x53)) << 24); + // a board row whose squad slot is empty (0xfff) makes the original read a player + // beyond the table; the port counts no expected bonus for it + const size_t player = g.squad_slots.at(range.first + size_t(s)) & 0xfff; + const int32_t expected = (flags & 1) && player < g.players.size() ? int32_t(modern::expected_bonus(g, m, rank, s, int(player), true)) : 0; + sum = wrap(int64_t(sum) + ((flags & 2) ? salary : 0) + + ((flags & 1) ? expected : 0) + ((flags & 8) ? bonus : 0)); + } + return sum; +} + +// BMHExeXa: the facilities' monthly running costs +int32_t facility_costs(const ModernState& g, int m) { + int32_t sum = 0; + for (int i = 0; i < 0xe; i++) sum += kFacilityCost[i]; + for (int i = 0xe; i < 0x16; i++) sum += (rec8(g, m, 0x2e + size_t(i)) & 7) * kFacilityCost[i]; + return sum; +} + +// FacilityIncome: the facilities' monthly income +int32_t facility_income(const ModernState& g, int m) { + int32_t sum = 0; + for (int k = 0; k < 6; k++) + if (rec8(g, m, size_t(k)) != 0) sum += int32_t(facility_level(g, m, k)) * kFacilityIncome[k]; + return sum; +} + +// BookMoney(manager, gate, 1): kiosks and restaurants of one home game, without the +// random factor +uint32_t catering_per_game(const ModernState& g, int m, int32_t gate) { + uint32_t sum = 0; + for (int k = 0; k < 14; k++) + if (rec8(g, m, size_t(k)) != 0) sum += kPerVisitor[k] * uint32_t(gate) * facility_level(g, m, k) / 100; + return sum; +} + +// The redraw of BalanceFromGame2 (with its continuation Redraw and the patch at +// Redraw2): recomputes the items if `refresh` asks for it, then the spectator income +// and the totals. +void redraw(const ModernState& source, BalancePlanDraft& d) { + const int m = d.manager; + const int view = int(d.view); + auto& r = d.rows; + r[3] = view < 2 ? rec32(source, m, 0x868) : 0; + int32_t home = r[kBalanceLeagueHomeGames] + r[kBalanceOtherHomeGames]; // local_48 + if (view == 0) home = 0; + if (view < 2) { + const int month = modern::month_code(source.date); + d.months_left = month >= 1 && month <= 12 ? kMonthsLeft[month] : 0; + d.days_left = 0x16d - source.season_day(); + const bool first_of_month = source.date == 0 || modern::month_code(source.date - 1) != month; + if (source.season_day() != 0 && month == 7 && first_of_month) d.months_left = d.days_left = 0; + home -= int8_t(rec8(source, m, 0x28c)) + int8_t(rec8(source, m, 0x28d)) + int8_t(rec8(source, m, 0x28e)); + if (home < 0) home = 0; + } else { + d.months_left = 12; + d.days_left = 0x16d; + } + const int months = int8_t(d.months_left); + if (d.refresh != 0) { + if (view < 2) { + for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = rec32(source, m, 0x85c + size_t(i) * 4); + r[7] = wrap(int64_t(rec32(source, m, 0x33c)) + rec32(source, m, 0x334) + rec32(source, m, 0x338)); + } else { + std::fill(r.begin(), r.begin() + kBalanceItems, 0); + } + if (view != 0 && months != 0) + for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = wrap(int64_t(r[size_t(i)]) + d.adjustments[size_t(i)] * 12 / months); + if (d.refresh != 2) r[kBalanceAverageGate] = r[kBalanceGateSoFar]; + if (view != 0) { + ModernState g = source; // scratch copy, see the header + const int32_t interest = wrap(int64_t(int16_t(d.days_left)) * daily_interest_preview(g, m)); + if (interest < 1) r[5] = wrap(int64_t(r[5]) - interest); + else r[0x10] = wrap(int64_t(r[0x10]) + interest); + r[5] = wrap(int64_t(r[5]) + shares_and_loans(g, m, 5, months)); + r[0x10] = wrap(int64_t(r[0x10]) - shares_and_loans(g, m, 6, months)); + // advertising: shirt (+0xadc) and TV (+0xae8) contracts, the 14 boards (+0xa34); + // free boards are expected to bring 80 % of the average board + r[0] = wrap(int64_t(r[0]) + int64_t(rec32(g, m, 0xadc)) * months); + r[2] = wrap(int64_t(r[2]) + int64_t(months) * rec32(g, m, 0xae8)); + int boards = 0; + for (int s = 0; s < 0xe; s++) { + const int32_t v = rec32(g, m, 0xa34 + size_t(s) * 0xc); + if (v != 0) boards++; + r[1] = wrap(int64_t(r[1]) + int64_t(v) * months); + } + if (g.memory.u8(::bmh::layout::GameMode) == 1 || (g.memory.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0)) boards = 0xe; + if (boards != 0 && boards < 0xe) { + int32_t missing = (r[1] / boards) * (0xe - boards); + if (months != 0) missing /= months; + r[1] = wrap(int64_t(r[1]) + int64_t(months) * ((int64_t(missing) * 0x50) / 100)); + } + r[7] = wrap(int64_t(r[7]) + int64_t(monthly_pay(g, m)) * months); + r[8] = wrap(int64_t(r[8]) + int64_t(facility_costs(g, m)) * months); + r[4] = wrap(int64_t(r[4]) + int64_t(facility_income(g, m)) * months); + const uint32_t catering = catering_per_game(g, m, r[kBalanceAverageGate]); + r[4] = wrap(int64_t(r[4]) + int64_t((catering * uint32_t(home)) / 12) * months); + const uint32_t costs = ::bmh::layout::Spending + uint32_t(m) * 0x24; + for (int k = 0; k < 3; ++k) { + const auto value = modern::environment_monthly_cost(g, m, k); + const auto raw = mem32(g, costs + uint32_t(k) * 4); + const int count = k == kYouthAcademy && raw > kEnvironmentStep[k] * 6 ? 1 : months; + r[9] = wrap(int64_t(r[9]) + int64_t(count) * value); + } + for (int k = 0; k < 3; k++) r[size_t(10 + k)] = wrap(int64_t(r[size_t(10 + k)]) + int64_t(months) * mem32(g, costs + 0xc + uint32_t(k) * 4)); + for (int k = 0; k < 2; k++) r[size_t(14 + k)] = wrap(int64_t(r[size_t(14 + k)]) + int64_t(months) * rec32(g, m, 0x854 + size_t(k) * 4)); + } + d.refresh = 0; + } + // the view "real" leaves out the season tickets of the remaining league home games + int32_t season_tickets = 0; + if (view == 1) { + int32_t sold = int32_t(uint16_t(rec8(source, m, 0x2ac) | rec8(source, m, 0x2ad) << 8)); + if (r[kBalanceAverageGate] < sold) sold = r[kBalanceAverageGate]; + int32_t games = r[kBalanceLeagueHomeGames] - int8_t(rec8(source, m, 0x28c)); + if (games < 0) games = 0; + season_tickets = wrap(int64_t((sold * 0x46) / 100) * r[kBalanceTicketPrice] * games); + } + r[3] = wrap(int64_t(r[3]) + (int64_t(home) * r[kBalanceTicketPrice] * r[kBalanceAverageGate] - season_tickets)); + double total = 0; + for (int i = 0; i < kBalanceItems; i++) { + if (r[size_t(i)] < 0) r[size_t(i)] = 0; + total += double(r[size_t(i)]) * (i < 7 ? 1 : -1); + } + d.depreciation = view < 2 ? rec32(source, m, 0x30c) : 0; + d.total = total - double(d.depreciation); +} + +} // namespace + +// StadiumRequiredAttendance: Source's monthly preview differs from booked month_change totals. +// Prediction may touch scratch tables; both pay previews run on an owned copy. +int32_t stadium_required_attendance(const ModernState& source, int manager) { + if (manager < 0 || manager > 4) throw FormatError("stadium attendance: invalid manager"); + ModernState g = source; + const int team = g.manager_teams.at(size_t(manager)); + const int league = team > 0x164 ? 0 : team_league(team); + if (league < 0 || league >= kLeagueCount) + throw FormatError("stadium attendance: manager has no Source league"); + const int home_games = league_matchdays(league) / 2; + if (home_games <= 0) throw FormatError("stadium attendance: invalid Source league home count"); + const int m = manager; + int32_t costs = wrap(int64_t(facility_costs(g, m)) + rec32(g, m, 0x854) + rec32(g, m, 0x858)); + costs = wrap(int64_t(costs) + monthly_pay(g, m, 0xa)); + for (int k = 0; k < 6; ++k) { + const int32_t value = modern::environment_monthly_cost(g, m, k); + costs = wrap(int64_t(costs) + value); + } + costs = wrap(int64_t(costs) - shares_and_loans(g, m, 2, 0) + int(rec8(g, m, 0x179)) * 1000); + if (costs < 0) costs = 0; + int32_t income = facility_income(g, m); + for (int i = 0; i < 16; ++i) income = wrap(int64_t(income) + rec32(g, m, 0xa34 + size_t(i) * 12)); + constexpr int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; // DeskState_DeskDate_RuntimeField + const int month = modern::month_code(g.date); + if (month < 1 || month > 12) throw FormatError("stadium attendance: invalid Source month"); + income = wrap(int64_t(income) + shares_and_loans(g, m, 1, 0) - + int64_t(daily_interest_preview(g, m)) * days[month]); + const int32_t bonus = monthly_pay(g, m, 9); + int32_t needed = wrap(int64_t(wrap(int64_t(costs) - income)) * 12 + bonus) / home_games; + const int price = rec8(g, m, 0x26e); + if (price != 0) needed /= price; + return std::max(needed, int32_t(0)); +} + +BalancePlanDraft open_balance_plan(const ModernState& g, int manager) { + BalancePlanDraft d; + d.manager = manager; + const int m = manager; + d.view = BalanceView(std::clamp(int(int8_t(rec8(g, m, 0x310))), 0, 2)); + const int league = team_league(g.manager_teams.at(size_t(m))); + auto& r = d.rows; + r[kBalanceLeagueHomeGames] = league < kLeagueCount ? league_matchdays(league) / 2 : 0; + r[kBalanceOtherHomeGames] = rec32(g, m, 0x2f8); + r[kBalanceAverageGate] = rec32(g, m, 0x2fc); + uint8_t ticket = g.memory.has(kPlanTicketPrice + uint32_t(m)) ? g.memory.u8(kPlanTicketPrice + uint32_t(m)) : 0; + if (ticket == 0) ticket = rec8(g, m, 0x26e); + r[kBalanceTicketPrice] = ticket; + r[kBalanceAccount] = rec32(g, m, 0x314); + // the average gate of the last league home games (+0x340, count +0x283) + int32_t sum = 0; + const int games = rec8(g, m, 0x283); + for (int i = 0; i < games; i++) sum = wrap(int64_t(sum) + rec32(g, m, 0x340 + size_t(i) * 4)); + r[kBalanceGateSoFar] = games != 0 ? sum / games : sum; + if (rec32(g, m, 0x300) != 0) r[kBalanceAverageGate] = rec32(g, m, 0x304) / rec32(g, m, 0x300); + for (int i = 0; i < kBalanceItems; i++) d.adjustments[size_t(i)] = rec32(g, m, 0x2b0 + size_t(i) * 4); + d.refresh = 2; + redraw(g, d); + return d; +} + +void cycle_balance_view(const ModernState& g, BalancePlanDraft& d) { + d.view = BalanceView((int(d.view) + 1) % 3); + d.refresh = d.rows[kBalanceAverageGate] != 0 ? 2 : 1; + redraw(g, d); +} + +void reset_balance_plan(const ModernState& g, BalancePlanDraft& d) { + d.adjustments.fill(0); + d.refresh = 1; + redraw(g, d); +} + +int32_t balance_row_maximum(const BalancePlanDraft& d, int row) { + if (row < 0 || row >= 0x16 || !kEditable[row]) return -1; + (void)d; // the input dialog BalanceFromGame only offers other step sizes for the gate + return kMaximum[kMaximumClass[row]]; +} + +BalanceEditStatus edit_balance_plan(const ModernState& g, BalancePlanDraft& d, int row, int32_t value) { + if (row < 0 || row >= 0x16 || !kEditable[row]) return BalanceEditStatus::not_editable; + if (d.view == BalanceView::so_far) return BalanceEditStatus::view_so_far; + if (value < 0 || value > modern::balance_row_maximum(d, row)) return BalanceEditStatus::out_of_range; + if (row < kBalanceItems) + d.adjustments[size_t(row)] = wrap(int64_t(d.adjustments[size_t(row)]) + + wrap(int64_t(int8_t(d.months_left)) * (int64_t(value) - d.rows[size_t(row)])) / 12); + d.rows[size_t(row)] = value; + if (row > 0x11) d.refresh = 2; + redraw(g, d); + return BalanceEditStatus::changed; +} + +bool close_balance_plan(ModernState& g, const BalancePlanDraft& d) { + const int m = d.manager; + const bool warning = double(rec32(g, m, 0x314)) + d.total < -4000000.0; // BalancePlanRuntimeField8 + for (int i = 0; i < kBalanceItems; i++) set_rec32(g, m, 0x2b0 + size_t(i) * 4, d.adjustments[size_t(i)]); + set_rec32(g, m, 0x308, int32_t(std::lround(d.total))); + if (g.memory.has(kPlanTicketPrice + uint32_t(m))) g.memory.set8(kPlanTicketPrice + uint32_t(m), uint8_t(d.rows[kBalanceTicketPrice])); + set_rec32(g, m, 0x2f8, d.rows[kBalanceOtherHomeGames]); + set_rec32(g, m, 0x2fc, d.rows[kBalanceAverageGate]); + set_rec32(g, m, 0x310, int32_t(d.view)); + return warning; +} + +} // namespace bmh::modern diff --git a/src/modern/game/balance_plan.hpp b/src/modern/game/balance_plan.hpp new file mode 100644 index 0000000..a21eb05 --- /dev/null +++ b/src/modern/game/balance_plan.hpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/balance_plan.hpp" +// All three youth budgets and staff costs share the monthly environment model. +// The balance plan ("Bilanz", desk menu 28, mode III; H2 p. 26-27; BMH.exe V2.24 + supported rule profile +// patch): the screen BalanceFromGame2 projects the club's income and expenses for the business +// year and lets the manager change every item. When he leaves the screen the resulting +// profit/loss becomes the plan figure (manager record +0x308). On the 16th Bundesliga +// matchday the plan is handed to the DFB (+0x308 -> +0x320, matchday.cpp); from then on it +// lifts or lowers the advertising offers (weekly.cpp, plan / 100000 within -10..10) and at +// the end of the season the DFB punishes a result more than 1 million below the plan +// (season.cpp, SeasonEvent). +// +// The screen has three views (left button, captions BalancePlan_DrawButtons_TextPointer): +// so_far "bisher" - the booked figures of the season so far (record +0x85c..), no changes +// real "real" - booked figures plus a projection for the months left +// future "zukunft" - a projection for twelve months +// The manager's changes are kept per item normalised to twelve months (record +0x2b0, the +// screen's local_c8) and are added again on the next visit; "Werte akt." (right button) +// drops them. +// +// The screen's state is a BalancePlanDraft (the locals of BalanceFromGame2); the functions below +// are its event handlers. Projections run on a copy of the ModernState: the wage projection +// (MonthlyPay -> table prediction) writes scratch tables, and a console must be able to +// look at the plan without changing the game. + +#include +#include + +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +constexpr int kBalanceItems = 18; // 0-6 income, 7-17 expenses (labels BalancePlan_DrawRows_TextPointer5) +// Rows after the items (labels BalancePlan_DrawRows_TextPointer4): league home games, other home games, average +// gate (calculated), ticket price, average gate so far, account balance. + + + +// BalanceFromGame2 up to its first redraw: the draft of `manager` with the stored view, the +// stored changes and the projection of that view. +// StadiumRequiredAttendance: minimum average attendance at the current stadium entry price. +// Pure preview, using a copy for Source prediction scratch writes; no RNG. +int32_t stadium_required_attendance(const ModernState&, int manager); + +BalancePlanDraft open_balance_plan(const ModernState& g, int manager); + +// The left button: the next view (so_far -> real -> future -> so_far), projected again. +void cycle_balance_view(const ModernState& g, BalancePlanDraft& draft); +// The right button "Werte akt.": drops the manager's changes and projects again. +void reset_balance_plan(const ModernState& g, BalancePlanDraft& draft); + +// Range of a row in the number input (BalanceFromGame): 0 .. maximum. +int32_t balance_row_maximum(const BalancePlanDraft& draft, int row); +// A click on a row and a new value: items keep the change in `adjustments` (scaled to twelve +// months); the home games, the gate and the ticket price project the plan again. +BalanceEditStatus edit_balance_plan(const ModernState& g, BalancePlanDraft& draft, int row, int32_t value); + +// Leaving the screen: writes the changes (+0x2b0), the plan figure (+0x308), the other home +// games and the gate (+0x2f8/+0x2fc), the view (+0x310) and the ticket price of the plan +// (PlanTicketPrice). Returns true when the DFB demands a better balance (account + plan below +// -4 million, message BalancePlan_BalanceFromGame_TextPointer2) - the plan is stored nevertheless. +bool close_balance_plan(ModernState& g, const BalancePlanDraft& draft); + +} // namespace bmh::modern diff --git a/src/modern/game/bank_credit.cpp b/src/modern/game/bank_credit.cpp new file mode 100644 index 0000000..cb5f1e2 --- /dev/null +++ b/src/modern/game/bank_credit.cpp @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/bank_credit.hpp" + +#include +#include +#include +#include +#include +#include +#include "modern/game/matchday.hpp" + +namespace bmh::modern { +namespace { +constexpr uint32_t kLoans = ::bmh::layout::Loans; +constexpr size_t kRecord = 0xb0c; +int32_t signed_word(uint32_t v) { return std::bit_cast(v); } +uint32_t word(int32_t v) { return std::bit_cast(v); } +int32_t add(int32_t a, int32_t b) { return signed_word(word(a) + word(b)); } +int32_t sub(int32_t a, int32_t b) { return signed_word(word(a) - word(b)); } +int32_t mul(int32_t a, int32_t b) { return signed_word(word(a) * word(b)); } +int32_t divide(int32_t a, int32_t b) { + if (!b || (a == std::numeric_limits::min() && b == -1)) + throw std::invalid_argument("invalid native credit division"); + return a / b; +} +uint32_t read_record(const ModernState& g, size_t at) { + uint32_t v = 0; + for (int i = 0; i < 4; ++i) v |= uint32_t(g.manager_records.at(at + i)) << (i * 8); + return v; +} +// Amount: signed IMUL/IDIV, x87 intermediate, QWORD store, +// exact-zero floor, then Amount2's explicit rounding toward zero. +int32_t amount(const BankCreditContext& c, uint32_t months, int32_t principal) { + if (months > 48 || c.rate_table[months] <= 100 || c.divisor != 100.0) + throw std::invalid_argument("invalid native credit factors"); + const int32_t factor = c.rate_table[months]; + const int32_t base = divide(mul(principal, factor), 100); + const int32_t den = divide(10000, factor - 100); + const long double intermediate = (static_cast(base) / c.divisor) + * den / c.divisor; + double raw = static_cast(intermediate); + if (raw == 0 && principal != 0) raw = 1; + raw = std::trunc(raw); + if (!std::isfinite(raw) || raw < std::numeric_limits::min() + || raw > std::numeric_limits::max()) + throw std::invalid_argument("invalid native credit amount"); + return static_cast(raw); +} +void balance(const BankCreditContext& c, BankCreditDraft& d) { + int32_t result = add(c.cash, signed_word(d.values[0])); + result = sub(result, signed_word(c.saved[0])); + result = sub(result, signed_word(d.values[6])); + result = add(result, d.refund); + result = sub(result, d.fees); + d.values[7] = word(sub(result, d.interest_adjustment)); +} +} + +BankCreditContext bank_credit_context(const ModernState& g, const LeImage& exe, int manager, int counterparty) { + BankCreditContext c; + if (manager < 0 || size_t(manager) >= g.manager_teams.size() + || g.manager_records.size() < (size_t(manager) + 1) * kRecord) return c; + // case 5: another human manager lends (row lender + 1 of the borrower's matrix) + if (counterparty < 0 || counterparty > 4 || counterparty - 1 == manager || + (counterparty > 0 && size_t(counterparty - 1) >= g.manager_teams.size())) return c; + c.counterparty = counterparty; + const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(counterparty) * 0x18; + try { + for (size_t i = 0; i < c.saved.size(); ++i) c.saved[i] = g.memory.u32(at + uint32_t(i) * 4); + for (size_t i = 0; i < c.rate_table.size(); ++i) c.rate_table[i] = exe.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i)); + const uint64_t bits = uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32; + c.divisor = std::bit_cast(bits); + const size_t rec = size_t(manager) * kRecord; + c.cash = signed_word(read_record(g, rec + 0x314)); + c.overdraft = signed_word(read_record(g, rec + 0x31c)); + if (counterparty > 0) { + const size_t lender = size_t(counterparty - 1) * kRecord; + c.lender_liquidity = add(signed_word(read_record(g, lender + 0x314)), signed_word(read_record(g, lender + 0x31c))); + } + c.available = c.divisor == 100.0 && c.saved[3] <= 48 && c.saved[4] <= 48; + for (auto factor : c.rate_table) c.available = c.available && factor > 100; + } catch (const std::out_of_range&) { return {}; } + return c; +} + +bool change_bank_credit_interest(ModernState& g, int manager, uint8_t new_rate) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || !g.credit_rate_table_available) + return false; + const uint32_t at = kLoans + uint32_t(manager) * 0x78; + for (uint32_t i = 0; i < 24; ++i) if (!g.memory.has(at + i)) return false; + try { + const int32_t principal = signed_word(g.memory.u32(at)); + const int32_t term = signed_word(g.memory.u32(at + 12)); + const int32_t elapsed = signed_word(g.memory.u32(at + 16)); + const int32_t remaining = sub(principal, mul(divide(principal, term), elapsed)); + const int32_t adjusted = divide(remaining, 100); + const int32_t next_principal = mul(adjusted, 100 - int32_t(new_rate)); + const int32_t next_term = sub(term, elapsed); + BankCreditContext c; + c.rate_table = g.credit_rate_table; + c.divisor = g.credit_divisor; + const uint32_t payment = word(amount(c, uint32_t(next_term), next_principal)); + g.memory.set32(at, word(next_principal)); + g.memory.set32(at + 12, word(next_term)); + g.memory.set32(at + 16, 0); + g.memory.set32(at + 20, 0); + g.memory.set32(at + 8, payment); + g.memory.set32(at + 4, payment * uint32_t(next_term)); + return true; + } catch (const std::exception&) { return false; } +} + +BankCreditDraft bank_credit_draft(const BankCreditContext& c) { + BankCreditDraft d; + for (size_t i = 0; i < c.saved.size(); ++i) d.values[i] = c.saved[i]; + // Source clears the working paid field after its first rendering. The UI + // still uses the saved field for that initial display. + d.values[5] = 0; + d.values[7] = word(c.cash); + return d; +} + +BankCreditBounds bank_credit_bounds(const BankCreditContext& c, const BankCreditDraft& d, int field) { + if (!c.available || (field != 0 && field != 1 && field != 3 && field != 6 && !(field == 2 && c.counterparty)) + || (field == 6 && !c.saved[0])) return {}; + try { + const auto& v = d.values; + int32_t accrued = 0; + if (v[0]) { + const uint32_t elapsed = v[4] ? v[4] : 1; + accrued = sub(mul(amount(c, elapsed, signed_word(v[0])), signed_word(elapsed)), + signed_word(v[5])); + } + const int32_t liquidity = add(c.cash, c.overdraft); + int32_t lo = 0, hi = 0; + if (field == 0) { + lo = 1000; + hi = sub(12000000, accrued); + // case 5: no more than the lender can pay out (balance + credit line) + if (c.counterparty && c.lender_liquidity < hi) hi = sub(c.lender_liquidity, accrued); + } + if (field == 2) { + // case 5 only: the monthly payment within 20 % of the annuity (Amount + // with the term and the net principal); the input starts at the annuity of + // the whole principal + const int32_t rate = amount(c, v[3], signed_word(v[0] - v[6])); + lo = sub(rate, rate / 5); + hi = add(rate, rate / 5); + if (lo >= hi || lo < 0) return {}; + return {word(lo), word(hi), word(amount(c, v[3], signed_word(v[0]))), true}; + } + if (field == 1) { lo = c.cash < accrued ? sub(accrued, liquidity) : liquidity; hi = accrued; } + if (field == 3) { + lo = 1; + hi = amount(c, v[3], signed_word(v[0] - v[6])) == 0 ? 0 : 48; + } + if (field == 6) { hi = liquidity < accrued ? liquidity : signed_word(v[0]); } + // Source checks availability before overriding the principal bounds. + if (lo >= hi) return {}; + if (field == 0 && lo < signed_word(c.saved[0])) { lo = signed_word(c.saved[0]); hi = 12000000; } + if (lo < 0 || hi < 0 || lo >= hi) return {}; + return {word(lo), word(hi), word(lo - (lo == 1)), true}; + } catch (const std::invalid_argument&) { return {}; } +} + +bool edit_bank_credit(const BankCreditContext& c, BankCreditDraft& draft, int field, uint32_t value) { + const auto bounds = modern::bank_credit_bounds(c, draft, field); + if (!bounds.available || value < bounds.minimum || value > bounds.maximum) return false; + BankCreditDraft d = draft; + try { + if (!d.interest_adjustment) { + d.principal_paid = c.saved[3] + ? mul(signed_word(c.saved[4]), divide(signed_word(c.saved[0]), signed_word(c.saved[3]))) + : mul(signed_word(c.saved[0]), signed_word(c.saved[4])); + } + d.values[field] = value; + // fees only for the bank (case 4) + d.fees = !c.counterparty && c.saved[0] && (d.values[6] || d.values[3] != c.saved[3]) ? 5000 : 0; + if (!d.interest_adjustment && (field == 0 || field == 3 || field == 6)) { + const int32_t term = c.saved[3] ? signed_word(c.saved[3]) : 1; + const int32_t saved_p = signed_word(c.saved[0]); + const int32_t remaining = sub(saved_p, d.principal_paid); + const int32_t interest = sub(sub(amount(c, 1, saved_p), saved_p), + sub(amount(c, 1, remaining), remaining)); + d.interest_adjustment = divide(mul(interest, signed_word(c.saved[3] - c.saved[4])), term); + d.refund = mul(signed_word(c.saved[4]), divide(saved_p, term)); + d.values[4] = d.values[5] = 0; + d.principal_paid = 0; + } + if (field != 2 && field != 3 && field != 6) d.values[3] = 48; + const int32_t net = signed_word(d.values[0] - d.values[6]); + // a monthly payment set in case 5 stays; every other edit computes the annuity + if (field != 2) d.values[2] = net ? word(amount(c, d.values[3], net)) : 0; + if (d.fees) d.fees = add(d.fees, sub(amount(c, 1, signed_word(d.values[6])), signed_word(d.values[6]))); + d.values[1] = d.values[2] * d.values[3]; + d.initial_display = false; + d.edits.push_back({field, value}); + balance(c, d); + } catch (const std::invalid_argument&) { return false; } + draft = std::move(d); + return true; +} + +BankCreditResult commit_bank_credit(ModernState& g, const LeImage& exe, int manager, + const std::array& expected, const std::vector& edits, bool accept_fees, + int counterparty) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return {BankCreditStatus::invalid_manager}; + const auto c = modern::bank_credit_context(g, exe, manager, counterparty); + if (!c.available) return {BankCreditStatus::invalid_state}; + if (c.saved != expected) return {BankCreditStatus::stale_request}; + if (edits.empty()) return {BankCreditStatus::no_change}; + if (edits.size() > 4096) return {BankCreditStatus::invalid_request}; + auto d = modern::bank_credit_draft(c); + for (const auto& edit : edits) + if (!modern::edit_bank_credit(c, d, edit.field, edit.value)) return {BankCreditStatus::invalid_request}; + // only the bank charges (and asks for) fees and the interest adjustment + const int32_t fees = c.counterparty ? 0 : add(d.fees, d.interest_adjustment); + const int lender = c.counterparty - 1; + if (fees && !accept_fees) return {BankCreditStatus::confirmation_required, fees, d.refund}; + auto resulting_record = c.saved; + if (!d.values[1]) resulting_record.fill(0); + else { + for (size_t i = 0; i < 5; ++i) resulting_record[i] = d.values[i]; + resulting_record[0] -= d.values[6]; + if (signed_word(resulting_record[1]) < signed_word(resulting_record[0])) + resulting_record[1] += resulting_record[0]; + if (signed_word(resulting_record[0]) < 1) resulting_record[0] = 1; + if (d.refund) resulting_record[4] = resulting_record[5] = 0; + } + if (!fees && !d.refund && c.saved[0] - d.values[0] + d.values[6] == 0 + && resulting_record == c.saved) return {BankCreditStatus::no_change}; + ModernState staged = g; + if (fees) modern::book_money(staged, manager, fees, true, false); + if (d.refund) { + d.values[4] = 0; + // the repaid part comes back from the bank or from the lender + if (lender >= 0) modern::book_money(staged, lender, d.refund, true, false); + modern::book_money(staged, manager, sub(0, d.refund), true, false); + } + const int32_t principal_change = signed_word(c.saved[0] - d.values[0] + d.values[6]); + modern::book_money(staged, manager, principal_change, true, false); + if (lender >= 0) modern::book_money(staged, lender, sub(0, principal_change), true, false); + const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(c.counterparty) * 0x18; + if (!d.values[1]) { + for (uint32_t i = 0; i < 6; ++i) staged.memory.set32(at + i * 4, 0); + } else { + d.values[0] -= d.values[6]; + if (signed_word(d.values[1]) < signed_word(d.values[0])) d.values[1] += d.values[0]; + if (signed_word(d.values[0]) < 1) d.values[0] = 1; + for (uint32_t i = 0; i < 5; ++i) staged.memory.set32(at + i * 4, d.values[i]); + if (d.refund) staged.memory.set32(at + 20, 0); + } + g = std::move(staged); + return {BankCreditStatus::accepted, fees, d.refund}; +} +} // namespace bmh::modern diff --git a/src/modern/game/bank_credit.hpp b/src/modern/game/bank_credit.hpp new file mode 100644 index 0000000..52edab9 --- /dev/null +++ b/src/modern/game/bank_credit.hpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/bank_credit.hpp" + +#include +#include +#include +#include "formats/le.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// MaxSharesToBuy case 4 (the bank) and case 5 (another manager lends). Row c of +// each manager's native 0x78-byte loan matrix (Loans + borrower * 0x78 + c * 0x18) +// is the credit from the bank (c = 0) or from manager c - 1, and contains principal, +// total, monthly payment, term, elapsed months and payments made. Case 5 differs only +// in: the principal is limited by the lender's balance plus credit line, the monthly +// payment (field 2) can be set within 20 % of the annuity, there are no fees and no +// fee question, and every booking is mirrored on the lender. The original asks the +// lender nothing. Projection and draft editing are read-only. + + + + +BankCreditContext bank_credit_context(const ModernState&, const LeImage&, int manager, int counterparty = 0); +// ChangeBankCreditInterest: apply the automatic interest change to the bank loan record. +bool change_bank_credit_interest(ModernState&, int manager, uint8_t new_rate); +BankCreditDraft bank_credit_draft(const BankCreditContext&); +BankCreditBounds bank_credit_bounds(const BankCreditContext&, const BankCreditDraft&, int field); +bool edit_bank_credit(const BankCreditContext&, BankCreditDraft&, int field, uint32_t value); + + +// Replay the local Source edits against the current native record before +// booking; fees and refund are derived here, never trusted from a UI amount. +BankCreditResult commit_bank_credit(ModernState&, const LeImage&, int manager, + const std::array& expected, const std::vector& edits, + bool accept_fees, int counterparty = 0); + +} // namespace bmh::modern diff --git a/src/modern/game/career.cpp b/src/modern/game/career.cpp new file mode 100644 index 0000000..5172637 --- /dev/null +++ b/src/modern/game/career.cpp @@ -0,0 +1,684 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/career.hpp" + +#include + +#include "game/messages.hpp" +#include "game/schedule.hpp" + +namespace bmh::modern { + +namespace { + + +// LeagueSizes: clubs per league; LeagueStrengthRanges: (minimum, maximum) strength per league. +// (the clubs per league are kLeagueSizes, schedule.hpp) +constexpr int kLeagueStrength[9][2] = {{71, 93}, {49, 71}, {28, 49}, {28, 49}, {10, 28}, + {85, 95}, {90, 95}, {75, 95}, {80, 95}}; + +} // namespace + +void generate_player(ModernState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand) { + Player& p = g.players.at(size_t(id)); + const bool keep_age = (level_flags & 0x1000) != 0, exact = (level_flags & 0x2000) != 0; + const int level = int16_t(level_flags & 0x0fff); + uint32_t w = 0x3000000; // goalkeepers + if ((p.w364 & 3) != 0) { + w = uint32_t(game.range(0, 7)) << 24; + w += uint32_t(game.range(0, 7)) << 21; + } + const int lo = exact ? level : level - level / 10, hi = exact ? level : level + level / 10; + const int condition = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63); // ClampInteger + w += uint32_t(condition) << 14; + const int technique = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63); + w += uint32_t(technique) << 7; + p.w35c = w + uint32_t(game.range(0x23, 0x41)); + p.w368 = (p.w368 & 0xff03c000u) + uint32_t(rand.range(0, 0x3fff)); + p.w364 &= ~(0x1fu << 21); + if (!keep_age) p.w364 |= uint32_t(game.range(2, 5)) << 21; +} + +std::vector startup_squad_list(const Database& db) { + std::vector slots(total_squad_slots(), 0x0fff); + for (size_t i = 0; i + 1 < db.squad_list.size() && i / 2 < slots.size(); i += 2) + slots[i / 2] = uint16_t(db.squad_list[i] | db.squad_list[i + 1] << 8); + std::copy_backward(slots.begin() + long((transfer_list_slot() + 40)), slots.begin() + long((transfer_list_slot() + 40) + (total_squad_slots() - free_agent_slot())), slots.end()); + return slots; +} + +void startup_players(ModernState& g, GameRandom& game, WatcomRandom& rand) { + for (size_t i = 0; i < 0x36; i++) { + const int level = rand.range(i < 0x16 ? 0x14 : 0x46, 0x5a); + modern::generate_player(g, int16_t(g.squad_slots.at((pool_end_slot() + 24) + i)), int16_t(level), game, rand); + } + int previous = 0, index = -1; // local_18, local_1c + for (int team = 0; team < league_clubs(); team++) { + const int league = team_league(team); + index = league == previous ? index + 1 : 0; + previous = league; + const uint32_t count = uint32_t(kLeagueSizes[league]); + const uint32_t range = uint32_t(kLeagueStrength[league][1] - kLeagueStrength[league][0]); + const int level = int16_t(int((count - uint32_t(index)) * range * 100) / int(count) / 100) + kLeagueStrength[league][0]; + const SquadRange r = squad_range(team); + for (size_t s = r.first; s < r.first + r.count; s++) { + const int id = g.squad_slots.at(s) & 0x0fff; + if (id != 0x0fff) modern::generate_player(g, id, level | 0x1000, game, rand); + } + } +} + +} // namespace bmh::modern + +#include "formats/le.hpp" +#include "formats/savestate.hpp" + +namespace bmh::modern { + +ModernState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat) { + const DbCounts counts; + const std::vector layout = save_layout(counts, true); + Bytes stream; + for (const SaveBlock& b : layout) { + Bytes data(b.size, 0); + auto put = [&](const Bytes& src, size_t at = 0) { + for (size_t i = 0; i < src.size() && at + i < data.size(); i++) data[at + i] = src[i]; + }; + if (!b.heap) { + for (size_t i = 0; i < b.size; i++) + if (exe.contains(b.address + uint32_t(i))) data[i] = exe.u8(b.address + uint32_t(i)); + } + switch (b.address) { + case ::bmh::layout::PlayerBonuses: if (b.heap) put(db.raw_player_bonus_values); break; + case ::bmh::layout::ClubBadgeSelectors: if (b.heap) put(db.raw_club_badge_selectors); break; + case ::bmh::layout::ClubIdentities: if (b.heap) put(db.raw_club_name_offsets); break; + case ::bmh::layout::PlayerNameOffsets: if (b.heap) put(db.raw_player_name_offsets); break; + case ::bmh::layout::MasterDatabaseMetadata: if (b.heap) put(db.raw_database_metadata); break; + case ::bmh::layout::ClubAuxiliaryWords: if (b.heap) put(db.raw_club_auxiliary_words); break; + case ::bmh::layout::ForeignClubStrength: put(db.raw_foreign_club_strength); break; + case ::bmh::layout::Career_Put_ExecutableField3: put(db.raw_league_auxiliary_bytes); break; + case ::bmh::layout::RefereeProperties: put(db.raw_referee_properties); break; + case ::bmh::layout::ClubKitSelectors: put(db.raw_club_kit_selectors); break; + case ::bmh::layout::ClubShortNameOffsets: put(db.raw_club_short_name_offsets); break; + case ::bmh::layout::ClubSeasonRecords: if (!b.heap) data[0] = 1; break; // the pointer: records allocated + case ::bmh::layout::NextDeskManager: + for (size_t m = 0; m < 4; m++) data[m * 2] = uint8_t(m), data[m * 2 + 1] = 0; + break; + case ::bmh::layout::ManagerAutomation: + for (size_t m = 0; m < 4; m++) data[m * 5] = 1; + break; + case ::bmh::layout::ActiveManager: data[0] = 4; break; + case ::bmh::layout::Desktops: + for (size_t k = 0; k < 5; k++) put(m3_men, k * 0x360); + break; + case ::bmh::layout::Formations: + put(m3_dat); + for (size_t k = 1; k < 4; k++) + for (size_t i = 0; i < 0x160; i++) data[k * 0x160 + i] = data[i]; + break; + case ::bmh::layout::SquadSlots: + if (b.heap) { + const std::vector slots = modern::startup_squad_list(db); + for (size_t i = 0; i < slots.size() && 2 * i + 1 < data.size(); i++) + data[2 * i] = uint8_t(slots[i]), data[2 * i + 1] = uint8_t(slots[i] >> 8); + } + break; + case ::bmh::layout::PlayerConditionTechniqueForm: + case ::bmh::layout::PlayerSkillWords: + case ::bmh::layout::PlayerIdentityWords: + if (b.heap) { + for (size_t i = 0; i < db.players.size() && 4 * i + 3 < data.size(); i++) { + uint32_t w = b.address == ::bmh::layout::PlayerConditionTechniqueForm ? db.players[i].w35c : b.address == ::bmh::layout::PlayerSkillWords ? db.players[i].w368 : db.players[i].w364; + if (b.address == ::bmh::layout::PlayerSkillWords && i + 32 >= db.players.size()) + w = (w & 0x07ffffffu) | uint32_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 - uint32_t(db.players.size() - i))) << 27; + for (int k = 0; k < 4; k++) data[4 * i + size_t(k)] = uint8_t(w >> (8 * k)); + } + } + break; + default: break; + } + stream.insert(stream.end(), data.begin(), data.end()); + } + for (const Bytes& pool : db.pools) { + stream.push_back(uint8_t(pool.size())); + stream.push_back(uint8_t(pool.size() >> 8)); + stream.insert(stream.end(), pool.begin(), pool.end()); + } + const SaveState save(stream, counts); + ModernState g = GameState::from_save(save, counts); + modern::competition_pointers(g.memory, exe); // CompetitionPointers + return g; +} + +} // namespace bmh::modern + +#include "modern/game/matchday.hpp" +#include "modern/game/season.hpp" +#include "modern/game/week.hpp" + +namespace bmh::modern { + +void new_career_markets_and_moods(ModernState& g, GameRandom& game, WatcomRandom& rand) { + StaticMemory& mem = g.memory; + for (uint32_t k = 0; k < 12; k++) { + if (k < 6) mem.set32(::bmh::layout::FundBlock + k * 0x1c, (1u << k) * 100000); + const size_t s = size_t(k) * 0x5c; + const uint32_t value = k * 2000 + 10000; + for (int i = 0; i < 4; i++) g.stocks.at(s + size_t(i)) = uint8_t(value >> (8 * i)); + g.stocks.at(s + 0x4e) = uint8_t(k * 20 + 100), g.stocks.at(s + 0x4f) = uint8_t((k * 20 + 100) >> 8); + } + modern::stir_random(game, rand); + const int first = game.range(0, 1); + if (g.texts) { + auto name = [&](int record, uint32_t pointer) { + const std::string& t = (*g.texts)[(pointer - ::bmh::layout::TextPointerTable) / 4]; + const size_t at = size_t(record) * 0xb0c + 0xa8; + for (size_t i = 0; i <= t.size(); i++) g.manager_records.at(at + i) = i < t.size() ? uint8_t(t[i]) : 0; + }; + name(first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField); + name(1 - first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField2); + name(2, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField3); + name(3, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField4); + } + for (int day = 0; day < 30; day++) modern::stock_market(g, game); + for (uint32_t i = 0; i < 900; i++) mem.set8(::bmh::layout::Titles + i, 0xff); + for (uint32_t i = 0; i < 4; i++) mem.set8(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField2 + i, uint8_t(1 << i)); + for (uint32_t i = 0; i < 0x2c; i++) mem.set16(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField + i * 0x58, 0xfff); + modern::reset_club_moods(g, game, rand, true); +} + +bool new_career_players(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + for (size_t slot = 0; slot < transfer_list_slot(); slot++) { + const int id = g.squad_slots.at(slot) & 0x0fff; + if (id == 0x0fff) continue; + Player& p = g.players.at(size_t(id)); + p.w364 |= uint32_t(rand.range(4, 0x10)) << 21; + p.w368 = (p.w368 & 0xffffc000u) + uint32_t(rand.range(0, 0x3fff)); + } + for (int slot = 3096; slot < 3096 + 0x36; slot++) + if (!modern::release_player(g, slot, game, rand, report)) return false; + return !report.unsupported; +} + +bool new_career_before_dialog(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + // CareerFirstSteps2 clears all four pending offers immediately before calling + // InitializeCareer. Raw executable BSS starts at zero, which is a valid offer + // for manager/player zero in ResolvePendingOffer, rather than the empty sentinel. + for (uint32_t offer = 0; offer < 4; ++offer) + g.memory.set32(::bmh::layout::OfferSlots + offer * 4, 0xffffffff); + modern::new_career_markets_and_moods(g, game, rand); + return modern::new_career_players(g, game, rand, report); +} + +} // namespace bmh::modern + +#include "game/lineup.hpp" +#include "modern/game/national.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecord = 0xb0c; + +uint16_t team_of(const ModernState& g, int m) { + const size_t at = size_t(m) * kRecord + 0x290; + return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); +} + +// FindManagerForClub: a club of a human manager (manager slot 4 counts when manager 0 coaches +// the national team). +bool human_club(const ModernState& g, int team) { + const int managers = g.memory.u8(::bmh::layout::ManagerCount); + for (int m = 0; m < managers; m++) + if (team_of(g, m) == uint16_t(team)) return true; + return team_of(g, 0) == no_team() && team_of(g, 4) == uint16_t(team); +} + +// OpenBMH deviates from the original: skips reserved calendar positions when assigning a joining manager to a club. +// The supported rule profile patch reserves club places whose calendar word (CompetitionCalendar, read with the +// club id as index) has the bits 0x4001. +bool reserved_place(const ModernState& g, int team) { + return team >= 0 && (g.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(team) * 2) & 0x4001) == 0x4001; +} + +// EuropeanClub: only the active prefixes of the three European lists count. +bool european_club(const ModernState& g, int team) { + for (const auto& entry : {std::pair{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_EuropeanClub_ExecutableField}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_EuropeanClub_ExecutableField2}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, ::bmh::layout::Career_EuropeanClub_ExecutableField3}}) + for (uint32_t i = 0; i < g.memory.u8(entry.second); ++i) + if (g.memory.u16(entry.first + i * 2) == uint16_t(team)) return true; + return false; +} + +// RemoveJoinTransfers: remove a joining club's sale entries and parallel bid fields. +void remove_join_transfers(ModernState& g, int team) { + StaticMemory& mem = g.memory; + for (uint32_t row = 0; row < 44; ++row) { + const uint32_t base = ::bmh::layout::EditorList + row * 0x58; + if ((mem.u16(base + 8) & 0x7fff) == uint16_t(team)) { + g.squad_slots.at(transfer_list_slot() + row) = kEmptySlot; + continue; + } + int bid = 0; + while (bid < 4 && mem.u16(base + uint32_t(bid) * 2) != uint16_t(team)) ++bid; + if (bid == 4) continue; + const uint32_t found = uint32_t(bid); + if (bid != 3) { + for (uint32_t k = found; k < 3; ++k) { + mem.set16(base + k * 2, mem.u16(base + (k + 1) * 2)); + mem.set32(base + 0xc + k * 4, mem.u32(base + 0xc + (k + 1) * 4)); + mem.set32(base + 0x1c + k * 4, mem.u32(base + 0x1c + (k + 1) * 4)); + mem.set8(base + 0x34 + k, mem.u8(base + 0x34 + k + 1)); + for (uint32_t b = 0; b < 7; ++b) + mem.set8(base + 0x38 + k * 7 + b, mem.u8(base + 0x38 + (k + 1) * 7 + b)); + } + ++bid; // The Source terminator is found + 1, not always the last bid. + } + mem.set16(base + uint32_t(bid) * 2, 0xffff); + if (row > 39) { + g.squad_slots.at(transfer_list_slot() + row + 40) = kEmptySlot; + mem.set32(::bmh::layout::Career_RemoveJoinTransfers_RuntimeField + row * 4, 0xffffffff); + } + } +} + +// ConfirmManager: clean loans only after the final club swap/remapping. +bool remove_join_loans(ModernState& g, int team, MinuteReport& report) { + StaticMemory& mem = g.memory; + for (uint32_t i = 0; i < 200; ++i) { + const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + i * 4, loan = mem.u32(at); + if (loan == 0) continue; + const int owner = int((loan >> 12) & 0x3ff), borrower = int((loan >> 22) & 0x3ff); + if (owner == team) mem.set32(at, 0); + else if (borrower == team) { + mem.set32(at, 0); + if (human_club(g, owner)) { + uint32_t k = 0; + while (k < 12 && mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2) != (loan & 0xfff)) ++k; + if (k == 12) { + report.fail("joining-manager loan has no human owner entry (PresentLoanReturn(0x3c))"); + return false; + } + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2, kEmptySlot); + } + } + } + return true; +} + +void put32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i)); +} + +// CareerAddManager2(team, mode): condition and technique of every player of a league club around +// a level of its league (mode 0 random W(min, max), 1 min + 3, 2 the middle + 1, 3 max - 3). +void set_club_strength(ModernState& g, int team, int mode, WatcomRandom& rand) { + if (team >= league_clubs()) return; + const int league = team_league(team); + const int lo = kLeagueStrength[league][0], hi = kLeagueStrength[league][1]; + int level = mode; + switch (mode) { + case 0: level = rand.range(lo, hi); break; + case 1: level = lo + 3; break; + case 2: level = (hi + lo) / 2 + 1; break; + case 3: level = hi - 3; break; + default: break; + } + level = int16_t(level); + const SquadRange r = squad_range(team); + for (size_t s = r.first; s < r.first + r.count; s++) { + const int id = g.squad_slots.at(s) & 0x0fff; + if (id == 0x0fff) continue; + Player& p = g.players.at(size_t(id)); + const int condition = std::clamp(rand.range(level - 6, level + 6), 0, 99); // ClampInteger + const int technique = std::clamp(rand.range(level - 6, level + 6), 0, 99); + p.w35c = (p.w35c & 0xffe0007fu) | uint32_t(condition) << 14 | uint32_t(technique) << 7; + } +} + +// CareerAddManager3(record, league, mode): the stadium of a human club - eight stand blocks +// (Career_BuildStadium_RuntimeField4[league] thousand places each), the facilities of the league +// (Career_BuildStadium_RuntimeField, levels W(Career_BuildStadium_RuntimeField2, Career_BuildStadium_RuntimeField3) << 2) and eight block values W(100, 140). +// Mode 1 (CareerDuration) builds everything one step better. +void build_stadium(ModernState& g, const LeImage& exe, int m, int league, int mode, WatcomRandom& rand) { + uint8_t* rec = &g.manager_records.at(size_t(m) * kRecord); + for (int k = 0; k < 8; k++) { + rec[0x4c + k] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 + uint32_t(league)) + (mode == 1 ? 1 : 0)); + rec[0x5c] = uint8_t(rec[0x5c] + rec[0x4c + k]); + } + for (int i = 0; i < 0x16; i++) { + const uint8_t level = mode == 1 ? 3 : exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(i + league * 0x17)); + if (i == 0x10 || i == 0x11 || level == 0) continue; + if (i == 0) { + rec[0] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(league * 0x17)) + (mode == 1 ? 0x55 : 0)); + } else { + rec[i] = uint8_t(rand.range(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField2 + uint32_t(i * 5)), exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField3 + uint32_t(i * 5))) << 2); + } + if (i > 0xd) rec[i + 0x2e] = uint8_t(level + (mode == 1 ? 1 : 0)); + } + rec[0x3f] = rec[0x3e] = uint8_t((mode == 1) + 1); + for (int k = 0x16; k < 0x1e; k++) rec[k] = uint8_t(rand.range(100, 0x8c)); +} + +} // namespace + +// StartingSponsors: in mode GameMode == 1 or in the one-year mode before +// the first season day, the three sponsor contracts start at the value for the +// selected league and difficulty. Use ModernState.date: memory CalendarDay can be +// stale in the port after a new-career/season transition. +void starting_sponsors(ModernState& g, int m) { + const StaticMemory& mem = g.memory; + if (!(mem.u8(::bmh::layout::GameMode) == 1 || (mem.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0))) return; + const size_t rec = size_t(m) * kRecord; + int league = g.manager_records.at(rec + 0x210); + if (league > 2) league--; + const int v = (((league * -20 + 80) * 60000 + 1000000) / 12 * (mem.u8(::bmh::layout::Difficulty) * -5 + 0xaa)) / 3000000 * 10000; + for (size_t o : {size_t(0xae8), size_t(0xadc), size_t(0xa34)}) put32(g.manager_records, rec + o, uint32_t(v)); + for (size_t o : {size_t(0xaed), size_t(0xae1), size_t(0xa39)}) g.manager_records.at(rec + o) = 1; +} + +void career_managers_begin(ModernState& g, bool adding) { + g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + const size_t rec = 4 * kRecord; + put32(g.manager_records, rec + 0x314, 1000000); + put32(g.manager_records, rec + 0x324, 1000000); + for (size_t i = 0; i < 0xd; i++) g.manager_records.at(rec + 0xc5 + i) = 2; + if (adding) { + const size_t count = g.memory.u8(::bmh::layout::ManagerCount); + g.manager_teams.resize(count); + for (size_t m = 0; m < count; ++m) g.manager_teams[m] = team_of(g, int(m)); + } else g.manager_teams.assign(g.memory.u8(::bmh::layout::ManagerCount), 0); + // ConfirmManager(0) posts PostSeasonNotice(0xff) immediately after the accepted + // new-career options dialog. The join path starts at a nonzero manager slot and + // must not repeat these three introduction messages. + if (adding || g.manager_teams.empty() || g.manager_teams.size() > 4) return; + post_text(g, -1, 1001); // CareerRuntimeField3 + post_text(g, -1, 1002); // CareerRuntimeField4 + post_text(g, -1, 1003); // CareerRuntimeField5 +} + +bool career_add_manager(ModernState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding, + GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + // Reject malformed requests before changing records or consuming either RNG. + if (!g.memory.has(::bmh::layout::ManagerCount) || m < 0 || m >= 4 || + g.memory.u8(::bmh::layout::ManagerCount) > 4 || m >= g.memory.u8(::bmh::layout::ManagerCount) || + size_t(m) >= g.manager_teams.size() || g.manager_records.size() < 5 * kRecord || + choice.team < 0 || choice.team >= first_foreign_cup() || size_t(choice.team) >= g.club_ids.size() || + choice.league < 0 || choice.league > 4 || choice.strength < 0 || choice.strength > 2 || + choice.portrait < 0 || choice.portrait > 11 || choice.name.size() > 24 || + g.tactics.size() < size_t(m + 1) * 0x840 || + g.manager_ratings.size() < size_t(m + 1) * 0x3c || + g.manager_results.size() < g.manager_teams.size() * 0x690 || + g.squad_slots.size() < total_squad_slots() || g.club_ids.size() < size_t(first_foreign_cup()) || + g.team_morale.size() < size_t(first_foreign_cup()) || g.team_flags.size() < size_t(first_foreign_cup()) || + g.club_heap_bc.size() < size_t(first_foreign_cup()) * 2 || g.club_heap_78.size() < size_t(first_foreign_cup()) * 2 || + g.club_heap_b8.size() < size_t(first_foreign_cup()) || g.position_history.size() < size_t(league_clubs()) * 0x1a || + (!g.club_table.empty() && g.club_table.size() < size_t(first_foreign_cup()) * 0x4a) || + g.player_bonus.size() < g.players.size() || g.player_cards.size() < g.players.size() || + !exe.contains(::bmh::layout::Career_CareerAddManager_ExecutableField) || !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField3 + 0x15 * 5) || + !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField + 4 * 0x17 + 0x15)) { + report.fail("invalid career manager choice or slot"); + return false; + } + for (int other = 0; other < m; ++other) + if (g.manager_teams[size_t(other)] == choice.team) { + report.fail("career manager club is already managed"); + return false; + } + for (size_t slot = 0; slot < transfer_list_slot(); ++slot) { + const uint16_t player = g.squad_slots[slot] & 0x0fff; + if (player != kEmptySlot && size_t(player) >= g.players.size()) { + report.fail("invalid career manager squad player"); + return false; + } + } + StaticMemory& mem = g.memory; + const size_t rec = size_t(m) * kRecord; + std::vector& r = g.manager_records; + for (size_t i = 0; i < 0x12; i++) r.at(rec + 0x1f6 + i) = 1; + for (size_t i = 0; i < 10; i++) r.at(rec + 0x8b6 + i) = 0xff; + r.at(rec + 0x1f6) = 0x40; + // the values of the dialog (ManagerScreen2) + for (size_t i = 0; i < 0x19; i++) r.at(rec + 0xa8 + i) = i < choice.name.size() ? uint8_t(choice.name[i]) : 0; + r.at(rec + 0x290) = uint8_t(choice.team), r.at(rec + 0x291) = uint8_t(choice.team >> 8); + r.at(rec + 0x221) = uint8_t(choice.portrait); + r.at(rec + 0x210) = uint8_t(choice.league); + g.manager_teams.at(size_t(m)) = int16_t(choice.team); + + int place = 1 + m; // the club's place in the first league + if (!adding && mem.u8(::bmh::layout::CareerDuration) <= 1) mem.set8(::bmh::layout::Career_CareerAddManager_RuntimeField, 0); + else place = m + 9; + while (reserved_place(g, place) || human_club(g, place) || (adding && european_club(g, place))) place++; // CareerAddManager4 + int league = r.at(rec + 0x210); // local_18 + const int team = int16_t(team_of(g, m)); + if (adding) remove_join_transfers(g, team); + if (team_league(team) != league) { + int other = place; + if (league != 0) { + const int first = league_first_team(league), last = first + 12; // CareerRuntimeField6 (league * 18 in DE) + do other = int16_t(game.range(first, last)); + while (human_club(g, other)); // ReservedPlace2 + // ReservedPlace: the next of 13 places that is neither reserved nor human + int c = other; + for (int k = 0; k < 13; k++) { + if (!reserved_place(g, c) && !human_club(g, c)) { + other = c; + break; + } + if (++c > last) c -= 13; + } + } + if (adding) remove_join_transfers(g, other); + modern::clubs_change_places(g, team, other); + set_club_strength(g, team, 0, rand); + place = 0; + } + if (league == 0 && place != 0) { + if (adding) remove_join_transfers(g, place); + modern::clubs_change_places(g, int16_t(team_of(g, m)), place); + } + set_club_strength(g, int16_t(team_of(g, m)), choice.strength + 1, rand); + + const int club = int16_t(team_of(g, m)); + if (adding && !remove_join_loans(g, club, report)) return false; + g.team_morale.at(size_t(club)) |= 0x80; + r.at(rec + 0x26f) = 0x32; + if (league > 2) league--; + modern::starting_sponsors(g, m); + r.at(rec + 0x26e) = uint8_t(std::max(20 - 2 * league, 14)); + build_stadium(g, exe, m, league, mem.u8(::bmh::layout::CareerDuration), rand); + if (league > 2) league = 2; + for (uint32_t i = 0; i < 3; i++) { + const uint32_t base = ::bmh::layout::Career_CareerAddManager_RuntimeField2 + uint32_t(m) * 0x24; + mem.set8(base + i, uint8_t(0x52 - league * 15)); + mem.set8(base + 3 + i, 6); + mem.set8(base + 6 + i, uint8_t(league)); + mem.set32(base + 0x18 + i * 4, 5000); + } + const SquadRange squad = squad_range(club); + r.at(rec + 0x288) = 0x16; + for (size_t i = 0; i < 0xd; i++) r.at(rec + 0xc5 + i) = 2; + for (size_t i = 0; i < 6; i++) r.at(rec + 0x8aa + 2 * i) = 0x26, r.at(rec + 0x8ab + 2 * i) = 0x02; + for (size_t i = 0; i < 0x3c; i++) g.manager_ratings.at(size_t(m) * 0x3c + i) = 100; + const int players = adding ? modern::squad_count(g, club, 2) : 20; + for (int i = 0; i < players; i++) { + const size_t slot = squad.first + size_t(i); + Player& p = g.players.at(size_t(g.squad_slots.at(slot) & 0x0fff)); + p.w364 &= ~(0x1fu << 21); + p.w364 |= uint32_t(rand.range(4, 9)) << 21; + modern::new_board_entry(g, m, i, int(slot), rand); + g.tactics.at(size_t(m) * 0x840 + size_t(i) * 0x58 + 0xd) = 100; + } + // Deviation from the original: a new career fills exactly 20 board rows (local_28 = 0x14), + // but new_career_players runs before the dialog and may already have moved a free agent + // into the chosen club (transfer_bid, "straight to the club"). That 21st player had no + // board row - no salary, and team_rating divides by his base pay (the original crashes + // once he plays). The remaining occupied rows get their entry the same way; with the + // usual 20 players nothing changes and no random number is drawn. + if (!adding) + for (size_t i = 20; i < squad.count && i < 24; i++) { + const size_t slot = squad.first + i; + const int id = g.squad_slots.at(slot) & 0x0fff; + if (id == 0x0fff) continue; + Player& p = g.players.at(size_t(id)); + p.w364 &= ~(0x1fu << 21); + p.w364 |= uint32_t(rand.range(4, 9)) << 21; + modern::new_board_entry(g, m, int(i), int(slot), rand); + g.tactics.at(size_t(m) * 0x840 + i * 0x58 + 0xd) = 100; + } + for (size_t i = 0; i < 0x690; i++) g.manager_results.at(size_t(m) * 0x690 + i) = 0xff; + const uint8_t level = mem.u8(::bmh::layout::Difficulty); + const uint32_t money = level == 0 ? 50000000u : 4000000u - level * 200000u; + put32(r, rec + 0x314, money); + put32(r, rec + 0x324, money); + r.at(rec + 0x219) = r.at(rec + 0x218) = 0xf; + put32(r, rec + 0x31c, uint32_t(400000 - league * 100000)); + put32(r, rec + 0x310, 1); + auto_lineup(g, club, 100); + return !report.unsupported; +} + +void career_managers_end(ModernState& g, bool adding) { + g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 0); + if (!adding) + for (uint32_t i = 0; i < 12; i++) g.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2, 0xfff); +} + +} // namespace bmh::modern + +namespace bmh::modern { + +// The English counterpart of CompetitionPointers: the Football Limited GermanRoundTable. The cup table +// (translated to CupTable, launch/fltd.hpp) is the English one; its entries 0-24 have the +// same roles as in German, so their arrays are the German ones (same sizes). Different: +// entry 0 (FA Cup qualifying stage) and the English-only competitions - entry 28 (FA Cup +// proper), 25-27 (League Cup) and 35 - which use memory blocks at their English addresses +// (english_competition_blocks); there are no indoor tournaments and no Masters. +namespace { + +// English round-string pointer tables -> the German ones the engine knows (cup.cpp) +uint32_t german_round_table(uint32_t en) { + switch (en) { + case ::bmh::layout::Career_GermanRoundTable_ExecutableField2: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField; // 4 teams + case ::bmh::layout::Career_GermanRoundTable_ExecutableField3: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField2; // 6 + case ::bmh::layout::Career_GermanRoundTable_ExecutableField: return ::bmh::layout::CareerSession_RuntimeError_ExecutableField2; // 20 + case ::bmh::layout::Career_GermanRoundTable_ExecutableField4: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField3; // 12 + default: return en; + } +} + +void competition_pointers_english(StaticMemory& mem, const LeImage& exe) { + auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; }; + modern::english_competition_blocks(mem); + for (uint32_t k = 1; k < 0xf; k++) { + uint32_t b = k; + if (k > 9) b -= 9; + if (k > 0xc) b -= 3; + mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc); + } + uint32_t k = 7; + for (uint32_t i = 0; i < 8; i += 2, k++) { + if (k == 10) k = 0xc; + mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2); + } + const std::pair single[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13}, + {::bmh::layout::CupTable, kEnglishFaQualifyingField}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, kEnglishFaResults}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}}; + for (const auto& [at, to] : single) mem.set_pointer(at, to); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10); + for (uint32_t i = 0; i < 4; i++) { + const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i)); + mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30); + mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20); + mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + } + mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc); + const std::pair more[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays}, + // the English-only cup entry table (entries 25-28 and 35) + {entry(28), ::bmh::layout::EnglishFaCupProperField}, {entry(28) + 0xc, ::bmh::layout::EnglishFaCupStageResults}, // FA Cup proper + {entry(25), ::bmh::layout::EnglishLeagueCupFirstRoundField}, {entry(25) + 0xc, ::bmh::layout::EnglishLeagueCupFirstRoundResults}, // League Cup + {entry(26), ::bmh::layout::EnglishLeagueCupQuarterFinalField}, {entry(26) + 0xc, ::bmh::layout::EnglishLeagueCupQuarterFinalResults}, {entry(26) + 0x10, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults}, + {entry(27), ::bmh::layout::EnglishLeagueCupSemiFinalField}, {entry(27) + 0xc, ::bmh::layout::EnglishLeagueCupSemiFinalResults}, + {entry(35) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField}, {entry(35), ::bmh::layout::EnglishAdditionalCupField}, {entry(35) + 0xc, ::bmh::layout::EnglishAdditionalCupResults}}; + for (const auto& [at, to] : more) mem.set_pointer(at, to); + // round tables the English table holds itself (static pointers to English strings) + for (uint32_t e = 0; e < 0x24; e++) { + const uint32_t at = entry(e) + 8; + const uint32_t p = mem.u32(at); + if (p >= ::bmh::layout::EnDataStart && p < ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField) mem.set_pointer(at, german_round_table(p)); + } +} + +} // namespace + +void english_competition_blocks(StaticMemory& mem) { + for (const auto& [at, size] : kEnglishCompetitionBlocks) + if (!mem.has(at)) mem.add_block(at, size); +} + +void competition_pointers(StaticMemory& mem, const LeImage& exe) { + if (kEnglishCompetitions) { + competition_pointers_english(mem, exe); + return; + } + auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; }; + // the cups of the leagues 1..14 (entries 1..14) + for (uint32_t k = 1; k < 0xf; k++) { + uint32_t b = k; + if (k > 9) b -= 9; + if (k > 0xc) b -= 3; + mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc); + } + // entries 7, 8, 9, 12 (Career_CompetitionPointersEnglish_RuntimeField10 pairs) + uint32_t k = 7; + for (uint32_t i = 0; i < 8; i += 2, k++) { + if (k == 10) k = 0xc; + mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2); + } + const std::pair single[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13}, {::bmh::layout::CupTable, ::bmh::layout::Field}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, ::bmh::layout::Career_CompetitionPointers_ExecutableField}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}}; + for (const auto& [at, to] : single) mem.set_pointer(at, to); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10); + for (uint32_t i = 0; i < 4; i++) { + const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i)); + mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30); + mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20); + mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + } + mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc); + const std::pair more[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays}}; + for (const auto& [at, to] : more) mem.set_pointer(at, to); + // the indoor tournaments and the Masters (entries 25..29) + for (uint32_t i = 0; i < 5; i++) { + const uint32_t e = entry(0x19 + i); + mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(e + 0xc, ::bmh::layout::MatchdayGroupWorkspace + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField4 + i)) * 2); + mem.set_pointer(e, ::bmh::layout::Teams + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField5 + i)) * 2); + } + mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField, ::bmh::layout::Teams); + mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField3, ::bmh::layout::MatchdayGroupWorkspace); +} + +} // namespace bmh::modern diff --git a/src/modern/game/career.hpp b/src/modern/game/career.hpp new file mode 100644 index 0000000..31e9261 --- /dev/null +++ b/src/modern/game/career.hpp @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +#include "game/career.hpp" +// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. +// The start of a new career (BMH.exe V2.24 + supported rule profile patch). +// +// The original starts every career at program start: CareerFirstSteps2 loads the data files +// (TEXTD.BLK, M3.MEN, M3.DAT, M3D.MAN), gives every player new values and then calls +// InitializeCareer, which sets up shares, funds, club moods, ages and skills, shows the +// options and manager dialogs (SetupScreen2) inside ConfirmManager and finally prepares the +// first season. Loading a savegame from the options screen replaces all of that. +// +// The game generator starts at 0 (CareerSession_Save_RuntimeField is not initialised), the Watcom generator +// at the clock value of srand() - recordings capture it. + +#include +#include +#include + +#include "formats/m3d.hpp" +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. +// GeneratePlayer with the supported rule profile patch GeneratePlayer2: new values for player `id` around +// `level` (low 12 bits of `level_flags`; 0x1000 = leave the age at 0, 0x2000 = exactly +// the level instead of +-10 %): +// - w35c bits 21-26: G(0, 7) << 3 | G(0, 7) for field players, 0x18 for goalkeepers +// (two game draws, high part first); +// - condition and technique G(level - level / 10, level + level / 10), each cut to +// 10..99; form G(35, 65); bits 27-31 cleared; +// - w368: skills W(0, 0x3fff), bits 18-23 (cards) cleared; +// - w364: age bits cleared, then (without 0x1000) G(2, 5) = 18..21 years. +void generate_player(ModernState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand); + +// The part of CareerFirstSteps2 after loading M3D.MAN: the 54 players of the extra slots +// (CareerSession_DataDirectory_RuntimeField4 ..) get W(20 or 70, 90) as level (the first 22 from 20), then the players +// of every league club get the level of its place in the database order of its league, +// from the league's maximum (first club) down towards its minimum (LeagueStrengthRanges pairs, +// club counts LeagueSizes), keeping the age at 0 for InitializeCareer. +void startup_players(ModernState& g, GameRandom& game, WatcomRandom& rand); + +// The squad list as CareerFirstSteps2 leaves it: all slots 0xfff, the database list read +// over them and its tail (from slot CareerRuntimeField + 40) moved up to slot CareerRuntimeField2 +// (memmove; the four slots before keep their values). +std::vector startup_squad_list(const Database& db); + +} // namespace bmh::modern + +namespace bmh::modern { + + +// The memory of the original after loading the data files in CareerFirstSteps2, as a ModernState +// (built like a savegame: every saved block from the program's data object - zero where +// it is uninitialised - with the data of M3.MEN, M3.DAT and M3D.MAN read over it): +// manager order 0..3, option byte 0 of each manager 1, active manager 4, M3.MEN five +// times (Desktops), the first 0x160 bytes of M3.DAT four times (the other three +// parts of the file are overwritten), the nationality of the last 32 players from +// CareerRuntimeField7. The player values are those of the database; startup_players follows. +ModernState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat); + +// CompetitionPointers (part of startup_state): the pointers of the competition table CupTable +// (36 entries of 0x28 bytes: +0 the teams, +8 the rounds, +0xc the results) to the tables of +// the leagues, cups and tournaments. +void competition_pointers(StaticMemory& mem, const LeImage& exe); + +// The memory of the English-only competitions (Football Limited, kEnglishCompetitions): +// blocks at their English addresses, which no German address uses. FA Cup results (67 +// matches) and fields (68 clubs: the 20 Premier League clubs, the 48 of the qualifying +// stage, the proper rounds), the League Cup (44 clubs, three entries) and entry 35. +constexpr uint32_t kEnglishFaResults = ::bmh::layout::EnglishFaCupResults; // 0x86 bytes, entry 0 +0x0c +constexpr uint32_t kEnglishFaField = ::bmh::layout::EnglishFaCupField; // 68 clubs: 20 + kEnglishFaQualifyingField +constexpr uint32_t kEnglishFaQualifyingField = ::bmh::layout::EnglishFaCupQualifyingField; // the 48 of the qualifying stage (entry 0) +constexpr uint32_t kEnglishLeagueCupField = ::bmh::layout::EnglishLeagueCupField; // 44 clubs: 20 + 24 at layout field (entry 25) +constexpr std::pair kEnglishCompetitionBlocks[] = { + {::bmh::layout::EnglishFaCupResults, 0x1ba}, // FA Cup: results EnglishFaCupResults, stage results EnglishFaCupStageResults, field EnglishFaCupField, proper EnglishFaCupProperField + {::bmh::layout::EnglishLeagueCupField, 0x136}, // League Cup: fields EnglishLeagueCupField/EnglishLeagueCupFirstRoundField/EnglishLeagueCupQuarterFinalField/EnglishLeagueCupSemiFinalField, results EnglishLeagueCupFirstRoundResults/EnglishLeagueCupQuarterFinalResults/EnglishLeagueCupSemiFinalResults/EnglishLeagueCupQuarterFinalOtherLegResults + {::bmh::layout::EnglishAdditionalCupResults, 0x48}, // entry 35: results EnglishAdditionalCupResults, field EnglishAdditionalCupField +}; +void english_competition_blocks(StaticMemory& mem); + +} // namespace bmh::modern + +namespace bmh::modern { + +// InitializeCareer up to the options dialog (SetupScreen2, called first in ConfirmManager(0)): +// - funds (price (1 << k) * 100 000) and shares (value k * 2000 + 10 000, price +// k * 20 + 100); +// - stir_random; G(0, 1) chooses which of the two computer manager names (Career_NewCareerMarketsAndMoods_ExecutableField / +// aeafc) the records 0 and 1 get, records 2 and 3 get Career_NewCareerMarketsAndMoods_ExecutableField3 / Career_NewCareerMarketsAndMoods_ExecutableField4 (needs +// g.texts; skipped without); +// - 30 days of share prices (stock_market); +// - Titles (900 bytes) 0xff, Career_NewCareerMarketsAndMoods_RuntimeField2 = 1, 2, 4, 8, the transfer list's 44 +// entries empty (player 0xfff); +// - club moods (reset_club_moods, career mode); +// - every club player (squad slots 0 .. CareerRuntimeField) gets an age W(4, 16) and new +// skills W(0, 0x3fff); +// - the 54 extra players leave for the free agents (release_player, MonthChange). +// Returns false if a step is not supported (report). +bool new_career_before_dialog(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); +// Its two parts: up to the club moods, and the ages, skills and extra players. +void new_career_markets_and_moods(ModernState& g, GameRandom& game, WatcomRandom& rand); +bool new_career_players(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh::modern + +namespace bmh::modern { + +// A manager as confirmed in his dialog (ManagerScreen2; the UI's ManagerChoice): the dialog +// writes name (record +0xa8), club (+0x290), start league 0..4 (+0x210) and portrait +// (+0x221) into the record and returns the strength 0 (lower third) .. 2 (upper third). + +// ConfirmManager before the first dialog: manager slot 4 (the national team's) gets the +// training plan 2 and 1 000 000 money. +void career_managers_begin(ModernState& g, bool adding = false); + +// StartingSponsors initializes the three sponsor contracts for mode I, or for a +// one-year career before season day 0. The date check uses ModernState.date, +// because the serialized CalendarDay mirror can be stale during startup/reset. +void starting_sponsors(ModernState& g, int manager); + +// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. +// The body of ConfirmManager's loop for manager `m` (`adding` = a manager joins a running +// game, param_1 != 0): the record is prepared and the dialog's values entered, then +// - the club moves to its place: in a league other than the chosen start league it +// changes places with a club of that league (G(first, first + 12), supported rule profile ReservedPlace2 +// / ReservedPlace skip clubs of humans and reserved places), which gets new values +// (CareerAddManager2(club, 0)); in the first league with a club place m + 1 (m + 9 when +// adding; supported rule profile CareerAddManager4 skips reserved and human places); +// - the club's players get condition and technique around the chosen strength +// (CareerAddManager2, W(level - 6, level + 6)); +// - record values: morale flag, board patience, stadium (CareerAddManager3, StartingSponsors), +// training plan, ratings, money (4 000 000 - level * 200 000; 50 000 000 at level 0), +// credit line, the first 20 players (or the whole squad when adding) on the tactics +// board with a new age W(4, 9), and an automatic line-up. +// The optional file of CareerAddManager (bonus codes) is not read. Needs the program image +// for its tables (Career_BuildStadium_RuntimeField4, Career_BuildStadium_RuntimeField, Career_BuildStadium_RuntimeField2). +bool career_add_manager(ModernState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding, + GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ConfirmManager after the loop: clear CareerSession_FormatError_RuntimeField6; only a new career empties the twelve +// human loan entries Career_CareerManagersEnd_RuntimeField. Joining preserves unrelated entries. +void career_managers_end(ModernState& g, bool adding); + +} // namespace bmh::modern diff --git a/src/modern/game/club_info.cpp b/src/modern/game/club_info.cpp new file mode 100644 index 0000000..2546760 --- /dev/null +++ b/src/modern/game/club_info.cpp @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/club_info.hpp" +#include +namespace bmh::modern { +ClubInfoEntry prepare_club_info_entry(ModernState& g, int team) { + if (team < 0 || (team >= league_clubs() && team != no_team())) + throw std::invalid_argument("club info: team has no squad"); + const SquadRange range = squad_range(team); + if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first) + throw std::invalid_argument("club info: truncated squad range"); + size_t occupied = 0; + for (size_t row = 0; row < range.count; ++row) { + const int id = g.squad_slots[range.first + row] & 0x0fff; + if (id == 0x0fff) continue; + if (size_t(id) >= g.players.size()) + throw std::invalid_argument("club info: invalid player ID"); + ++occupied; + } + // Allocate the owned pre-cleanup drawing rows before the first engine write. + ClubInfoEntry entry; + entry.displayed_slots.assign(g.squad_slots.begin() + range.first, + g.squad_slots.begin() + range.first + range.count); + // SquadCount(team,2) counts occupied IDs over the complete range. PrepareLineupEntry + // scans that count-sized prefix, even if the supplied map is sparse. + int last = int(occupied) - 1; + while (last >= 0 && (g.squad_slots[range.first + size_t(last)] & 0xc000) == 0) --last; + for (int row = 0; row <= last && row < 17; ++row) { + auto& slot = g.squad_slots[range.first + size_t(row)]; + slot = uint16_t((slot & 0x3fff) | (row < 11 ? 0x8000 : 0x4000)); + } + entry.displayed_slots.assign(g.squad_slots.begin() + range.first, + g.squad_slots.begin() + range.first + range.count); + // PrepareClubInfoEntry clears bits13..15 for injured players over the entire range. + // Empty slots are a dummy ID in Original; preserve the sentinel explicitly. + for (size_t row = 0; row < range.count; ++row) { + auto& slot = g.squad_slots[range.first + row]; + const int id = slot & 0x0fff; + if (id != 0x0fff && ((g.players[size_t(id)].w364 >> 16) & 0x1f) != 0) + slot &= 0x1fff; + } + return entry; +} +uint8_t set_club_info_category(ModernState& g, int team, int requested) { + constexpr size_t scan_count = 0x147; + if (team < 0 || size_t(team) >= g.team_morale.size() || + g.team_morale.size() < scan_count || requested < 0 || requested > 2) + throw std::invalid_argument("club info: invalid category request or club table"); + const size_t manager_count = g.memory.has(::bmh::layout::ManagerCount) + ? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size(); + if (manager_count > 4 || manager_count > g.manager_teams.size()) + throw std::invalid_argument("club info: truncated manager teams"); + const bool national = !g.manager_teams.empty() && g.manager_teams.front() == no_team(); + constexpr size_t national_club = 4 * 0xb0c + 0x290; + if (national && g.manager_records.size() < national_club + 2) + throw std::invalid_argument("club info: truncated national manager record"); + // FindManagerForClub matches the first ManagerCount teams, irrespective of manager name, + // then the fifth record when the first manager is the national coach. + const auto human = [&](int club) { + for (size_t m = 0; m < manager_count; ++m) + if (g.manager_teams[m] == club) return true; + return national && (g.manager_records[national_club] | + uint16_t(g.manager_records[national_club + 1]) << 8) == club; + }; + uint8_t category = uint8_t(requested); + uint8_t seen = 0; + if (category == 2) { + for (size_t club = 0; club < scan_count; ++club) { + if ((g.team_morale[club] >> 6) != 2) continue; + ++seen; + if (seen != 4 || category != 2) continue; + if (!human(team)) category = 0; + else { + // Source local10 stays0: every search restarts at the first club. + for (size_t other = 0; other < scan_count; ++other) { + if ((g.team_morale[other] >> 6) == 2 && !human(int(other))) { + g.team_morale[other] = uint8_t((g.team_morale[other] & 0x3f) | 0x40); + --seen; + break; + } + } + } + } + } + g.team_morale[size_t(team)] = uint8_t((g.team_morale[size_t(team)] & 0x3f) | (category << 6)); + return category; +} + +} diff --git a/src/modern/game/club_info.hpp b/src/modern/game/club_info.hpp new file mode 100644 index 0000000..269a06a --- /dev/null +++ b/src/modern/game/club_info.hpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/club_info.hpp" +#include "modern/game/modern_state.hpp" +namespace bmh::modern { +// ClubInfoFromGame -> LineupScreen(..., param11=1): PrepareLineupEntry before +// drawing, PrepareClubInfoEntry after drawing. No player selection or RNG. +// Applies to computer and human domestic squads and the national squad. +// Invalid team/range/player IDs throw before any mutation. +ClubInfoEntry prepare_club_info_entry(ModernState& g, int team); +// ClubInfoFromGame numeric icon -> SetClubInfoCategory. Returns the applied raw +// category (0..2); may demote another computer club's category2 to1. +uint8_t set_club_info_category(ModernState& g, int team, int requested); +} diff --git a/src/modern/game/club_player_detail.cpp b/src/modern/game/club_player_detail.cpp new file mode 100644 index 0000000..be34d5a --- /dev/null +++ b/src/modern/game/club_player_detail.cpp @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/club_player_detail.hpp" + +#include +#include + +#include "modern/game/matchday.hpp" +#include "modern/game/month.hpp" +#include "modern/game/national.hpp" +#include "game/lineup.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { +namespace { +constexpr size_t kRecord = 0xb0c, kBoard = 0x840, kBoardRow = 0x58; + +uint16_t record_word(const ModernState& g, size_t manager, size_t offset) { + const size_t at = manager * kRecord + offset; + if (at + 2 > g.manager_records.size()) throw std::invalid_argument("player detail: truncated manager record"); + return uint16_t(g.manager_records[at] | uint16_t(g.manager_records[at + 1]) << 8); +} + +int source_manager(const ModernState& g, int club) { + const size_t count = g.memory.has(::bmh::layout::ManagerCount) ? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size(); + if (count > 4 || count > g.manager_teams.size()) throw std::invalid_argument("player detail: invalid manager count"); + for (size_t m = 0; m < count; ++m) if (g.manager_teams[m] == club) return int(m); + if (count && g.manager_teams[0] == no_team() && record_word(g, 4, 0x290) == club) return 4; + return -1; +} + +int club_of_slot(int slot) { + if (slot < 0) return -1; + if (slot < 90 * 24) return slot / 24; + if (slot < 90 * 24 + 48 * 16) return (slot - 90 * 8) / 16; + if (slot >= pool_end_slot() && slot < pool_end_slot() + 24) return no_team(); + return -1; +} + +std::array board_copy(const ModernState& g, int manager, int row) { + const size_t at = size_t(manager) * kBoard + size_t(row) * kBoardRow; + if (at + kBoardRow > g.tactics.size()) throw std::invalid_argument("player detail: truncated manager board"); + std::array out{}; + std::copy_n(g.tactics.begin() + static_cast(at), out.size(), out.begin()); + return out; +} +} // namespace + +ClubPlayerDetailContext club_player_detail_context(const ModernState& g, const ClubPlayerDetailSelection& s) { + if ((s.origin != ClubPlayerDetailOrigin::squad && s.origin != ClubPlayerDetailOrigin::market_pool) || + s.player_id < 0 || size_t(s.player_id) >= g.players.size() || + size_t(s.player_id) >= g.player_cards.size() || size_t(s.player_id) >= g.player_bonus.size()) + throw std::invalid_argument("player detail: invalid player identity"); + ClubPlayerDetailContext out; + out.selection = s; + out.active_manager = g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0; + if (out.active_manager < 0 || size_t(out.active_manager) >= g.manager_teams.size()) + throw std::invalid_argument("player detail: invalid active manager"); + if (s.origin == ClubPlayerDetailOrigin::market_pool) { + if (s.runtime_team != -1 || s.physical_row != -1 || s.human_loan_index != -1 || + s.market_pool_slot < int(transfer_list_slot()) || + s.market_pool_slot >= int(transfer_list_slot()) + kClubPlayerDetailMarketPoolCount || + s.rendered_row < 0 || s.rendered_row >= kClubPlayerDetailMarketPoolCount || + size_t(s.market_pool_slot) >= g.squad_slots.size()) + throw std::invalid_argument("player detail: invalid transfer-market slot"); + out.source_slot = s.market_pool_slot; + out.displayed_slot = g.squad_slots[size_t(out.source_slot)]; + if (out.displayed_slot == kEmptySlot || (out.displayed_slot & 0x0fff) != s.player_id) + throw std::invalid_argument("player detail: stale transfer-market identity"); + out.market_pool = true; + out.source_manager = -1; + out.primary_club = -1; + } else { + if (s.rendered_row < 0 || s.rendered_row >= 24 || s.runtime_team < 0 || + (s.runtime_team >= league_clubs() && s.runtime_team != no_team())) + throw std::invalid_argument("player detail: invalid runtime club"); + const auto range = squad_range(s.runtime_team); + if (range.first + range.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated squad"); + out.source_manager = source_manager(g, s.runtime_team); + out.primary_club = s.runtime_team; + } + if (s.origin == ClubPlayerDetailOrigin::market_pool) { + // The validated pool identity is already loaded. National resolution + // below may select a real squad copy; offers never imply a board. + } else if (s.human_loan_index >= 0) { + const auto range = squad_range(s.runtime_team); + if (s.human_loan_index >= 12 || s.physical_row != -1 || s.runtime_team == no_team() || out.source_manager < 0) + throw std::invalid_argument("player detail: invalid human loan row"); + const uint32_t loan = uint32_t(s.human_loan_index); + const uint32_t player_at = ::bmh::layout::Career_CareerManagersEnd_RuntimeField + loan * 2, owner_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField2 + loan, board_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField + loan * kBoardRow; + if (!g.memory.has(player_at + 1) || !g.memory.has(owner_at) || !g.memory.has(board_at + kBoardRow - 1) || + g.memory.u16(player_at) != s.player_id || g.memory.u8(owner_at) != out.source_manager) + throw std::invalid_argument("player detail: stale human loan identity"); + out.human_loan = true; + out.source_slot = int(range.first) + s.rendered_row; + out.displayed_slot = uint16_t(s.player_id); + out.board.emplace(); + for (size_t i = 0; i < kBoardRow; ++i) (*out.board)[i] = g.memory.u8(board_at + uint32_t(i)); + } else { + const auto range = squad_range(s.runtime_team); + if (s.human_loan_index != -1 || s.physical_row < 0 || size_t(s.physical_row) >= range.count) + throw std::invalid_argument("player detail: invalid physical row"); + out.source_slot = int(range.first) + s.physical_row; + out.displayed_slot = g.squad_slots[size_t(out.source_slot)]; + if ((out.displayed_slot & 0x0fff) != s.player_id) throw std::invalid_argument("player detail: stale physical identity"); + } + if (!out.human_loan) { + if (g.manager_teams[size_t(out.active_manager)] == no_team()) { + const auto national = squad_range(no_team()); + if (national.first + national.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated national squad"); + bool selected = false; + for (size_t row = 0; row < national.count; ++row) + if ((g.squad_slots[national.first + row] & 0x0fff) == s.player_id) selected = true; + out.national_mode = selected ? 2 : 1; + // ClubPlayerDetailFromGame remaps BOTH modes to the first matching slot below + // LargeSquadClubCount, including pool slots, before resolving club/owner/board. + size_t slot = 0; + while (slot < national.first && (g.squad_slots[slot] & 0x0fff) != s.player_id) ++slot; + if (slot == national.first) throw std::invalid_argument("player detail: national player has no source slot before national squad"); + out.source_slot = int(slot); + out.primary_club = club_of_slot(out.source_slot); + out.secondary_club = selected ? no_team() : -1; + out.displayed_slot = g.squad_slots[slot]; + out.source_manager = out.primary_club < 0 ? -1 : source_manager(g, out.primary_club); + } + if (out.national_mode != 0 && out.primary_club == int(record_word(g, 4, 0x290)) && g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3)) { + const uint8_t owner = g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3); // literal SquadRange override + out.source_manager = owner == 0xff ? -1 : owner; + } + if (out.source_manager >= 0) { + const auto owner_range = squad_range(out.primary_club); + const int row = out.source_slot - int(owner_range.first); + if (row < 0 || size_t(row) >= owner_range.count) throw std::invalid_argument("player detail: board row outside owner squad"); + out.board = board_copy(g, out.source_manager, row); + } + } + for (int loan = 0; loan < 200; ++loan) { + const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan) * 4; + if (!g.memory.has(at + 3)) continue; + const uint32_t value = g.memory.u32(at); + if (value == 0 || (value & 0x0fff) != uint32_t(s.player_id)) continue; + out.loan_record = loan; + out.loan_duration = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) ? g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) : 0; + if (out.human_loan || out.national_mode == 0) { + out.primary_club = int((value >> 12) & 0x3ff); + out.secondary_club = int((value >> 22) & 0x3ff); + } + break; + } + if (out.human_loan && out.loan_record < 0) throw std::invalid_argument("player detail: missing packed human loan record"); + out.attributes = g.players[size_t(s.player_id)]; + out.cards = g.player_cards[size_t(s.player_id)]; + out.bonus = g.player_bonus[size_t(s.player_id)]; + out.original_name = g.player_name(s.player_id); + const uint8_t national_override = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) ? uint8_t(g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) & 10) : 0; + const bool national_label = !out.human_loan && out.national_mode != 0 && national_override == 0 && + out.attributes.nationality() + ((out.bonus & 0x80) >> 2) == 0; + for (int offer = 0; !national_label && offer < 4; ++offer) { + const uint32_t at = ::bmh::layout::OfferSlots + uint32_t(offer) * 4; + if (!g.memory.has(at + 3)) continue; + const uint32_t value = g.memory.u32(at); + if ((out.source_manager < 0 || int(value & 31) == out.source_manager) && + int((value >> 10) & 0x0fff) == s.player_id) { out.active_offer = offer; break; } + } + // ClubPlayerDetail_InvalidArgument_RuntimeField2/nationality select the label and the ResolvePendingOffer fallback, not the + // ClubPlayerDetailRedraw dispatch: any existing action remains national in modes1/2. + out.national_action_available = !out.human_loan && out.national_mode != 0 && + (national_label || out.active_offer >= 0); + return out; +} + +ClubPlayerDetailRedraw club_player_detail_redraw(const ModernState& g, const ClubPlayerDetailSelection& selection, + const LeImage& original, GameRandom& game, WatcomRandom& rand, + bool portrait_available) { + ClubPlayerDetailRedraw out; + out.context = modern::club_player_detail_context(g, selection); + std::array feature_count{}; + for (size_t i = 0; i < feature_count.size(); ++i) { + feature_count[i] = original.u8(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + uint32_t(i)); + if (feature_count[i] == 0) throw std::invalid_argument("player detail: empty Original portrait feature range"); + } + const uint32_t named_players = original.u32(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField); + out.portrait_available = portrait_available; + if (portrait_available) { + uint32_t seed = 0x14344; + if (uint32_t(selection.player_id) < named_players) + for (size_t i = 0; i < out.context.original_name.size(); ++i) + seed += uint32_t(int32_t(int8_t(out.context.original_name[i]))) * uint32_t(i) * 10; + game.set_seed(int32_t(seed)); + game.range(0, 100); + out.portrait_base = uint8_t(game.range(0, 3)); + for (size_t i = 0; i < out.portrait_features.size(); ++i) + out.portrait_features[i] = uint8_t(game.range(0, feature_count[i] - 1)); + const uint64_t before = game.calls(); + modern::stir_random(game, rand); + out.portrait_burn_count = uint16_t(game.calls() - before); + } + if (!out.context.human_loan) { + uint32_t value = 0, salary = 0; + modern::market_value(g, out.context.source_slot, 0, 100, value, salary, 0, 0, rand); + out.market_value = ((value + (value >> 2)) / 10000) * 10000; + } + return out; +} + +bool club_player_detail_national_action(ModernState& g, const ClubPlayerDetailSelection& selection, + WatcomRandom& rand, MinuteReport& report) { + const auto context = modern::club_player_detail_context(g, selection); + if (!context.national_action_available) + throw std::invalid_argument("player detail: national action is not offered by Source"); + const auto national = squad_range(no_team()); + bool applied = true; + if (context.national_mode == 1) + applied = modern::add_to_squad(g, context.active_manager, context.source_slot, int(national.first), rand) >= 0; + else if (!g.memory.has(::bmh::layout::MatchEventsDisabled) || g.memory.u8(::bmh::layout::MatchEventsDisabled) == 0) + applied = modern::remove_from_seller(g, no_team(), selection.player_id, report); + auto_lineup(g, no_team(), 0xe4); // ClubPlayerDetailFromGame follows either action with this call. + return applied; +} +} // namespace bmh::modern diff --git a/src/modern/game/club_player_detail.hpp b/src/modern/game/club_player_detail.hpp new file mode 100644 index 0000000..376bd01 --- /dev/null +++ b/src/modern/game/club_player_detail.hpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/club_player_detail.hpp" + +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + + +// The list owns all row identities. A loan row has physical_row==-1 and its +// explicit Source Career_CareerManagersEnd_RuntimeField index. rendered_row is the visible list index, which +// may differ from a filtered/sorted market-pool entry. + + +// OpenTransferEditor passes actual slots CareerRuntimeField + entry (0..39) for ordinary +// transfer-market pool cards. It never turns the entry into a squad row. +constexpr int kClubPlayerDetailMarketPoolCount = 40; + +// Resolves runtime club, explicit row and Source loan/national ownership without +// changing ModernState or either random generator. Invalid/stale identities throw. +ClubPlayerDetailContext club_player_detail_context(const ModernState&, + const ClubPlayerDetailSelection&); + + +// One actual ClubPlayerDetailFromGame card rebuild: Copy2/21213 portrait draws, followed +// by422ac/42307/PlayerCardMarketValue market valuation. Pure renderer calls consume this owned +// result repeatedly and never draw RNG. The caller passes Source heap gate. +ClubPlayerDetailRedraw club_player_detail_redraw(const ModernState&, + const ClubPlayerDetailSelection&, + const LeImage& original, + GameRandom&, WatcomRandom&, + bool portrait_available = true); + +// ClubInfoFromGame temporarily uses (bbcde!=2), then restores its caller's value. +constexpr uint8_t club_player_detail_input_mode(uint8_t prior) { return prior != 2; } + +// The actual Source nomination/remove button. Returns false if the national +// squad is full; the Source lineup refresh still follows the attempted add. +bool club_player_detail_national_action(ModernState&, const ClubPlayerDetailSelection&, + WatcomRandom&, MinuteReport&); + +} // namespace bmh::modern diff --git a/src/modern/game/cup.cpp b/src/modern/game/cup.cpp new file mode 100644 index 0000000..7f88d56 --- /dev/null +++ b/src/modern/game/cup.cpp @@ -0,0 +1,783 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/cup.hpp" + +#include +#include +#include +#include +#include + +#include "modern/game/driver.hpp" +#include "game/lineup.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" + +namespace bmh::modern { + +// After the fifth indoor tournament (the end of AdvanceCup for competition 0xb): the +// field of the Masters. +// MastersQualification2: the holders of the three titles of last season (Cup_AdvanceCup_RuntimeField6[0..2], +// u16 club ids) qualify directly, each once (list Cup_MastersQualification_RuntimeField, count CupRuntimeField); +// they head the team list (Teams). +// IndoorStandingsFromGame(0): the clubs 0-39 are sorted by their Masters points (Cup_AdvanceCup_ExecutableField, +// Games descending); IndoorTournamentDraw only resets the tournament (no draw while +// CupRuntimeField != 0); the best clubs not qualified yet fill the list up to eight, which +// is shuffled (PrepareEvent, one game draw per club). The strength class Cup_AdvanceCup_RuntimeField3 +// stays that of the last tournament. +// The test "qualified yet" (MastersQualification) scans Cup_MastersQualification_RuntimeField[0 .. CupRuntimeField), but +// CupRuntimeField also counts the clubs filled in from the points list, which never enter +// Cup_MastersQualification_RuntimeField: the scan runs over the stale entries 2 and 3 (0 unless an earlier Masters +// had three direct qualifiers) and from entry 4 into the invitation counters that follow +// (MatchdaySetup_IndoorTournamentDraw_RuntimeField, u16 per club). A club whose id equals one of those values (team 0 with a +// 0 there, small ids with an invitation count) is skipped although it has the points. +// The list is not in the savegame; the replay keeps it in memory, starting at 0. +void masters_qualification(ModernState& g, GameRandom& game) { + StaticMemory& mem = g.memory; + constexpr uint32_t kTeams = ::bmh::layout::Teams, kDirect = ::bmh::layout::Cup_MastersQualification_RuntimeField; + if (!mem.has(kDirect)) mem.add_block(kDirect, 8); + // MastersQualification: whether club t is in Cup_MastersQualification_RuntimeField[0 .. count) + auto listed = [&](uint16_t t, size_t count) { + for (size_t k = 0; k < count; k++) + if (mem.u16(kDirect + uint32_t(k) * 2) == t) return true; + return false; + }; + size_t count = 0; // CupRuntimeField + for (uint32_t k = 0; k < 3; k++) { + const uint16_t t = mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6 + k * 2); + if (k == 0 || !listed(t, count)) mem.set16(kDirect + uint32_t(count++) * 2, t); + } + for (size_t k = 0; k < count; k++) mem.set16(kTeams + uint32_t(k) * 2, mem.u16(kDirect + uint32_t(k) * 2)); + int16_t order[0x28]; + uint32_t points[0x28]; + for (int i = 0; i < 0x28; i++) order[i] = int16_t(i), points[i] = mem.u16(::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(i) * 2); + quicksort_by_key(order, points, 0x28); + modern::indoor_tournament_reset(g); + for (int i = 0; count < 8; i++) { + const uint16_t t = uint16_t(order[i]); + if (!listed(t, count)) mem.set16(kTeams + uint32_t(count++) * 2, t); + } + for (uint32_t i = 0; i < 8; i++) { // PrepareEvent(8, teams) + const uint32_t j = uint32_t(game.range(0, 7)); + const uint16_t a = mem.u16(kTeams + i * 2); + mem.set16(kTeams + i * 2, mem.u16(kTeams + j * 2)); + mem.set16(kTeams + j * 2, a); + } + for (uint32_t k = 0; k < 8; k++) { + const int manager = g.manager_of(mem.u16(kTeams + k * 2)); + if (manager < 0) continue; + post_composed(g, manager, kMastersQualificationText); // MastersQualificationText + modern::book_money(g, manager, -150000, true, true); + } + const std::string name = message_text(g, ::bmh::layout::Cup_MastersQualification_TextPointer); + if (g.tournament_name.size() < 0x24) g.tournament_name.resize(0x24, 0); + for (size_t i = 0; i <= name.size() && i < 0x24; i++) g.tournament_name[i] = i < name.size() ? uint8_t(name[i]) : 0; +} + +namespace { + +void put32(Bytes& b, size_t o, uint32_t v) { + for (int i = 0; i < 4; i++) b.at(o + i) = uint8_t(v >> (8 * i)); +} + +// Replays of postponed league matches: cup entry type 9 plays the matches whose replay day +// (table Postponed, 40 entries of 6 bytes: day, round, league, match) is today. +constexpr uint32_t kPostponed = ::bmh::layout::Postponed; +constexpr uint32_t kReplayFixtures = ::bmh::layout::ReplayFixtures; // team list of the type 9 entry (home, away) +constexpr uint32_t kReplayResults = ::bmh::layout::ReplayResults; // its result array (u16 per match) + +// AddBlock: the fixtures of today's replays; the entry's team count (+0x1a) and played +// counter (+0x1d) restart. +void prepare_replays(ModernState& g, uint32_t e, int day) { + StaticMemory& mem = g.memory; + mem.add_block(kReplayFixtures, 0x50); + mem.add_block(kReplayResults, 0x12); + mem.set8(e + 0x1d, 0); + mem.set8(e + 0x1a, 0); + for (uint32_t i = 0; i < 0x12; i++) mem.set8(kReplayResults + i, 0xcc); + int k = 0; + for (int n = 0; n < 0x28; n++) { + const uint32_t at = kPostponed + uint32_t(n) * 6; + if (mem.u16(at) != day) continue; + const int league = mem.u8(at + 3); + const std::vector fx = generate_fixtures(league_table_teams(league), mem.u8(at + 2) + 1, league_matchdays(league) / 2, + league_first_team(league)); + const Fixture& f = fx.at(mem.u8(at + 4)); + mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.home)); + mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.away)); + mem.set8(e + 0x1a, uint8_t(mem.u8(e + 0x1a) + 2)); + } +} + +// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors). +void remove_competition(StaticMemory& mem, int id) { + for (int i = 0; i < 8; i++) { + if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + uint32_t(i))) != id) continue; + for (int j = i; j < 7; j++) mem.set8(::bmh::layout::ActiveSelectors + uint32_t(j), mem.u8(::bmh::layout::Cup_RemoveCompetition_RuntimeField + uint32_t(j))); + mem.set8(::bmh::layout::Cup_RemoveCompetition_RuntimeField2, 0x14); + return; + } +} + +// UndoReschedule(day, 0, 0): today's replay results go back into the league result table and +// their entries are freed; then EndCompetition(9) takes the competition off the list of +// running competitions (ActiveSelectors). +void store_replays(ModernState& g, int day) { + StaticMemory& mem = g.memory; + int k = 0; + for (int n = 0; n < 0x28; n++) { + const uint32_t at = kPostponed + uint32_t(n) * 6; + if (mem.u16(at) != day) continue; + const uint16_t r = mem.u16(kReplayResults + uint32_t(k++) * 2); + const uint8_t result = uint8_t(((r >> 5) << 4) | (r & 0xf)); + g.results.at(size_t(mem.u8(at + 4)) + size_t(mem.u8(at + 2)) * 10 + size_t(mem.u8(at + 3)) * 0x17C) = result; + mem.set16(at, 0); + } + remove_competition(mem, 9); +} + +// Size of the round string table a cup group plays with (pointer at entry +8). +int group_table_teams(const StaticMemory& mem, uint32_t e) { + switch (mem.pointer(e + 8)) { + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: return 4; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: return 6; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: return 12; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: return 16; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: return 18; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: return 20; + } + return 0; +} + +// AddResult(entry, 0): the table of a cup group from its result array (u16 per match, +// 0xCCCC = not played), indexed by draw position. Bit 7 of the flags: three points for a +// win. The ranks are sorted like the league tables (AddResult2) after the last two rounds +// and after later rounds with results. +LeagueTable group_table(const StaticMemory& mem, uint32_t e) { + LeagueTable t; + const uint8_t flags = mem.u8(e + 0x14); + const int teams = mem.u8(e + 0x1a), rounds = mem.u8(e + 0x1b), played = mem.u8(e + 0x1d); + t.size = teams; + const int three_points = flags >> 7; + int last = played - 1, before_last = 0x80; + if (last > 1) before_last = played - 2; + if (last < 0) last = 0; + sort_table(t, 0); + const uint32_t results = mem.pointer(e + 0x0c); + for (int r = 0; r < rounds; r++) { + const std::vector fx = generate_fixtures(group_table_teams(mem, e), r + 1, rounds / ((flags & 1) + 1), 0); + bool counted = false; + for (int s = 0; s < teams; s += 2) { + const uint16_t u = mem.u16(results + uint32_t(s / 2 + r * teams / 2) * 2); + if (u == 0xcccc) continue; + const uint8_t goals[2] = {uint8_t((u >> 5) & 0x1f), uint8_t(u & 0x1f)}; + const int club[2] = {fx.at(size_t(s / 2)).home, fx.at(size_t(s / 2)).away}; + add_result(t, club, goals, 3, three_points); + counted = true; + } + if (before_last == r || last == r || (last < r && counted)) sort_table(t, 0); + } + return t; +} + +// The end of a group stage (AdvanceCup): the qualifiers place by place (all group +// winners, then the runners-up, ...) until the stage's quota (+0x1f) is reached; a place +// taken only partly keeps its best clubs by the table key. Group winner and runner-up are +// noted in +0x22 / +0x24 of every group. Returns the qualifiers and in `loser_pair` the +// first two clubs of the first group ordered by the last table's second place (for a final +// of two). +std::vector group_qualifiers(StaticMemory& mem, uint32_t e, std::array& loser_pair) { + const int groups = mem.u8(e + 0x1e) & 0xF; + int quota = int8_t(mem.u8(e + 0x1f)); + std::vector teams; + std::vector keys; + LeagueTable t; + for (int place = 0; quota > 0; place++) { + for (int grp = 0; grp < groups; grp++) { + uint32_t ge = e; + while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize; + t = group_table(mem, ge); + int idx = 0; + while (idx < mem.u8(ge + 0x1a) && t.rank(idx) != place) idx++; + const uint16_t team = mem.u16(mem.pointer(ge) + uint32_t(idx) * 2); + if (place == 0) mem.set16(ge + 0x22, team); + if (place == 1) mem.set16(ge + 0x24, team); + keys.push_back(sort_key(t, idx, 0)); + teams.push_back(team); + quota--; + } + } + const uint32_t list = mem.pointer(e); + loser_pair[0] = t.rank(0) == 1 ? mem.u16(list) : mem.u16(list + 2); + const int wanted = int8_t(mem.u8(e + 0x1f)); + const int cut = wanted - wanted % groups; + for (; quota < 0; quota++) { + uint32_t worst = keys.back(); + size_t at = 0; + for (int k = cut; k < wanted; k++) + if (keys[size_t(k)] < worst) at = size_t(k), worst = keys[size_t(k)]; + if (worst < keys.back()) { + std::swap(teams.back(), teams[at]); + std::swap(keys.back(), keys[at]); + } + teams.pop_back(); + keys.pop_back(); + } + return teams; +} + +} // namespace + +LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address) { + return group_table(mem, entry_address); +} + +int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address) { + return group_table_teams(mem, entry_address); +} + +void end_competition(StaticMemory& mem, int id) { remove_competition(mem, id); } + +void prepare_friendlies(ModernState& g) { + StaticMemory& mem = g.memory; + if (!mem.has(::bmh::layout::FriendlyDays) || !mem.has(::bmh::layout::FriendlyTeams) || !mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24)) return; + const int today = g.season_day(); // DaysIntoSeason + int count = 0; // local_c: two teams per friendly + for (int i = 0; i < 0x1e; i++) { + if (int16_t(mem.u16(::bmh::layout::FriendlyDays + uint32_t(i) * 2)) != int16_t(today)) continue; + for (int c = 0; c < 2; c++) + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24 + uint32_t(c + count) * 2, mem.u16(::bmh::layout::FriendlyTeams + uint32_t(i * 2 + c) * 2)); + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29 + uint32_t(count >> 1) * 2, 0xcccc); + mem.set16(::bmh::layout::FriendlyDays + uint32_t(i) * 2, 0); + count += 2; + if (i < 0x1d) { + // the planned ones after it move up (the last place keeps its copy) + for (int k = i; k < 0x1d; k++) { + mem.set32(::bmh::layout::FriendlyTeams + uint32_t(k) * 4, mem.u32(::bmh::layout::Cup_PrepareFriendlies_RuntimeField + uint32_t(k) * 4)); + mem.set16(::bmh::layout::FriendlyDays + uint32_t(k) * 2, mem.u16(::bmh::layout::Cup_PrepareFriendlies_RuntimeField2 + uint32_t(k) * 2)); + } + i--; + // the planner's entry 30 counts them (two per friendly); only decreased here, + // not for the last place (as in the original) + const uint32_t planned = modern::cup_entry_address(30) + 0x1a; + mem.set8(planned, uint8_t(mem.u8(planned) - 2)); + } + } + mem.set8(modern::cup_entry_address(24) + 0x1a, uint8_t(count)); // today's friendlies (CupRuntimeField2) +} + +int find_cup(const StaticMemory& mem, int id) { + for (int i = 0; i < kCupEntries; i++) + if (int16_t(mem.u16(modern::cup_entry_address(i) + 0x18)) == id) return i; + return -1; +} + +int cup_round(const StaticMemory& mem, int entry) { + const uint32_t e = modern::cup_entry_address(entry); + const uint8_t flags = mem.u8(e + 0x14), played = mem.u8(e + 0x1d); + if (!(flags & 4)) return played; + return played / ((flags & 1) + 1); +} + +int cup_round_offset(const StaticMemory& mem, int entry, int round) { + if (round == 0) return 0; + const int teams = mem.u8(modern::cup_entry_address(entry) + 0x1a); + return teams * 2 - teams / (1 << (round - 1)); +} + +void rebuild_replay_lists(ModernState& g, uint32_t competitions) { + for (int bit = 5; bit < 0x13; bit++) { + if (!((competitions >> bit) & 1)) continue; + const int entry = modern::find_cup(g.memory, bit - 5); + if (entry >= 0 && int16_t(g.memory.u16(modern::cup_entry_address(entry) + 0x18)) == 9) + prepare_replays(g, modern::cup_entry_address(entry), g.season_day()); + } +} + +void setup_cup_groups(ModernState& g, int id, std::vector& groups, MinuteReport& report) { + const StaticMemory& mem = g.memory; + int entry = modern::find_cup(mem, id); + if (entry < 0) { + report.fail("cup " + std::to_string(id) + " not in the cup table"); + return; + } + const int type = int16_t(mem.u16(modern::cup_entry_address(entry) + 0x18)); + if (type == 9) prepare_replays(g, modern::cup_entry_address(entry), g.season_day()); + if (type == 10) modern::prepare_friendlies(g); + if (type > 9 && mem.u8(modern::cup_entry_address(entry) + 0x1a) != 0) { + // AddCompetition: onto the list of running competitions (ActiveSelectors, 0x14 = free) + for (uint32_t i = 0; i < 8; i++) { + if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + i)) == type) break; + if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + g.memory.set8(::bmh::layout::ActiveSelectors + i, uint8_t(type)); + break; + } + } + } + // (the friendlies 10, the promotion play-off 0xd and the indoor tournament 0xb only join + // the running list above) + if (type > 0xb && type != 0xd && mem.u8(modern::cup_entry_address(entry) + 0x1a) != 0) { + report.fail("cup " + std::to_string(id) + ": preparation of this competition (AddBlock/2631b/26175)"); + return; + } + // skip the stages that are completed (bounded: a broken chain would loop for ever) + for (int steps = 0; modern::cup_round(mem, entry) >= mem.u8(modern::cup_entry_address(entry) + 0x1b); ++steps) { + const int next = int8_t(mem.u8(modern::cup_entry_address(entry) + 0x16)); + if (steps > 0x24 || next < 0 || next >= 0x24) { + report.fail("cup " + std::to_string(id) + ": stage chain without an open stage (entry " + std::to_string(entry) + + ", round " + std::to_string(modern::cup_round(mem, entry)) + " of " + + std::to_string(mem.u8(modern::cup_entry_address(entry) + 0x1b)) + ", next " + std::to_string(next) + ")"); + return; + } + entry = next; + } + const int parallel = mem.u8(modern::cup_entry_address(entry) + 0x1e) & 0xF; + if (mem.u32(modern::cup_entry_address(entry)) == 0) return; + for (int k = 0; k < parallel; k++) { + const uint32_t e = modern::cup_entry_address(entry); + const uint8_t flags = mem.u8(e + 0x14); + const int teams = mem.u8(e + 0x1a); + if (teams == 0) continue; // (the original then looks at the same entry again) + MatchGroup grp; + grp.desc = modern::group_descriptor(g, groups.size()); + grp.desc.at(0) = uint8_t(type + 1); + grp.desc.at(1) = flags; + // competition 11 is the German indoor tournament; in the English game the same entry + // is the League Cup ("Koka Kola Cup"), an ordinary cup on grass (EN Put32) + if (type == 0xb && !kEnglishCompetitions) g.indoor = true; + put32(grp.desc, 0xcc, e); + // the first leg of a two-legged knockout tie is never decided on the day + if ((flags & 5) == 5 && mem.u8(e + 0x1d) % 2 == 0) grp.desc.at(1) &= 0xF7; + int matches = 0, first = 0; // local_1c; the result index is `first` / 2 + const uint32_t list = mem.pointer(e); + if (!(flags & 4)) { + // a group: GenerateFixtures on the cup's round strings (+8), round = played + 1, the + // draw positions index the group's team list; two-legged groups play the rounds + // of the string table twice, home and away swapped + matches = teams / 2; + const int played = mem.u8(e + 0x1d); + first = uint8_t(matches * played * 2); + const int rounds = mem.u8(e + 0x1b) / ((flags & 1) + 1); + int table_teams = 0; + switch (mem.pointer(e + 8)) { + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: table_teams = 4; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: table_teams = 6; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: table_teams = 12; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: table_teams = 16; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: table_teams = 18; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: table_teams = 20; break; + } + if (table_teams == 0) { + report.fail("cup group with unknown round strings"); + return; + } + for (const Fixture& f : generate_fixtures(table_teams, played + 1, rounds, 0)) { + if (int(grp.fixtures.size()) >= matches * 2) break; + grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.home) * 2))); + grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.away) * 2))); + } + // the fixtures are kept in the descriptor itself (+0x88; +0x7c points there) + for (size_t i = 0; i < grp.fixtures.size(); i++) { + grp.desc.at(0x88 + i * 2) = uint8_t(grp.fixtures[i]); + grp.desc.at(0x89 + i * 2) = uint8_t(uint16_t(grp.fixtures[i]) >> 8); + } + } else { + const int round = modern::cup_round(mem, entry); + matches = teams / (1 << (round + 1)); + first = modern::cup_round_offset(mem, entry, round); + for (int i = 0; i < matches * 2; i++) grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(first + i) * 2))); + } + grp.desc.at(2) = uint8_t(matches); + if (type == 0 && matches == 1) grp.desc.at(1) &= 0xFD; // the national cup final + // MatchdayNeedsManagerDesks: a human manager's club notes its side (record +0x28a) + for (int i = 0; i < matches * 2; i++) + for (size_t mgr = 0; mgr < g.manager_teams.size(); mgr++) + if (g.manager_teams[mgr] == grp.fixtures[size_t(i)]) g.manager_records.at(mgr * 0xB0C + 0x28a) = uint8_t(i % 2); + for (int leg = 0; leg < 2; leg++) { + if (leg == 1 && !(flags & 1)) break; + const uint32_t results = mem.pointer(e + 0x0c + uint32_t(leg) * 4); + if (results == 0) continue; + grp.cup_result_address[leg] = results + uint32_t(first / 2) * 2; + std::vector& r = leg == 0 ? grp.cup_results : grp.cup_other_leg; + for (int i = 0; i < matches; i++) r.push_back(mem.u16(grp.cup_result_address[leg] + uint32_t(i) * 2)); + } + groups.push_back(grp); + entry++; + } +} + +} // namespace bmh::modern + +namespace bmh::modern { + +void store_cup_results(ModernState& g, const MatchGroup& grp) { + if (grp.desc.at(0) == 0 || grp.cup_result_address[0] == 0) return; + for (size_t i = 0; i < grp.cup_results.size(); i++) + g.memory.set16(grp.cup_result_address[0] + uint32_t(i) * 2, grp.cup_results[i]); +} + +namespace { + +// NationalTournamentEnd, at the end of the international tournament (competition type 4): the +// honours list of the tournaments (Placements, 4 bytes per tournament, newest first) +// moves one place on and gets the first four (final winner and loser Cup_NationalTournamentEnd_RuntimeField/2dce, +// third place match Cup_NationalTournamentEnd_RuntimeField3/2df6) as national team index | 0x80. A Bundestrainer's +// association (manager slot 0 holds team 0x165) pays 400000 for taking part and the +// premium of the place (CupRuntimeField3). +void national_tournament_end(ModernState& g) { + StaticMemory& mem = g.memory; + const int teams[4] = {int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField2)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField3)), + int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField4))}; + static constexpr int32_t kPremium[4] = {1000000, 600000, 300000, 200000}; // CupRuntimeField3 + if (mem.has(::bmh::layout::Placements)) + for (int i = 0x4c - 1; i >= 0; i--) mem.set8(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField5 + uint32_t(i), mem.u8(::bmh::layout::Placements + uint32_t(i))); + const bool coach = !g.manager_teams.empty() && g.manager_teams[0] == no_team(); + if (coach) modern::book_money(g, 0, -400000, true, true); + for (int i = 0; i < 4; i++) { + if (teams[i] == no_team() && coach) modern::book_money(g, 0, -kPremium[i], true, true); + // (0x8a + 0x1e + 0xbd = 0x165: CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 + ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3) + if (mem.has(::bmh::layout::Placements)) mem.set8(::bmh::layout::Placements + uint32_t(i), uint8_t((teams[i] - no_team()) | 0x80)); + } +} + +// cup_tie on the result arrays of a stage (CupTie(results0, results1, index, flags)) +int stage_tie(const StaticMemory& mem, uint32_t e, int index) { + MatchGroup grp; + grp.desc.assign(0xd0, 0); + grp.desc.at(1) = mem.u8(e + 0x14); + const uint32_t r0 = mem.pointer(e + 0x0c), r1 = mem.pointer(e + 0x10); + grp.cup_results.assign(size_t(index) + 1, 0); + grp.cup_results[size_t(index)] = mem.u16(r0 + uint32_t(index) * 2); + if (r1 != 0) { + grp.cup_other_leg.assign(size_t(index) + 1, 0); + grp.cup_other_leg[size_t(index)] = mem.u16(r1 + uint32_t(index) * 2); + } + return modern::cup_tie(grp, index); +} + +void swap16(StaticMemory& mem, uint32_t a, uint32_t b) { + const uint16_t x = mem.u16(a); + mem.set16(a, mem.u16(b)); + mem.set16(b, x); +} + +// Getenv(teams, offset): Source home advantage followed by an unstable-free +// descending sort on each tie's combined league weight. Kept in this Core module so +// finish_cup can expose the Original draw before the inner sort and retain its outer sort. +void order_national_cup_ties(ModernState& g, int teams, int offset) { + StaticMemory& mem = g.memory; + const uint32_t list = mem.pointer(modern::cup_entry_address(0)) + uint32_t(offset) * 2; + static constexpr uint8_t kWeight[10] = {3, 1, 0, 0, 2, 0, 0, 0, 7, 0}; + const int lower = league_first_team(2); + std::vector weights; + weights.reserve(size_t(teams / 2)); + auto team = [&](int i) { return int16_t(mem.u16(list + uint32_t(i) * 2)); }; + auto swap_pair = [&](int a, int b) { + swap16(mem, list + uint32_t(a) * 2, list + uint32_t(b) * 2); + swap16(mem, list + uint32_t(a + 1) * 2, list + uint32_t(b + 1) * 2); + }; + for (int i = 0; i < teams; i += 2) { + if (lower <= team(i + 1) && team(i) < lower) + swap16(mem, list + uint32_t(i) * 2, list + uint32_t(i + 1) * 2); + auto league = [](int t) { return t > 0x164 ? 0 : team_league(t); }; + const int la = league(team(i)), lb = league(team(i + 1)); + weights.push_back(uint8_t(kWeight[la < 10 ? la : 9] + kWeight[lb < 10 ? lb : 9])); + } + for (int i = 0; i < teams / 2 - 1; ++i) + for (int j = i + 1; j < teams / 2; ++j) + if (weights[size_t(i)] < weights[size_t(j)]) { + std::swap(weights[size_t(i)], weights[size_t(j)]); + swap_pair(i * 2, j * 2); + } +} + +bool source_cup_draw_enabled(const StaticMemory& mem, int competition) { + // CupDrawFromGame: outside leagues 4..7 the leagues must be enabled, then the + // competition's display option must be clear. The follow-up package targets comp0. + if (competition < 4 || competition > 7) { + if (!mem.has(::bmh::layout::CompetitionSelection) || (mem.u8(::bmh::layout::CompetitionSelection) & 1) == 0) return false; + } + const uint32_t option = ::bmh::layout::LeaguePresentationOptions + uint32_t(competition + 5) * 9; + return mem.has(option) && mem.u8(option) == 0; +} + +void observe_cup_draw(const ModernState& g, int entry, SeasonCupDrawPhase phase, + const SeasonCupDrawHook& hook) { + if (!hook) return; + const StaticMemory& mem = g.memory; + const uint32_t address = modern::cup_entry_address(entry); + SeasonCupDrawEvent event; + event.phase = phase; + event.entry_address = address; + event.competition = mem.u8(address + 0x18); + event.round = modern::cup_round(mem, entry); + event.offset = modern::cup_round_offset(mem, entry, event.round); + event.count = size_t(mem.u8(address + 0x1a)) >> event.round; + const uint32_t first = mem.pointer(address) + uint32_t(event.offset) * 2; + event.participants.reserve(event.count); + for (size_t i = 0; i < event.count; ++i) + event.participants.push_back(mem.u16(first + uint32_t(i) * 2)); + hook(g, event); +} + +} // namespace + +void advance_cup(ModernState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game, + const SeasonCupDrawHook& cup_draw, const CompetitionWinnerHook& winner_display) { + StaticMemory& mem = g.memory; + int entry = modern::find_cup(mem, id); + if (entry < 0) return; + const int type = int16_t(mem.u16(modern::cup_entry_address(entry) + 0x18)); + if (type == 9) return store_replays(g, g.season_day()); + // EndCompetition(type), re-added at the next preparation; the English Put32 keeps its + // League Cup (type 0xb) running like the other cups + if (type == 0xb && !kEnglishCompetitions) remove_competition(mem, type); + if (type == 10) { + // the friendlies: off the running list, the day's calendar entry masked with 0xffe + // (0x4001 becomes 0) and no teams left in today's entry (CupRuntimeField2) + remove_competition(mem, type); + const uint32_t day = ::bmh::layout::CompetitionCalendar + uint32_t(g.season_day()) * 2; + if (mem.has(day)) mem.set16(day, uint16_t(mem.u16(day) & 0xffe)); + mem.set8(modern::cup_entry_address(24) + 0x1a, 0); + return; + } + if (type > 8 && type != 0xd && type != 0xb) { + report.fail("cup " + std::to_string(id) + ": processing of this competition (AdvanceCup)"); + return; + } + while (modern::cup_round(mem, entry) >= mem.u8(modern::cup_entry_address(entry) + 0x1b)) + entry = int8_t(mem.u8(modern::cup_entry_address(entry) + 0x16)); + uint32_t e = modern::cup_entry_address(entry); + std::vector winners, losers; + std::array loser_pair{}; + if (!(mem.u8(e + 0x14) & 4)) { + // a group stage: every group (the consecutive entries up to the one without a + // parallel link, +0x17) counts the round + for (uint32_t ge = e;; ge += kCupEntrySize) { + mem.set8(ge + 0x1d, uint8_t(mem.u8(ge + 0x1d) + 1)); + if (mem.u8(ge + 0x17) == 0) break; + } + if (mem.u8(e + 0x1d) < mem.u8(e + 0x1b)) return; + winners = group_qualifiers(mem, e, loser_pair); + } else { + const int round = modern::cup_round(mem, entry); + const int slots = mem.u8(e + 0x1a) / (1 << round); // local_3c: teams in this round + const int first = modern::cup_round_offset(mem, entry, round); + mem.set8(e + 0x1d, uint8_t(mem.u8(e + 0x1d) + 1)); // (unless CupRuntimeField4) + const uint32_t list = mem.pointer(e); + if ((mem.u8(e + 0x14) & 1) && mem.u8(e + 0x1d) % 2 != 0) { + // after the first leg: the pairs turn round, the results go to the second array + for (int i = 0; i < slots; i += 2) { + swap16(mem, list + uint32_t(first + i) * 2, list + uint32_t(first + i + 1) * 2); + const uint32_t k = uint32_t((first + i) / 2) * 2; + swap16(mem, mem.pointer(e + 0x0c) + k, mem.pointer(e + 0x10) + k); + } + return; + } + for (int i = 0; i < slots; i += 2) { + int t = stage_tie(mem, e, (first + i) / 2); + if (t > 1) t = 1; + winners.push_back(mem.u16(list + uint32_t(first + i + t) * 2)); + losers.push_back(mem.u16(list + uint32_t(first + i + 1 - t) * 2)); + } + } + // CupRuntimeField5[type] < 5 (national cup and the three European cups): a human manager's + // club that goes through counts one more round in his season record (ManagerOf, + // record +0xda + season * 3 + 1 national / 2 European) + if (type >= 0 && type <= 3) + for (uint16_t t : winners) { + const int manager = g.manager_of(t); + if (manager < 0) continue; + const size_t at = size_t(manager) * 0xB0C + 0xda + size_t(std::min(g.season, 0x31)) * 3 + (type > 0 ? 2 : 1); + g.manager_records.at(at) = uint8_t(g.manager_records.at(at) + 1); + } + if (modern::cup_round(mem, entry) == mem.u8(e + 0x1b)) { + // the stage is over + if (mem.u8(e + 0x16) == 0) { + // The last stage of the competition. A single final notes its winner (+0x22) and + // loser (+0x24); competition 0xc leaves the running list. + if (winners.size() == 1) { + mem.set16(e + 0x22, winners[0]); + if (!losers.empty()) mem.set16(e + 0x24, losers[0]); + } + if (type == 0xc) remove_competition(mem, 0xc); + // CupRuntimeField5: the title of the competition (0xFF: none) + static constexpr uint8_t kTitle[14] = {1, 2, 3, 4, 5, 0xff, 6, 0xff, 8, 0xff, 0xff, 0xff, 0xff, 0xff}; + const uint8_t title = type >= 0 && type < 14 ? kTitle[type] : 0xff; + if (title != 0xff && !winners.empty()) { + if (type == 4) national_tournament_end(g); // NationalTournamentEnd + // CompetitionWinnerScreen(0, title, winner): the winner screen (unless switched off, + // Cup_AdvanceCup_RuntimeField; no draws) clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2. A human manager's club counts + // the title in his record: +0x8a6 national cup, +0x8a8 European cups. + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display) + winner_display(g, {title, winners[0]}); + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + const int manager = g.manager_of(winners[0]); + if (manager >= 0 && type >= 0 && type < 4) { + const size_t at = size_t(manager) * 0xB0C + (type == 0 ? 0x8a6 : 0x8a8); + const uint16_t n = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); + g.manager_records.at(at) = uint8_t(n + 1), g.manager_records.at(at + 1) = uint8_t((n + 1) >> 8); + } + // ListTitleHoldersAf(winner, title): the list of title holders (Titles) + mem.set16(::bmh::layout::Titles + uint32_t(title) * 100 + uint32_t(std::min(g.season, 0x31)) * 2, winners[0]); + } + if (type == 0 && !winners.empty()) { + // the national cup: winner (Cup_AdvanceCup_RuntimeField5) and the previous holder + // (Career_CompetitionPointersEnglish_ExecutableField28 = Cup_AdvanceCup_RuntimeField6); Cup_AdvanceCup_RuntimeField2 = 0 if the holder won again, else 2 + mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, winners[0]); + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6)); + if (mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31)) mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, 0xcccc); + if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField2)) mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField2, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6) == winners[0] ? 0 : 2); + } + // a linked stage (+0x17) takes the runner-up (the indoor tournament's final group + // notes it in the group for third place) + if (mem.u8(e + 0x17) != 0 && winners.size() > 1) + mem.set16(modern::cup_entry_address(mem.u8(e + 0x17)) + 0x22, winners[1]); + // (the indoor tournament only: the English League Cup has no Masters; its winner + // would go to EN CupRuntimeField6 for Europe - not ported, see docs/fltd.md) + if (type != 0xb || kEnglishCompetitions) return; + // the indoor tournament: the four places (CupRuntimeField7 picks them from the list + // champion..fourth) earn points for the Masters (CupRuntimeField8 x strength class + // Cup_AdvanceCup_RuntimeField3, clubs of the first two leagues only), then the next tournament is + // drawn; after five tournaments the Masters follow + int held = mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4); + if (held > 4) { + // the end of the Masters: CompetitionWinnerScreen(0, 7, winner) shows the winner (unless + // switched off, Cup_AdvanceCup_RuntimeField; no draws) and clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2; + // ListTitleHoldersAf(winner, 7) enters it in the list of title holders (Titles, + // 50 seasons per competition); Cup_AdvanceCup_RuntimeField7 = winner; a human manager's club + // gets a message and 250 000; EndCompetition removes the competition + const uint16_t winner = mem.u16(e + 0x22); + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display) + winner_display(g, {7, winner}); + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + mem.set16(::bmh::layout::Titles + 7 * 100 + uint32_t(std::min(g.season, 0x31)) * 2, winner); + if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField7)) mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField7, winner); + const int manager = g.manager_of(winner); + if (manager >= 0) { + post_composed(g, manager, kMastersWinnerText); // MastersWinnerText + modern::book_money(g, manager, -250000, true, true); + } + remove_competition(mem, type); + return; + } + static constexpr uint8_t kPlaceOrder[4] = {0, 2, 1, 3}; // CupRuntimeField7 + static constexpr uint8_t kPlacePoints[5] = {0, 6, 4, 2, 1}; // CupRuntimeField8 + for (int i = 0; i < 4 && size_t(kPlaceOrder[i]) < winners.size(); i++) { // Uint32T + const int team = winners[kPlaceOrder[i]]; + if (team < kLeagueSizes[0] + kLeagueSizes[1]) { + const uint32_t at = ::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(team) * 2; + mem.set16(at, uint16_t(mem.u16(at) + kPlacePoints[i + 1] * mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField3))); + } + } + mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, uint8_t(++held)); + if (!game) { + report.fail("indoor tournament: the next draw needs the game generator"); + return; + } + if (held >= 5) { + modern::masters_qualification(g, *game); + return; + } + modern::indoor_tournament_draw(g, *game, rand); // (CupRuntimeField = 0) + return; + } + uint32_t last = e; + const int seeded = mem.u8(e + 0x20); + if (seeded != 0) { + // clubs seeded directly into the next stage stand before the team lists + const int groups = mem.u8(e + 0x1e) & 0xF; + int left = seeded; + for (int k = 0; left != 0; k++) + for (int grp = 0; grp < groups; grp++) { + uint32_t ge = e; + while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize; + last = ge; + if (left != 0) { + winners.push_back(mem.u16(mem.pointer(ge) - 2 - uint32_t(k) * 2)); + left--; + } + } + } + entry = int8_t(mem.u8(last + 0x16)); + e = modern::cup_entry_address(entry); + } + const int count = int(winners.size()); // local_14 + if (mem.u8(e + 0x14) & 0x20) { + // the draw + for (int i = 0; i < count; i++) { + const int a = rand.range(0, count - 1); + const int b = rand.range(0, count - 1); + std::swap(winners[size_t(b)], winners[size_t(a)]); + } + } + if (!(mem.u8(e + 0x14) & 4)) { + // a group stage: the teams go round the groups, taken from the end + // groups of two (third place and final): the losers of the ties are added (local_88) + if (mem.u8(e + 0x1a) == 2) + for (int i = 0; i < 2 && size_t(i) < losers.size(); i++) winners.push_back(losers[size_t(i)]); + const int groups = mem.u8(e + 0x1e) & 0xF; + int left = int(winners.size()); + uint32_t ge = e; + for (int slot = 0; slot < mem.u8(e + 0x1a); slot++) + for (int grp = 0; grp < groups; grp++) { + ge = e; + while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize; + mem.set16(mem.pointer(ge) + uint32_t(slot) * 2, winners.at(size_t(--left))); + } + // AdvanceCup leaves any entrants beyond the regular group slots in the reserved + // list immediately before the final linked group's team list (entry +0x20 is the + // source guard). The Source consumes the remaining local list backwards. + if (mem.u8(ge + 0x20) != 0) { + for (int slot = 0; left > 0; ++slot) + for (int grp = 0; grp < groups; ++grp) + if (left > 0) + mem.set16(mem.pointer(ge) - 2 - uint32_t(slot) * 2, winners.at(size_t(--left))); + } + if (mem.u8(e + 0x1a) == 2) { + // the first club of this group and the second of the linked group change places + const uint32_t a = mem.pointer(e), b = mem.pointer(modern::cup_entry_address(mem.u8(e + 0x17))) + 2; + const uint16_t x = mem.u16(a); + mem.set16(a, mem.u16(b)); + mem.set16(b, x); + } + } else { + const int next_round = modern::cup_round(mem, entry); + const int offset = modern::cup_round_offset(mem, entry, next_round); + const uint32_t to = mem.pointer(e); + int first_pair = 0; + if (next_round == mem.u8(e + 0x1b) && mem.u8(e + 0x20) != 0) { + first_pair = mem.u8(e + 0x20); + for (int i = 0; i < first_pair; ++i) + mem.set16(to - 2 - uint32_t(i) * 2, winners.at(size_t(i))); + } + for (int i = first_pair; i < count / 2; i++) { + mem.set16(to + uint32_t(offset + i * 2) * 2, winners[size_t(i)]); + mem.set16(to + uint32_t(offset + i * 2 + 1) * 2, winners[size_t(count - 1 - i)]); + } + if (e == modern::cup_entry_address(0)) { + const bool eligible = type == 0 && count > 2 && (mem.u8(e + 0x14) & 0x20) != 0 && + source_cup_draw_enabled(mem, type); + if (eligible) { + // CupDrawFromGame displays the just-written shuffled order first. + observe_cup_draw(g, entry, SeasonCupDrawPhase::draw, cup_draw); + // It then performs Getenv and CupGroupOverviewEffects before returning. + order_national_cup_ties(g, count, offset); + modern::cup_overview_effects(g); // simulation effects occur even without an observer + observe_cup_draw(g, entry, SeasonCupDrawPhase::overview, cup_draw); + } + // AdvanceCup performs this outer sort after CupDrawFromGame returns (including + // its hidden-display early return). It is idempotent after the inner sort. + order_national_cup_ties(g, count, offset); + } + } + // Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3: clubs left in the European cups + const uint32_t left_at[4] = {0, ::bmh::layout::Career_EuropeanClub_ExecutableField, ::bmh::layout::Career_EuropeanClub_ExecutableField2, ::bmh::layout::Career_EuropeanClub_ExecutableField3}; + if (type >= 1 && type <= 3 && mem.has(left_at[type])) mem.set8(left_at[type], uint8_t(count)); +} + +} // namespace bmh::modern diff --git a/src/modern/game/cup.hpp b/src/modern/game/cup.hpp new file mode 100644 index 0000000..71c2bce --- /dev/null +++ b/src/modern/game/cup.hpp @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +#include "game/cup.hpp" +// Cup competitions (BMH.exe V2.24 + supported rule profile patch). +// +// All cups are described by the table at CupTable: 36 entries of 0x28 bytes, one per stage +// (knockout rounds of a cup, a group of a group stage, a final, ...). Entries of the same +// cup share the id at +0x18 and are linked: +// +0x00 pointer to the team list (u16 team ids; for knockout stages the pairs of each +// round follow each other, round r starting at cup_round_offset(r)) +// +0x08 pointer to the round strings of group stages (fixture tables, see schedule.hpp) +// +0x0c pointer to the results of the first/only leg, +0x10 of the second leg (u16 per +// match: bits 0-4 away goals, 5-9 home goals, 10-15 phase; 0xCCCC not played) +// +0x14 flags: bit 0 two legs, bit 2 knockout, bit 3 the tie is decided on the day +// (extra time), bit 1 away-side penalty for league-style chances, ... +// +0x16 index of the next stage, +0x17 index of the parallel group of this stage +// +0x18 cup id (0 national cup, 1-3 European cups, 4.. further competitions) +// +0x1a number of teams, +0x1b number of rounds (legs), +0x1d legs played so far +// +0x1e low nibble: number of parallel groups, high nibble: index of this group +// Match group descriptors of cups have type = cup id + 1 and point to their table entry +// (descriptor +0xcc) instead of holding a league number. + +#include +#include + +#include "game/match_engine.hpp" +#include "game/table.hpp" +#include "modern/game/season.hpp" +#include "game/sportschau_presentation.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +constexpr uint32_t kCupTable = ::bmh::layout::CupTable; +constexpr int kCupEntries = 36; +constexpr uint32_t kCupEntrySize = 0x28; + +inline uint32_t cup_entry_address(int index) { return kCupTable + uint32_t(index) * kCupEntrySize; } +inline int cup_entry_index(uint32_t address) { return int((address - kCupTable) / kCupEntrySize); } + +// FindCup(id, 0): the first table entry of a cup, -1 if there is none. +int find_cup(const StaticMemory& mem, int id); +// CupRound: the current round of a stage (legs played, halved for two-legged ties). +int cup_round(const StaticMemory& mem, int entry); +// CupRoundOffset: index of the first team of knockout round `round` in the team list. +int cup_round_offset(const StaticMemory& mem, int entry, int round); + +// AddResult's group-table calculation. Exposes the existing Core projection +// as a read-only value for Source overview observers and renderers. +LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address); +// Team count selected by the Source group round-schedule pointer at entry +8. +int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address); + +// SetupCupGroups: the match groups of cup `id` for today, appended to `groups`. +void setup_cup_groups(ModernState& g, int id, std::vector& groups, MinuteReport& report); +// The lists of today's postponed-match replays (blocks ReplayFixtures/ReplayResults, not in the savegame) as +// the preparation of the matchday built them (prepare_replays, no draws): needed when a game +// saved at the pre-match desk of a replay day is continued. +void rebuild_replay_lists(ModernState& g, uint32_t competitions); + +// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors). +void end_competition(StaticMemory& mem, int id); + +// PrepareFriendlies: the friendlies (competition 10, cup table entry 24) of today: the planned ones +// (entry 30: team pairs FriendlyTeams, season days FriendlyDays, 30 places) of this season day +// go into the day's fixture list (Career_CompetitionPointersEnglish_ExecutableField24) with an open result (0xcccc) and leave the plan. +void prepare_friendlies(ModernState& g); + +} // namespace bmh::modern + +namespace bmh::modern { + +// Writes the results of a cup group (current leg) back into the result array in memory. +void store_cup_results(ModernState& g, const MatchGroup& grp); + +// AdvanceCup for knockout stages: after a matchday of cup `id` the legs played go up; +// after the first leg of a two-legged tie the pairs turn round (home and away swapped, +// the results moved to the other leg's array). After a complete round the winners +// (cup_tie) meet in the next round - drawn if the stage has flag 0x20 (WatcomRandom) - +// or, when the stage is over, fill the next linked stage, including qualifiers and direct +// seeds for group and knockout formats; group match simulation and competition-specific +// finals remain outside this routine. +// The indoor tournament draws its next tournament at the end (game generator, `game`). +void advance_cup(ModernState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr, + const SeasonCupDrawHook& cup_draw = {}, const CompetitionWinnerHook& winner = {}); + +// The end of the fifth indoor tournament: the field of the Masters (MastersQualification2, +// IndoorStandingsFromGame(0)), see cup.cpp. +void masters_qualification(ModernState& g, GameRandom& game); + +} // namespace bmh::modern diff --git a/src/modern/game/desk.cpp b/src/modern/game/desk.cpp new file mode 100644 index 0000000..2c7040c --- /dev/null +++ b/src/modern/game/desk.cpp @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/desk.hpp" + +#include +#include +#include +#include + +#include "modern/game/matchday.hpp" +#include "game/messages.hpp" +#include "modern/game/prediction.hpp" +#include "game/schedule.hpp" +#include "modern/game/week.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecord = 0xB0C; + +// DeskRuntimeField: which of the 0x36 desk buttons exist, for the pseudo club 0x165 and per +// game mode (GameMode; the table for mode m starts at DeskRuntimeField + m * 0x36). +constexpr uint8_t kButtons[0xa2] = { + 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, + 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, + 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, + 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 0}; + +int16_t rd16(const std::vector& v, size_t o) { return int16_t(v.at(o) | v.at(o + 1) << 8); } + +} // namespace + +void update_prestige(ModernState& g, int manager) { + static const uint8_t kWeight[4] = {25, 50, 15, 10}; // DeskRuntimeField2 + std::vector& r = g.manager_records; + const size_t rec = size_t(manager) * kRecord; + r.at(rec + 0x211) = 0; + for (int k = 0; k < 4; k++) { + int value = 0; // local_c + switch (k) { + case 0: value = (rd16(r, rec + 0x8b2) * 100) / 0x44c; break; + case 1: value = (rd16(r, rec + 0x8aa) * 100) / 0x44c; break; + case 2: { + const int32_t balance = int32_t(r.at(rec + 0x314) | r.at(rec + 0x315) << 8 | r.at(rec + 0x316) << 16 | + uint32_t(r.at(rec + 0x317)) << 24); + value = std::clamp(balance / 50000 + 0x32, 0, 100); + break; + } + case 3: value = r.at(rec + 0x26f); break; + } + r.at(rec + 0x211) = uint8_t(r.at(rec + 0x211) + int8_t((kWeight[k] * value) / 100)); + } +} + +void save_game_draws(WatcomRandom& rand) { + const int high = rand.range(0, 0x8fff), low = rand.range(0, 0x8fff); + (void)high, (void)low; // the savegame id high * layout field + low + 1 (DeskRuntimeField3, list ab790) + rand.range(0, 0xff); // DeskRuntimeField4 = r + 'n', the check byte at the end of the file + rand.range(0, 0xff); // the key byte of the header +} + +void enter_desk(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, + const DeskAutosaveHook& autosave) { + const int team = g.manager_teams.at(size_t(manager)); + // HasNoEquivalentCondition: button states (block Desktops, 0x10 bytes per button, 0x360 per manager) + const int mode = g.memory.has(::bmh::layout::GameMode) ? g.memory.u8(::bmh::layout::GameMode) : 0; + const int mode2 = g.memory.has(::bmh::layout::CareerDuration) ? g.memory.u8(::bmh::layout::CareerDuration) : 0; + if (g.memory.has(::bmh::layout::Desktops)) + for (int b = 1; b < 0x36; b++) { + const uint32_t at = ::bmh::layout::Desktops + uint32_t(b) * 0x10 + uint32_t(manager) * 0x360 + 1; + uint8_t v = uint8_t(g.memory.u8(at) & 0xf); + // EN AlwaysHidesRecordIndoorTableIncluding always hides record 10 (IndoorTable), including + // Modus III. DE HasNoEquivalentCondition has no equivalent condition. + if ((kEnglishCompetitions && b == 10) || + (team == no_team() && kButtons[b] == 0) || (mode < 3 && kButtons[mode * 0x36 + b] == 0) || + (b == 0x16 && mode2 == 1 && g.date < 0x16e)) + v |= 0x10; + g.memory.set8(at, v); + } + modern::stir_random(game, rand); // StirRandom + if (team != no_team()) { + std::array buf; + modern::table_prediction(g, team, 1, buf); + } + // The autosave: at the first manager's desk a new month code (CareerSession_PairingsRuntimeDraw_ExecutableField5) counts one + // more month (DeskRuntimeField5); every Desk_EnterDesk_RuntimeField months (a setting, byte 0x61 of block + // LeaguePresentationOptions, 0 = off) the game saves itself as AUTOSAVE (MakeSavegame) + if (manager == 0) { + const int month = modern::month_code(g.date); + if (g.autosave_month != month) g.autosave_month = month, g.autosave_months++; + } + const int period = g.memory.has(::bmh::layout::LeaguePresentationOptions) ? g.memory.u8(::bmh::layout::Desk_EnterDesk_RuntimeField) : 0; + if (period != 0 && g.autosave_months != 0 && g.autosave_months % period == 0) { + if (autosave) autosave(g, rand); + else modern::save_game_draws(rand); // unpresented/headless legacy model + g.autosave_months = 0; + } + // (the warnings of Fill are display only) + modern::update_prestige(g, manager); + // At the "Saisonende" desk (CareerSession_RuntimeError_RuntimeField4): the main sponsor's minimal goal (record + // +0x176, a table place). Missed: "Ihnen entgehen Sponsorgelder, da Sie das Minimalziel + // (. Platz) nicht erreicht haben." Reached: (4 - league) * 50000 per place better + // than the goal plus one (the third divisions count as the second), booked as income. + std::vector& r = g.manager_records; + const size_t rec = size_t(manager) * 0xB0C; + const int goal = r.at(rec + 0x176); + if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && g.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) != 0 && goal != 0) { + const int place = int16_t(modern::table_position(g, team)) + 1; // TablePosition + std::string text; + if (goal < place) { + text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer5) + format_number(g, goal, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer6); + } else { + int league = int8_t(r.at(rec + 0x210)); // CareerSession_BeginFriendlyOpponentTable_RuntimeField2 + if (league > 2) league--; + const int32_t amount = (4 - league) * 50000 * (goal - place + 1); + modern::book_money(g, manager, -amount, true, true); // BookMoney2 with FinanceStatisticsEnabled + text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer2) + format_number(g, amount, 0x101) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer) + + format_number(g, place, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer3) + format_number(g, goal, 1) + + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer4); + } + post_composed(g, manager, text); + r.at(rec + 0x176) = 0; + } +} + +} // namespace bmh::modern diff --git a/src/modern/game/desk.hpp b/src/modern/game/desk.hpp new file mode 100644 index 0000000..bf34c9b --- /dev/null +++ b/src/modern/game/desk.hpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/desk.hpp" +// Entering a human manager's desk (DeskDate, the part before the desk screen). + +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" +#include + +namespace bmh::modern { + +// DeskDate up to the screen: the desk buttons (HasNoEquivalentCondition), the random stir when a +// screen is entered (StirRandom), the table prediction with its season goal messages +// (Void5 mode 1), the autosave every Desk_EnterDesk_RuntimeField months and the manager's +// prestige (UpdatePrestige). +// Source save operation at the desk boundary. A successful writer owns exactly +// the normal four Save draws; failure before opening the file owns none. +void enter_desk(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, + const DeskAutosaveHook& autosave = {}); + +// The draws of saving a game (MakeSavegame): the savegame id (two WatcomRandom(0, 0x8fff)) +// and two bytes WatcomRandom(0, 0xff). Everything else the save writes is not saved itself. +void save_game_draws(WatcomRandom& rand); + +// UpdatePrestige: prestige of a human manager (record +0x211), a weighted sum of his two +// manager ratings (+0x8b2 25 %, +0x8aa 50 %), his money (15 %) and record +0x26f (10 %). +void update_prestige(ModernState& g, int manager); + +} // namespace bmh::modern diff --git a/src/modern/game/desk_actions.cpp b/src/modern/game/desk_actions.cpp new file mode 100644 index 0000000..0f534a7 --- /dev/null +++ b/src/modern/game/desk_actions.cpp @@ -0,0 +1,2250 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/desk_actions.hpp" + +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "modern/game/matchday.hpp" +#include "game/messages.hpp" +#include "modern/game/month.hpp" +#include "game/transfer_bid.hpp" +#include "modern/game/weekly.hpp" +#include "modern/game/club_player_detail.hpp" +#include "modern/game/week.hpp" + +namespace bmh::modern { + +namespace { + +int32_t rd32(const std::vector& v, size_t o) { + return int32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16 | uint32_t(v.at(o + 3)) << 24); +} +void wr32(std::vector& v, size_t o, int32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(uint32_t(x) >> (8 * i)); +} + +// Manager record (ManagerRecords + manager * 0xb0c) offsets used here. +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kTeam = 0x290; // club of the manager (low byte used) +constexpr size_t kFocus = 0xc1; // four training camp sliders 0..15 +constexpr size_t kStays = 0x21f; // bits 0-6 stays, bit 7 "in a camp this week" +constexpr size_t kCampExpenses = 0x890; // money spent on training camps +constexpr uint32_t kFriendlyTeams = ::bmh::layout::FriendlyTeams; +constexpr uint32_t kFriendlyDays = ::bmh::layout::FriendlyDays; +constexpr uint32_t kFriendlyPlanEntries = 30; +constexpr uint32_t kFriendlyPlanCount = ::bmh::layout::FriendlyPlanCount; // cup entry 30, +0x1a; counts two teams per booking +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; +constexpr const char* kOrdinarySellerBoundary = + "seller is outside the Original ordinary club squads (clubs 0..137 or free agents only)"; + +// DeskActions_ConfigureTrainingCampData_RuntimeField: four quality grades per resort (1..5). The sliders use grade +// kSliderGrade[u] (DeskActionsRuntimeField), the morale grade 2 (DeskActionsRuntimeField2), the freshness grade +// 3 (DeskActionsRuntimeField3). +constexpr int kSliderGrade[4] = {1, 0, 0, 3}; +// DeskActionsRuntimeField4: step by drawn index (0..23); indices 0..7 lower a value, 8.. raise it. +constexpr int8_t kStep[24] = {-3, -2, -2, -2, -1, -1, -1, -1, 0, 0, 1, 1, + 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5}; +// DeskActionsRuntimeField5: direction per value (familiarity counts the other way round). +constexpr int8_t kDirection[5] = {1, 1, 1, -1, 1}; + +// Scaled: a * b * 20 / 100 with unsigned byte arguments. +int scaled(int a, int b) { return (a & 0xff) * (b & 0xff) * 20 / 100; } + +FriendlyBookingQuote make_friendly_quote(const ModernState& g, int manager, int opponent, + bool manager_home) { + FriendlyBookingQuote out; + out.manager = manager; + out.opponent = opponent; + out.manager_home = manager_home; + if (!g.memory.has(kFriendlyPlanCount)) { + out.status = FriendlyQuoteStatus::invalid_state; + return out; + } + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size()) { + out.status = FriendlyQuoteStatus::invalid_manager; + return out; + } + const int own_team = g.manager_teams[size_t(manager)]; + if (own_team < 0 || own_team >= first_foreign_cup() || opponent < 0 || opponent >= first_foreign_cup() || opponent == own_team) { + out.status = FriendlyQuoteStatus::invalid_opponent; + return out; + } + out.manager_team = own_team; + out.planner_count = g.memory.u8(kFriendlyPlanCount); + out.home_team = manager_home ? own_team : opponent; + out.away_team = manager_home ? opponent : own_team; + out.payer_manager = g.manager_of(out.home_team); + out.opponent_manager = g.manager_of(opponent); + const int first_rating = team_average(g, own_team, 0xff).value; + const int second_rating = team_average(g, opponent, 0xff).value; + const uint32_t combined = uint32_t(first_rating + second_rating) * 1000; + // DeskDate uses integer arithmetic in this order: (sum * (sum / 13000) / 7000) * 1000. + out.cost = int32_t((uint64_t(combined) * (combined / 13000) / 7000) * 1000); + out.status = FriendlyQuoteStatus::quoted; + return out; +} + +int national_opponent_manager(const ModernState& g, const NationalFriendlyOwner& owner, + int opponent) { + const int ordinary = g.manager_of(opponent); + if (ordinary >= 0) return ordinary; + // FindManagerForClub's second lookup: spare manager record 4 represents the + // Bundestrainer's own association only for the first human national coach. + if (owner.manager == 0 && !g.manager_teams.empty() && g.manager_teams[0] == no_team() && + g.memory.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField) && int(g.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)) == opponent && + 5 * kRecordSize <= g.manager_records.size()) return 4; + return -1; +} + +NationalFriendlyQuote make_national_friendly_quote(const ModernState& g, + const NationalFriendlyOwner& owner, int opponent, bool manager_home, WatcomRandom& rand) { + NationalFriendlyQuote out; + out.owner = owner; + out.watcom_seed_before = rand.seed(); + out.watcom_calls_before = rand.calls(); + out.terms.manager = owner.manager; + out.terms.manager_team = owner.runtime_team; + out.terms.opponent = opponent; + out.terms.manager_home = manager_home; + if (!g.memory.has(kFriendlyPlanCount)) { + out.terms.status = FriendlyQuoteStatus::invalid_state; + return out; + } + if (!owner.request_id || owner.menu_kind != 6 || owner.runtime_team != no_team() || owner.manager < 0 || + size_t(owner.manager) >= g.manager_teams.size() || + (size_t(owner.manager) + 1) * kRecordSize > g.manager_records.size() || + g.manager_teams[size_t(owner.manager)] != no_team()) { + out.terms.status = FriendlyQuoteStatus::invalid_manager; + return out; + } + // Page 4 cannot return Germany (0); the engine boundary repeats that gate. + if (opponent <= no_team() || opponent > 0x1a2 || opponent == no_team()) { + out.terms.status = FriendlyQuoteStatus::invalid_opponent; + return out; + } + + out.terms.planner_count = g.memory.u8(kFriendlyPlanCount); + out.terms.home_team = manager_home ? no_team() : opponent; + out.terms.away_team = manager_home ? opponent : no_team(); + out.terms.opponent_manager = national_opponent_manager(g, owner, opponent); + out.terms.payer_manager = manager_home ? owner.manager : out.terms.opponent_manager; + const auto own = team_average(g, no_team(), 0xff, &rand); + const auto opposing = team_average(g, opponent, 0xff, &rand); + out.own_rating = own.value; + out.opponent_rating = opposing.value; + const uint32_t combined = uint32_t(out.own_rating + out.opponent_rating) * 1000; + out.terms.cost = int32_t((uint64_t(combined) * (combined / 13000) / 7000) * 1000); + out.terms.status = FriendlyQuoteStatus::quoted; + out.watcom_seed_after = rand.seed(); + out.watcom_calls_after = rand.calls(); + return out; +} + +bool same_national_friendly_quote(const NationalFriendlyQuote& supplied, + const NationalFriendlyQuote& fresh) { + const auto& a = supplied.terms; + const auto& b = fresh.terms; + if (supplied.watcom_calls_after < supplied.watcom_calls_before || + fresh.watcom_calls_after < fresh.watcom_calls_before) return false; + return supplied.owner == fresh.owner && a.status == FriendlyQuoteStatus::quoted && + fresh.watcom_seed_before == supplied.watcom_seed_before && + fresh.watcom_seed_after == supplied.watcom_seed_after && + fresh.watcom_calls_after - fresh.watcom_calls_before == + supplied.watcom_calls_after - supplied.watcom_calls_before && + supplied.own_rating == fresh.own_rating && supplied.opponent_rating == fresh.opponent_rating && + a.manager == b.manager && a.opponent == b.opponent && a.manager_team == b.manager_team && + a.manager_home == b.manager_home && a.home_team == b.home_team && a.away_team == b.away_team && + a.payer_manager == b.payer_manager && a.opponent_manager == b.opponent_manager && + a.cost == b.cost && a.planner_count == b.planner_count; +} + +bool same_friendly_quote(const FriendlyBookingQuote& left, const FriendlyBookingQuote& right) { + return left.status == FriendlyQuoteStatus::quoted && right.status == FriendlyQuoteStatus::quoted && + left.manager == right.manager && left.opponent == right.opponent && + left.manager_team == right.manager_team && left.manager_home == right.manager_home && + left.home_team == right.home_team && left.away_team == right.away_team && + left.payer_manager == right.payer_manager && left.opponent_manager == right.opponent_manager && + left.cost == right.cost && + left.planner_count == right.planner_count; +} + +FriendlyDateStatus friendly_date_fields_unchecked(const ModernState& g, + const FriendlyBookingQuote& quote, + uint16_t day) { + if (quote.status != FriendlyQuoteStatus::quoted) return FriendlyDateStatus::invalid_quote; + if (day >= 0x16e || !g.memory.has(::bmh::layout::DaysIntoSeason)) return FriendlyDateStatus::invalid_date; + // DaysIntoSeason (today); g.memory keeps only the value of the loaded savegame + if (int(day) <= g.season_day()) return FriendlyDateStatus::current_or_past; + // A friendly on the next July 1 is never dispatched: TurnDriver emits the + // season-end desk before preparing that day's competitions (is_season_end). + // CalendarCell likewise stops its calendar loop at the next July 1. The + // leap-year June 30 at season_day 365 remains playable; the same index in a + // regular year is already the next season boundary. + const uint32_t absolute_day = g.season_start + day; + if (absolute_day > 0 && modern::month_code(absolute_day) == 7 && + modern::month_code(absolute_day - 1) != 7) + return FriendlyDateStatus::invalid_date; + const uint32_t calendar_at = kCalendar + uint32_t(day) * 2; + if (!g.memory.has(calendar_at + 1) || !g.memory.has(kFriendlyDays + 0x3b) || + !g.memory.has(kFriendlyTeams + 0x77)) return FriendlyDateStatus::invalid_date; + const uint16_t calendar_word = g.memory.u16(calendar_at); + // DayConflict applies this gate to the selected day as well as its neighbors. + // Calendar class bits alone (0x40/0x100/0x1c0) do not authorize a choice; only the + // transient UI projection bit 15 can make such a word pass. This API never invents it. + if (calendar_word != 0 && calendar_word != 0x4001 && (calendar_word & 0x8000) == 0) + return FriendlyDateStatus::unavailable; + // The saved count is a byte and Max adds two. Refuse malformed values that + // would wrap rather than charging the manager and corrupting the planner counter. + if (quote.planner_count > 253) return FriendlyDateStatus::plan_full; + + // CalendarCell tests the selected day and neighbors with DayConflict. Its temporary + // calendar eligibility bit 15 is UI-local and absent from the saved ModernState, so only + // unambiguous empty/0x4001 neighbors are accepted here. + for (int probe = std::max(0, int(day) - 1); probe <= std::min(0x16d, int(day) + 1); ++probe) { + const uint32_t probe_at = kCalendar + uint32_t(probe) * 2; + if (!g.memory.has(probe_at + 1)) return FriendlyDateStatus::invalid_date; + if (probe != day) { + const uint16_t neighbor_word = g.memory.u16(probe_at); + if (neighbor_word != 0 && neighbor_word != 0x4001) return FriendlyDateStatus::unavailable; + } + for (size_t i = 0; i < kFriendlyPlanEntries; ++i) { + if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != uint16_t(probe)) continue; + const uint32_t teams_at = kFriendlyTeams + uint32_t(i) * 4; + const int first = int16_t(g.memory.u16(teams_at)); + const int second = int16_t(g.memory.u16(teams_at + 2)); + if (first == quote.manager_team || second == quote.manager_team || + first == quote.opponent || second == quote.opponent || + first == no_team() || second == no_team()) return FriendlyDateStatus::unavailable; + } + } + size_t insertion = 0; + size_t used_entries = 0; + for (size_t i = 0; i < kFriendlyPlanEntries; ++i) + if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != 0) ++used_entries; + while (insertion < kFriendlyPlanEntries) { + const uint16_t planned_day = g.memory.u16(kFriendlyDays + uint32_t(insertion) * 2); + if (planned_day == 0 || planned_day >= day) break; + ++insertion; + } + // The original insertion would overwrite the last slot if all 30 were occupied. + // Refuse that case rather than silently dropping a previously booked fixture. + if (insertion == kFriendlyPlanEntries || used_entries == kFriendlyPlanEntries) + return FriendlyDateStatus::plan_full; + return (calendar_word & 0x01c0) != 0 ? FriendlyDateStatus::available_with_calendar_event + : FriendlyDateStatus::available; +} + +FriendlyDateStatus friendly_date_unchecked(const ModernState& g, const FriendlyBookingQuote& quote, + uint16_t day) { + if (!same_friendly_quote(quote, make_friendly_quote(g, quote.manager, quote.opponent, + quote.manager_home))) + return FriendlyDateStatus::invalid_quote; + return friendly_date_fields_unchecked(g, quote, day); +} + +} // namespace + +FriendlyBookingQuote quote_friendly_match(const ModernState& g, int manager, int opponent, + bool manager_home) { + return make_friendly_quote(g, manager, opponent, manager_home); +} + +NationalFriendlyQuote quote_national_friendly_match(const ModernState& g, + const NationalFriendlyOwner& owner, int opponent, bool manager_home, WatcomRandom& rand) { + WatcomRandom staged = rand; + NationalFriendlyQuote result = make_national_friendly_quote(g, owner, opponent, + manager_home, staged); + if (result.terms.status == FriendlyQuoteStatus::quoted) rand = staged; + return result; +} + +NationalFriendlyQuote preview_national_friendly_match(const ModernState& g, + const NationalFriendlyOwner& owner, int opponent, bool manager_home, + const WatcomRandom& rand) { + WatcomRandom staged = rand; + return make_national_friendly_quote(g, owner, opponent, manager_home, staged); +} + +FriendlyDateStatus national_friendly_match_date_status(const ModernState& g, + const NationalFriendlyQuote& quote, const NationalFriendlyOwner& owner, + const WatcomRandom& rand, uint16_t season_day) { + if (quote.owner != owner || owner.menu_kind != 6 || owner.runtime_team != no_team() || + owner.manager < 0 || size_t(owner.manager) >= g.manager_teams.size() || + g.manager_teams[size_t(owner.manager)] != no_team() || + rand.seed() != quote.watcom_seed_after || rand.calls() != quote.watcom_calls_after) + return FriendlyDateStatus::invalid_quote; + WatcomRandom verify(quote.watcom_seed_before); + const NationalFriendlyQuote fresh = make_national_friendly_quote(g, owner, + quote.terms.opponent, quote.terms.manager_home, verify); + if (!same_national_friendly_quote(quote, fresh)) return FriendlyDateStatus::invalid_quote; + return friendly_date_fields_unchecked(g, quote.terms, season_day); +} + +NationalFriendlyBookingResult book_national_friendly_match(ModernState& g, + const NationalFriendlyBookingRequest& request, const WatcomRandom& watcom, + GameRandom& game_random) { + NationalFriendlyBookingResult out; + const auto& quote = request.quote; + if (quote.terms.status != FriendlyQuoteStatus::quoted || quote.owner != request.owner || + watcom.seed() != quote.watcom_seed_after || watcom.calls() != quote.watcom_calls_after) { + out.status = quote.terms.status == FriendlyQuoteStatus::invalid_manager + ? FriendlyBookingStatus::invalid_manager + : quote.terms.status == FriendlyQuoteStatus::invalid_opponent + ? FriendlyBookingStatus::invalid_opponent + : quote.terms.status == FriendlyQuoteStatus::invalid_state + ? FriendlyBookingStatus::invalid_request + : FriendlyBookingStatus::stale_quote; + return out; + } + WatcomRandom verify(quote.watcom_seed_before); + const NationalFriendlyQuote fresh = make_national_friendly_quote(g, request.owner, + quote.terms.opponent, quote.terms.manager_home, verify); + if (!same_national_friendly_quote(quote, fresh)) { + out.status = fresh.terms.status == FriendlyQuoteStatus::invalid_manager + ? FriendlyBookingStatus::invalid_manager + : fresh.terms.status == FriendlyQuoteStatus::invalid_opponent + ? FriendlyBookingStatus::invalid_opponent + : FriendlyBookingStatus::stale_quote; + return out; + } + static_cast(out) = quote.terms; + + ModernState staged = g; + const FriendlyDateStatus date_status = friendly_date_fields_unchecked( + staged, quote.terms, request.season_day); + if (date_status == FriendlyDateStatus::current_or_past || + date_status == FriendlyDateStatus::invalid_date) { + out.status = FriendlyBookingStatus::invalid_date; + return out; + } + if (date_status == FriendlyDateStatus::plan_full) { + out.status = FriendlyBookingStatus::plan_full; + return out; + } + if (date_status != FriendlyDateStatus::available && + date_status != FriendlyDateStatus::available_with_calendar_event) { + out.status = date_status == FriendlyDateStatus::invalid_quote + ? FriendlyBookingStatus::stale_quote + : FriendlyBookingStatus::date_unavailable; + return out; + } + if (out.opponent_manager >= 0 && out.opponent_manager != out.manager) { + if (!request.accept_opponent) { + out.status = FriendlyBookingStatus::opponent_declined; + return out; + } + if (request.consenting_manager != out.opponent_manager) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + } + if (out.payer_manager >= 0) { + if (!request.accept_cost) { + out.status = FriendlyBookingStatus::declined; + return out; + } + if (request.approving_manager != out.payer_manager) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + if (out.cost < 0 || !modern::book_money(staged, out.payer_manager, out.cost, false, true)) { + out.status = FriendlyBookingStatus::insufficient_funds; + return out; + } + } + + size_t insertion = 0; + while (insertion < kFriendlyPlanEntries) { + const uint16_t planned_day = staged.memory.u16(kFriendlyDays + uint32_t(insertion) * 2); + if (planned_day == 0 || planned_day >= request.season_day) break; + ++insertion; + } + if (insertion == kFriendlyPlanEntries) { + out.status = FriendlyBookingStatus::plan_full; + return out; + } + for (size_t i = kFriendlyPlanEntries - 1; i > insertion; --i) { + staged.memory.set16(kFriendlyDays + uint32_t(i) * 2, + staged.memory.u16(kFriendlyDays + uint32_t(i - 1) * 2)); + staged.memory.set32(kFriendlyTeams + uint32_t(i) * 4, + staged.memory.u32(kFriendlyTeams + uint32_t(i - 1) * 4)); + } + staged.memory.set16(kFriendlyDays + uint32_t(insertion) * 2, request.season_day); + staged.memory.set16(kFriendlyTeams + uint32_t(insertion) * 4, uint16_t(out.home_team)); + staged.memory.set16(kFriendlyTeams + uint32_t(insertion) * 4 + 2, uint16_t(out.away_team)); + const uint32_t calendar_at = kCalendar + uint32_t(request.season_day) * 2; + staged.memory.set16(calendar_at, uint16_t(staged.memory.u16(calendar_at) | 0x4001)); + staged.memory.set8(kFriendlyPlanCount, + uint8_t(staged.memory.u8(kFriendlyPlanCount) + 2)); + + GameRandom staged_game = game_random; + out.national_bonus_awarded = staged_game.range(0x3c, 0x5a) < quote.opponent_rating; + if (out.national_bonus_awarded) { + const size_t record_byte = size_t(out.manager) * kRecordSize + 0x210; + if (record_byte >= staged.manager_records.size()) { + out.status = FriendlyBookingStatus::invalid_manager; + out.national_bonus_awarded = false; + return out; + } + staged.manager_records[record_byte] = uint8_t(staged.manager_records[record_byte] + 1); + } + out.status = FriendlyBookingStatus::booked; + g = std::move(staged); + game_random = staged_game; + return out; +} + +FriendlyDateStatus friendly_match_date_status(const ModernState& g, + const FriendlyBookingQuote& quote, + uint16_t season_day) { + return friendly_date_unchecked(g, quote, season_day); +} + +FriendlyBookingResult book_friendly_match(ModernState& g, const FriendlyBookingRequest& request) { + FriendlyBookingResult out; + const FriendlyBookingQuote fresh = make_friendly_quote(g, request.quote.manager, + request.quote.opponent, + request.quote.manager_home); + if (!same_friendly_quote(request.quote, fresh)) { + out.status = request.quote.status == FriendlyQuoteStatus::invalid_manager + ? FriendlyBookingStatus::invalid_manager + : request.quote.status == FriendlyQuoteStatus::invalid_opponent + ? FriendlyBookingStatus::invalid_opponent + : request.quote.status == FriendlyQuoteStatus::invalid_state + ? FriendlyBookingStatus::invalid_request + : FriendlyBookingStatus::stale_quote; + return out; + } + static_cast(out) = fresh; + const FriendlyDateStatus date_status = friendly_date_unchecked(g, fresh, request.season_day); + if (date_status == FriendlyDateStatus::current_or_past || + date_status == FriendlyDateStatus::invalid_date) { + out.status = FriendlyBookingStatus::invalid_date; + return out; + } + if (date_status == FriendlyDateStatus::plan_full) { + out.status = FriendlyBookingStatus::plan_full; + return out; + } + if (date_status != FriendlyDateStatus::available && + date_status != FriendlyDateStatus::available_with_calendar_event) { + out.status = date_status == FriendlyDateStatus::invalid_quote + ? FriendlyBookingStatus::stale_quote + : FriendlyBookingStatus::date_unavailable; + return out; + } + + if (out.opponent_manager >= 0 && out.opponent_manager != out.manager) { + if (!request.accept_opponent) { + out.status = FriendlyBookingStatus::opponent_declined; + return out; + } + if (request.consenting_manager != out.opponent_manager) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + } + + const int payer = out.payer_manager; + if (payer >= 0) { + if (!request.accept_cost) { + out.status = FriendlyBookingStatus::declined; + return out; + } + if (request.approving_manager != payer) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + if (out.cost < 0 || !modern::book_money(g, payer, out.cost, false, true)) { + out.status = FriendlyBookingStatus::insufficient_funds; + return out; + } + } + + size_t insertion = 0; + while (insertion < kFriendlyPlanEntries) { + const uint16_t planned_day = g.memory.u16(kFriendlyDays + uint32_t(insertion) * 2); + if (planned_day == 0 || planned_day >= request.season_day) break; + ++insertion; + } + for (size_t i = kFriendlyPlanEntries - 1; i > insertion; --i) { + g.memory.set16(kFriendlyDays + uint32_t(i) * 2, + g.memory.u16(kFriendlyDays + uint32_t(i - 1) * 2)); + const uint32_t dest = kFriendlyTeams + uint32_t(i) * 4; + const uint32_t src = kFriendlyTeams + uint32_t(i - 1) * 4; + g.memory.set32(dest, g.memory.u32(src)); + } + const uint32_t day_at = kFriendlyDays + uint32_t(insertion) * 2; + const uint32_t teams_at = kFriendlyTeams + uint32_t(insertion) * 4; + g.memory.set16(day_at, request.season_day); + g.memory.set16(teams_at, uint16_t(out.home_team)); + g.memory.set16(teams_at + 2, uint16_t(out.away_team)); + const uint32_t calendar_at = kCalendar + uint32_t(request.season_day) * 2; + g.memory.set16(calendar_at, uint16_t(g.memory.u16(calendar_at) | 0x4001)); + g.memory.set8(kFriendlyPlanCount, uint8_t(g.memory.u8(kFriendlyPlanCount) + 2)); + + out.status = FriendlyBookingStatus::booked; + return out; +} + +void configure_training_camp_data(ModernState& g, const LeImage& exe) { + auto prices = g.training_camp_base_prices; + auto quality = g.training_camp_quality; + for (size_t resort = 0; resort < prices.size(); ++resort) { + prices[resort] = std::bit_cast(exe.u32(::bmh::layout::DeskActions_ConfigureTrainingCampData_RuntimeField2 + uint32_t(resort * 4))); + if (prices[resort] < 0) throw FormatError("training camp: negative resort base price"); + for (size_t grade = 0; grade < quality[resort].size(); ++grade) { + const uint8_t value = exe.u8(::bmh::layout::DeskActions_ConfigureTrainingCampData_RuntimeField + uint32_t(resort * 4 + grade)); + if (value < 1 || value > 5) throw FormatError("training camp: resort quality outside 1..5"); + quality[resort][grade] = value; + } + } + g.training_camp_base_prices = prices; + g.training_camp_quality = quality; +} + +int32_t training_camp_price(const ModernState& g, int manager, int resort) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || resort < 0 || resort >= kTrainingCampResorts) + throw FormatError("training camp: invalid manager or resort"); + const int team = int8_t(g.manager_records.at(size_t(manager) * kRecordSize + kTeam)); + return g.training_camp_base_prices[size_t(resort)] + team_average(g, team, 0xff).players * 5000; +} + +bool set_training_camp_focus(ModernState& g, int manager, const std::array& focus) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size() || + std::any_of(focus.begin(), focus.end(), [](uint8_t v) { return v > 15; }) || + focus[3] != uint8_t(15 - (unsigned(focus[0]) + focus[1] + focus[2]) / 3)) return false; + std::copy(focus.begin(), focus.end(), g.manager_records.begin() + size_t(manager) * kRecordSize + kFocus); + return true; +} + +TransferActionResult list_manager_player(ModernState& g, int manager, int squad_row, WatcomRandom& rand, + MinuteReport& report) { + TransferActionResult out; + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) { + out.status = TransferActionStatus::invalid_manager; + return out; + } + const SquadRange range = squad_range(g.manager_teams[size_t(manager)]); + if (squad_row < 0 || size_t(squad_row) >= range.count) return out; + const int slot = int(range.first) + squad_row; + const int player = g.squad_slots.at(size_t(slot)) & 0xfff; + if (player == 0xfff) { + out.status = TransferActionStatus::invalid_player; + return out; + } + if (!modern::list_transfer_player(g, slot, rand, report)) { + out.status = report.unsupported ? TransferActionStatus::invalid_request : TransferActionStatus::blocked_by_board; + return out; + } + out.status = TransferActionStatus::accepted; + out.player = player; + // The transfer-list slot follows the new pool slot. The engine uses 40 entries + // for the normal list; entries 40-43 are reserved for matchday approaches. + for (int i = 0; i < 40; ++i) + if ((g.squad_slots.at(0xb70u + size_t(i)) & 0xfff) == player) { out.list_entry = i; break; } + return out; +} + +namespace { + +TransferActionResult submit_transfer_bid_impl(ModernState& g, const TransferBidRequest& request, + WatcomRandom& rand, const HumanBuyerSaleHooks* source_hooks, MinuteReport* source_report) { + TransferActionResult out; + if (source_report && source_report->unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + if (request.manager < 0 || size_t(request.manager) >= g.manager_teams.size()) { + out.status = TransferActionStatus::invalid_manager; + return out; + } + if (request.list_entry < 0 || request.list_entry >= 40 || request.player < 0 || request.fee <= 0 || request.annual_salary <= 0 || + request.contract_years < 1 || request.contract_years > 4) return out; + const uint32_t entry = ::bmh::layout::EditorListUnsigned + uint32_t(request.list_entry) * 0x58; + const int player = g.squad_slots.at(0xb70u + size_t(request.list_entry)) & 0xfff; + if (player == 0xfff) { + out.status = TransferActionStatus::invalid_player; + return out; + } + if (player != request.player) { + out.status = TransferActionStatus::invalid_request; + return out; + } + const uint16_t seller_word = g.memory.u16(entry + 8); + if (seller_word != 0xffff && (seller_word & 0x7fff) == uint16_t(g.manager_teams[size_t(request.manager)])) return out; + const size_t rec = size_t(request.manager) * kRecordSize; + const int32_t balance = rd32(g.manager_records, rec + 0x314); + const int32_t credit = rd32(g.manager_records, rec + 0x31c); + if (int64_t(balance) + credit < request.fee) { + out.status = TransferActionStatus::blocked_by_board; + out.player = player; + return out; + } + const int buyer = g.manager_teams[size_t(request.manager)]; + const SquadRange buyer_range = squad_range(buyer); + if (modern::squad_count(g, buyer, 3) >= int(buyer_range.count) - 1) { + out.status = TransferActionStatus::no_squad_room; + out.player = player; + return out; + } + const uint16_t team = uint16_t(buyer); + for (int b = 0; b < 4; ++b) + if (g.memory.u16(entry + uint32_t(b) * 2) == team) { + out.status = TransferActionStatus::pending; + out.player = player; + return out; + } + int bid = 0; + while (bid < 4 && g.memory.u16(entry + uint32_t(bid) * 2) != 0xffff) bid++; + if (bid == 4) { + out.status = TransferActionStatus::blocked_by_board; + return out; + } + const uint32_t fee_base = (g.memory.u32(entry + 0x2c) / 10000) * 0x30d4; + const uint32_t salary_base = ((uint32_t((request.contract_years - 1) * 20 + 100) * g.memory.u32(entry + 0x30)) / 10000) * 100; + if (fee_base == 0 || salary_base == 0) { + out.status = TransferActionStatus::offer_too_low; + out.player = player; + return out; + } + const uint32_t fee_pct = uint32_t(uint64_t(uint32_t(request.fee)) * 100 / fee_base); + const uint32_t salary_pct = uint32_t(uint64_t(uint32_t(request.annual_salary)) * 100 / salary_base); + const int seller = seller_word == 0xffff ? -1 : int(seller_word & 0x7fff); + const int seller_manager = seller < 0 ? -1 : g.manager_of(seller); + // This opt-in adapter starts only after the existing ordinary bid quote + // qualifies. It ports the exact SettleHumanBuyerSale/Fail settlement and direct + // caller tail; the earlier SubmitTransferBidSourceHumanBuyer ProjectTransferOfferList/GameMode/W negotiation itself + // remains the existing approximation and is not claimed as Source parity. + const bool source_direct_candidate = source_hooks && seller_manager < 0 && + fee_pct >= 110 && salary_pct >= g.memory.u8(entry + 0x55); + if (source_direct_candidate) { + if (request.list_entry >= 40 || seller < 0 || (seller >= league_clubs() && seller != 0x0fff) || seller == buyer || + request.manager < 0 || size_t(request.manager) >= g.manager_teams.size() || + !g.memory.has(::bmh::layout::ActiveManager) || g.memory.u8(::bmh::layout::ActiveManager) != request.manager || + source_hooks->direct_mode != HumanBuyerSaleDirectMode::ordinary_ai_purchase || + (g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2) && g.memory.u8(::bmh::layout::DeskActions_EditorFail_RuntimeField2) != 0) || + (source_hooks->allocator_gate != HumanBuyerSaleAllocatorGate::zero && + source_hooks->allocator_gate != HumanBuyerSaleAllocatorGate::blocked) || + !source_hooks->notice || source_hooks->before_accounts || + source_hooks->after_paid_accounts || buyer_range.count != 24) { + if (source_report) source_report->fail("SubmitTransferBidSourceHumanBuyer: unsupported human-buyer direct sale runtime/context"); + out.status = TransferActionStatus::unsupported; + out.player = player; + return out; + } + } + if (uint64_t(uint32_t(request.fee)) * 100 / fee_base < uint32_t(rand.range(0x5a, 100)) || + uint64_t(uint32_t(request.annual_salary)) * 100 / salary_base < g.memory.u8(entry + 0x55)) { + out.status = TransferActionStatus::offer_too_low; + out.player = player; + return out; + } + const uint32_t checked_fee_pct = uint32_t(uint64_t(uint32_t(request.fee)) * 100 / fee_base); + const uint32_t checked_salary_pct = uint32_t(uint64_t(uint32_t(request.annual_salary)) * 100 / salary_base); + g.memory.set16(entry + uint32_t(bid) * 2, team); + g.memory.set32(entry + 0x1c + uint32_t(bid) * 4, uint32_t(request.fee)); + g.memory.set32(entry + 0x0c + uint32_t(bid) * 4, uint32_t(request.annual_salary)); + g.memory.set8(entry + 0x34 + uint32_t(bid), uint8_t(request.contract_years * 12)); + for (size_t i = 0; i < request.bonuses.size(); ++i) + g.memory.set8(entry + 0x38 + uint32_t(bid) * 7 + uint32_t(i), uint8_t(std::min(request.bonuses[i], 100))); + out.status = TransferActionStatus::pending; + out.player = player; + out.list_entry = request.list_entry; + out.fee = request.fee; + out.annual_salary = request.annual_salary; + if (seller_manager < 0 && checked_fee_pct >= 110 && checked_salary_pct >= g.memory.u8(entry + 0x55)) { + if (source_direct_candidate) { + HumanBuyerSaleRequest sale; + sale.list_entry = request.list_entry; + sale.bid_slot = bid; + sale.list_address = entry; + sale.source_pool_slot = 0xb70u + size_t(request.list_entry); + sale.expected_seller = seller; + sale.expected_buyer = buyer; + sale.expected_active_manager = request.manager; + sale.raw_offer_slot = -1; + if (!source_report) { + out.status = TransferActionStatus::unsupported; + return out; + } + HumanBuyerSaleHooks direct_hooks = *source_hooks; + direct_hooks.before_accounts = [&](const ModernState& state, const HumanBuyerSaleRequest& context) { + // SubmitTransferBidSourceHumanBuyer enters with the active buyer and presents Original DeskActions_SubmitTransferBidImpl_ExecutableField + // before SettleHumanBuyerSale. This runs only after the shared preflight succeeds. + direct_hooks.notice(state, {request.manager, context.list_entry, -1, + ::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField, message_text(state, ::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField), 0x80}); + }; + const HumanBuyerSaleResult settled = modern::settle_human_buyer_sale(g, sale, direct_hooks, rand, *source_report); + if (source_report->unsupported || settled.status == HumanBuyerSaleStatus::unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + // SubmitTransferBidSourceHumanBuyer's ordinary-list tail. No blanket bid-row or pool cleanup: + // ReleasePlayer owns matching-pool removal on an actual move. + // OpenTransferEditor established DeskActions_EditorFail_RuntimeField2=0 in the unsaved runtime before this + // ordinary AI-seller branch. Do not synthesize transient EXE globals + // in Native memory; a present marker was validated above. + // Actual EXE VA1c447/1c7c5 clears a WORD at CareerSession_BeginFriendlyOpponentTable_ExecutableField2, not a dword. + // Honor an explicitly represented full word without adding BSS. + if (g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2) && g.memory.has(::bmh::layout::DeskActions_SubmitTransferBidImpl_RuntimeField)) + g.memory.set16(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + switch (settled.status) { + case HumanBuyerSaleStatus::moved: out.status = TransferActionStatus::accepted; break; + case HumanBuyerSaleStatus::funds_refused: out.status = TransferActionStatus::insufficient_funds; break; + case HumanBuyerSaleStatus::allocator_blocked: out.status = TransferActionStatus::allocator_blocked; break; + case HumanBuyerSaleStatus::no_room: out.status = TransferActionStatus::no_squad_room; break; + case HumanBuyerSaleStatus::unsupported: out.status = TransferActionStatus::unsupported; break; + } + } else { + MinuteReport legacy_report; + if (modern::accept_transfer_bid_immediately(g, request.list_entry, bid, rand, legacy_report)) + out.status = TransferActionStatus::accepted; + else + out.status = TransferActionStatus::no_squad_room; + } + } + return out; +} + +TransferActionResult submit_transfer_bid_source_impl(ModernState& g, const TransferBidRequest& request, + WatcomRandom& rand, const HumanBuyerSaleHooks& hooks, MinuteReport& report) { + TransferActionResult out; + const auto unsupported = [&](const char* reason) { + report.fail(std::string("SubmitTransferBidSourceHumanBuyer: ") + reason); + out.status = TransferActionStatus::unsupported; + out.player = request.player; + out.list_entry = request.list_entry; + return out; + }; + if (report.unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + if (request.manager < 0 || size_t(request.manager) >= g.manager_teams.size() || + (size_t(request.manager) + 1) * kRecordSize > g.manager_records.size()) { + out.status = TransferActionStatus::invalid_manager; + return out; + } + const bool ordinary_entry = request.list_entry >= 0 && request.list_entry < 40 && + !request.poach && !request.loan_return_entry; + const bool poach_entry = request.list_entry >= 40 && request.list_entry < 44 && + request.poach && !request.loan_return_entry; + const bool return_entry = request.list_entry >= 40 && request.list_entry < 44 && + request.loan_return_entry && !request.poach; + if ((!ordinary_entry && !poach_entry && !return_entry) || + request.player < 0 || request.player >= 0x0fff || + request.fee < 0 || request.annual_salary < 0 || request.contract_years < 1 || request.contract_years > 4 || + std::any_of(request.bonuses.begin(), request.bonuses.end(), [](uint32_t value) { return value > 255; })) { + out.status = TransferActionStatus::invalid_request; + return out; + } + if (return_entry) { + const uint32_t marker_address = ::bmh::layout::OfferSlots + uint32_t(request.list_entry - 40) * 4; + const uint32_t expected_marker = uint32_t(request.player) * 0x400u + uint32_t(request.manager); + if (!g.memory.has(marker_address + 3) || g.memory.u32(marker_address) != expected_marker) { + out.status = TransferActionStatus::invalid_request; + return out; + } + } + + const int buyer = g.manager_teams[size_t(request.manager)]; + const SquadRange buyer_range = squad_range(buyer); + const size_t buyer_record = size_t(request.manager) * kRecordSize; + if (buyer < 0 || buyer >= 90 || buyer_range.count != 24 || + (uint16_t(g.manager_records.at(buyer_record + kTeam)) | + (uint16_t(g.manager_records.at(buyer_record + kTeam + 1)) << 8)) != uint16_t(buyer)) + return unsupported("unsupported ordinary human-buyer record or 24-slot squad"); + + const uint32_t list = ::bmh::layout::EditorListUnsigned + uint32_t(request.list_entry) * 0x58; + const size_t expected_pool_slot = 0xb70u + size_t(request.list_entry); + if (!g.memory.has(list + 0x57) || request.source_slot < 0 || + size_t(request.source_slot) != expected_pool_slot || size_t(request.source_slot) >= g.squad_slots.size()) + return unsupported("missing or mismatched explicit ordinary Source pool slot"); + const int player = int(g.squad_slots[size_t(request.source_slot)] & 0x0fff); + if (player == 0x0fff || player != request.player || + int(g.squad_slots[0xb70u + size_t(request.list_entry)] & 0x0fff) != player) + return unsupported("ordinary Source list/player identity mismatch"); + + if (!g.memory.has(::bmh::layout::ActiveManager) || g.memory.u8(::bmh::layout::ActiveManager) != request.manager || + !g.memory.has(::bmh::layout::GameMode) || (g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2) && g.memory.u8(::bmh::layout::DeskActions_EditorFail_RuntimeField2) != 0) || + hooks.direct_mode != HumanBuyerSaleDirectMode::ordinary_ai_purchase || !hooks.notice) + return unsupported("missing ordinary-entry, active-manager, mode, or notice ownership"); + const uint8_t career_mode = g.memory.u8(::bmh::layout::GameMode); + if (career_mode < 1 || career_mode > 3) + return unsupported("unsupported saved career negotiation mode"); + + const uint16_t seller_word = g.memory.u16(list + 8); + const int seller = int(seller_word & 0x7fff); + if (seller_word == 0xffff || seller == buyer) + return unsupported("invalid ordinary seller identity"); + // Seller words name runtime squad owners (SlotTeam), not club-name + // offsets. The four foreign leagues are already runtime clubs90..137; + // season initialization can reorder SSC Neapel within that range. + // SquadRange4: clubs0..89 have24 slots, clubs90..137 have16. The + // ordinary settlement already removes players using that actual range. + // Higher club IDs have no ordinary squad; do not invent their settlement + // or let ReleasePlayer reach its missing-player/internal-error21 boundary. + if (seller != 0x0fff && seller >= league_clubs()) { + report.fail(kOrdinarySellerBoundary); + out.status = TransferActionStatus::unsupported; + out.player = player; out.list_entry = request.list_entry; + return out; + } + const int seller_manager = seller == 0x0fff ? -1 : g.manager_of(seller); + if (seller_manager >= 4 || seller_manager == request.manager) + return unsupported("unsupported seller manager identity"); + if (request.loan && seller == 0x0fff) + return unsupported("Fail/DayStepRest2: free-agent loan return destination is not represented"); + + const auto source_notice = [&](uint32_t address, std::string message, uint16_t flags) { + hooks.notice(g, {request.manager, request.list_entry, -1, address, std::move(message), flags}); + }; + if (request.fee == 0 || request.annual_salary == 0) { + source_notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_TextPointer, message_text(g, ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_TextPointer), 0x40); + out.status = TransferActionStatus::rejected; + out.player = player; out.list_entry = request.list_entry; + return out; + } + const uint32_t team = uint32_t(buyer); + int bid_slot = -1; + for (int slot = 0; slot < 4; ++slot) { + const uint16_t bidder = g.memory.u16(list + uint32_t(slot) * 2); + if (bidder == uint16_t(team)) { + if (bid_slot >= 0) return unsupported("duplicate own buyer bid words"); + bid_slot = slot; + } + } + + const auto apply_editor_values = [&](int slot, uint32_t fee) { + const uint32_t b = uint32_t(slot); + g.memory.set32(list + 0x1c + b * 4, fee); + g.memory.set32(list + 0x0c + b * 4, uint32_t(request.annual_salary)); + g.memory.set8(list + 0x34 + b, uint8_t(request.contract_years * 12) | + uint8_t(request.loan ? 0x80 : 0)); + for (size_t n = 0; n < request.bonuses.size(); ++n) + g.memory.set8(list + 0x38 + b * 7 + uint32_t(n), uint8_t(request.bonuses[n])); + }; + const uint32_t available = uint32_t(rd32(g.manager_records, buyer_record + 0x314)) + + uint32_t(rd32(g.manager_records, buyer_record + 0x31c)); + + // SubmitTransferBidSourceHumanBuyer is reached only for a new buyer word. An existing own offer is + // an editor-only update: preserve its row, apply the changed fields, and do + // not consume any qualification W values a second time. + if (bid_slot >= 0) { + const uint8_t old_term = g.memory.u8(list + 0x34 + uint32_t(bid_slot)); + if ((old_term & 0x80) != uint8_t(request.loan ? 0x80 : 0)) + return unsupported("OpenTransferEditor: changing the loan class of an existing offer is unsupported"); + const uint32_t fee = uint32_t(request.fee) <= available ? uint32_t(request.fee) : 0u; + apply_editor_values(bid_slot, fee); + if (fee == 0) { + source_notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField, message_text(g, ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField), 0x40); + out.status = TransferActionStatus::insufficient_funds; + } else { + out.status = TransferActionStatus::pending; + } + out.player = player; out.list_entry = request.list_entry; + out.fee = int32_t(fee); out.annual_salary = request.annual_salary; + return out; + } + + for (int slot = 0; slot < 4; ++slot) { + if (g.memory.u16(list + uint32_t(slot) * 2) == 0xffff) { bid_slot = slot; break; } + } + if (bid_slot < 0) { + out.status = TransferActionStatus::blocked_by_board; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + // OpenTransferEditor checks funds before entering SubmitTransferBidSourceHumanBuyer. Keep that parent gate + // ahead of the inner capacity check and qualification RNG. + if (uint32_t(request.fee) > available) { + source_notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField, message_text(g, ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField), 0x40); + out.status = TransferActionStatus::insufficient_funds; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + // SubmitTransferBidSourceHumanBuyer uses equality here. Weekly decisions can legitimately move this + // count past23 while outgoing loans still reserve places (M139/#114). + // Reject the higher counts too: accepting more players would consume the + // returning player's slot and stop the next season. Keep Source's notice, + // signed manager byte and refusal before bid writes or qualification RNG. + if (!g.memory.has(::bmh::layout::DeskActions_Unsupported_RuntimeFieldUnsigned + uint32_t(request.manager))) + return unsupported("missing bbcc8 buyer-manager capacity byte"); + const int capacity = int(int8_t(g.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeFieldUnsigned + uint32_t(request.manager)))) + + int(uint8_t(modern::squad_count(g, buyer, 3))); + if (capacity >= 0x17) { + source_notice(::bmh::layout::DeskActions_Unsupported_ExecutableField, message_text(g, ::bmh::layout::DeskActions_Unsupported_ExecutableField), 0x40); + out.status = TransferActionStatus::no_squad_room; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + apply_editor_values(bid_slot, uint32_t(request.fee)); + g.memory.set16(list + uint32_t(bid_slot) * 2, uint16_t(team)); + const TransferBidRatingRequest rating_request{request.source_slot, request.list_entry, bid_slot, + buyer, player}; + const TransferBidRating rating = modern::rate_transfer_bid_source(g, rating_request, rand, report); + if (!rating.supported || report.unsupported) { + out.status = TransferActionStatus::unsupported; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + // Poaching (rows 40..43) is decided at once: a refusal is final (rejected), the player + // is easier to convince in mode III (W90..96 instead of W120..190), a human seller is + // asked (PresentManagerDialog: yes 0xa0, no 0) and the club refuses less often (W92..98). + if (request.poach && !hooks.confirm) return unsupported("missing poaching PresentManagerDialog question owner"); + uint32_t salary_threshold = 0; + switch (career_mode) { + case 1: salary_threshold = 100; break; + case 2: salary_threshold = uint32_t(rand.range(90, 110)); break; + case 3: salary_threshold = uint32_t(request.poach ? rand.range(90, 96) : rand.range(120, 190)); break; + default: return unsupported("unsupported saved career negotiation mode"); + } + if (rating.salary_pct < salary_threshold) { + source_notice(::bmh::layout::DeskActions_Unsupported_ExecutableField3, g.player_name(player) + message_text(g, ::bmh::layout::DeskActions_Unsupported_ExecutableField3), 0x80); + out.status = request.poach ? TransferActionStatus::rejected : TransferActionStatus::pending; + out.player = player; out.list_entry = request.list_entry; + out.fee = request.fee; out.annual_salary = request.annual_salary; + return out; + } + + uint32_t fee_pct = career_mode == 3 ? rating.fee_pct : 200u; + if (request.poach && seller_manager >= 0) { + // "Sind Sie mit dem Angebot von einverstanden?" to the selling manager + const std::string question = message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer) + + format_amount(g, std::bit_cast(g.memory.u32(list + 0x1c + uint32_t(bid_slot) * 4))) + + message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer2); + fee_pct = hooks.confirm(g, seller_manager, question) ? 0xa0u : 0u; + } + bool dfb_fee = false; + if (uint32_t(rand.range(92, request.poach ? 98 : 150)) >= fee_pct) { + if (request.poach) { + // The club refuses; as the player agreed, the DFB sets the fee to 188 % of his + // market value (AddToSquad with 0xbc) and the buyer may pay it (PresentManagerDialog). + uint32_t fee = 0, salary = 0; + const bool loan = (g.memory.u8(list + 0x34 + uint32_t(bid_slot)) & 0x80) != 0; + modern::market_value(g, request.source_slot, loan ? 1 : 0, 0xbc, fee, salary, 1, 0, rand); + g.memory.set32(list + 0x1c + uint32_t(bid_slot) * 4, fee); + const std::string question = message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer4) + format_amount(g, std::bit_cast(fee)) + + message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer5); + out.player = player; out.list_entry = request.list_entry; + out.fee = std::bit_cast(fee); out.annual_salary = request.annual_salary; + if (!hooks.confirm(g, request.manager, question)) { + out.status = TransferActionStatus::rejected; + return out; + } + dfb_fee = true; + } else { + if (seller_word == 0x0fff) { + source_notice(::bmh::layout::DeskActions_Unsupported_ExecutableField2, message_text(g, ::bmh::layout::DeskActions_Unsupported_ExecutableField2), 0x80); + } else { + source_notice(::bmh::layout::DeskActions_Unsupported_TextPointer3, g.club_name(seller) + message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer3), 0x80); + } + out.status = TransferActionStatus::pending; + out.player = player; out.list_entry = request.list_entry; + out.fee = request.fee; out.annual_salary = request.annual_salary; + return out; + } + } + + out.player = player; out.list_entry = request.list_entry; + out.fee = std::bit_cast(g.memory.u32(list + 0x1c + uint32_t(bid_slot) * 4)); + out.annual_salary = request.annual_salary; + if ((hooks.allocator_gate != HumanBuyerSaleAllocatorGate::zero && + hooks.allocator_gate != HumanBuyerSaleAllocatorGate::blocked) || + hooks.before_accounts || hooks.after_paid_accounts) { + return unsupported("unknown direct allocator gate or caller-owned settlement hook"); + } + HumanBuyerSaleRequest sale; + sale.list_entry = request.list_entry; + sale.bid_slot = bid_slot; + sale.list_address = list; + sale.source_pool_slot = size_t(request.source_slot); + sale.expected_seller = seller; + sale.expected_buyer = buyer; + sale.expected_active_manager = request.manager; + sale.raw_offer_slot = -1; + sale.poach = request.poach; + sale.loan_return_entry = request.loan_return_entry; + HumanBuyerSaleHooks direct_hooks = hooks; + // "Sie einigen sich mit dem Spieler..." (DeskActions_SubmitTransferBidImpl_ExecutableField); a poached player: "Ihr erstes Angebot wird + // angenommen!" (DeskActions_SubmitTransferOfferEditorSource_ExecutableField); after the DFB fee the original goes to the accounts directly + const uint32_t accepted_text = request.poach ? ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_ExecutableField : ::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField; + if (!dfb_fee) + direct_hooks.before_accounts = [&](const ModernState& state, const HumanBuyerSaleRequest& context) { + direct_hooks.notice(state, {request.manager, context.list_entry, -1, + accepted_text, message_text(state, accepted_text), 0x80}); + }; + const HumanBuyerSaleResult settled = modern::settle_human_buyer_sale(g, sale, direct_hooks, rand, report); + if (report.unsupported || settled.status == HumanBuyerSaleStatus::unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + + // SubmitTransferBidSourceHumanBuyer's normal direct tail: matching-pool removal is performed only + // by ReleasePlayer on a move; clear only already represented transient storage. + if (g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2) && g.memory.has(::bmh::layout::DeskActions_SubmitTransferBidImpl_RuntimeField)) g.memory.set16(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + if (g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2)) g.memory.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2, 0); + switch (settled.status) { + case HumanBuyerSaleStatus::moved: out.status = TransferActionStatus::accepted; break; + case HumanBuyerSaleStatus::funds_refused: out.status = TransferActionStatus::insufficient_funds; break; + case HumanBuyerSaleStatus::allocator_blocked: out.status = TransferActionStatus::allocator_blocked; break; + case HumanBuyerSaleStatus::no_room: out.status = TransferActionStatus::no_squad_room; break; + case HumanBuyerSaleStatus::unsupported: out.status = TransferActionStatus::unsupported; break; + } + return out; +} + +} // namespace + +std::optional transfer_market_snapshot_preview( + const ModernState& g,int manager,int runtime_club,int index) { + if(manager<0||manager>=4||size_t(manager)>=g.manager_teams.size()|| + g.manager_teams[size_t(manager)]!=runtime_club||runtime_club<0||runtime_club>=league_clubs()||index<0||index>=12) + return std::nullopt; + const auto owner=squad_range(runtime_club); + int count=0,ordinal=-1; + for(int i=0;i<12;++i) { + const uint32_t id=::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(i)*2,who=::bmh::layout::ClubInfo_FormatError_RuntimeField2+uint32_t(i); + if(!g.memory.has(id)||!g.memory.has(id+1)||!g.memory.has(who))return std::nullopt; + if(g.memory.u16(id)!=0x0fff&&g.memory.u8(who)==manager) { + if(i==index)ordinal=count; + ++count; + } + } + if(ordinal<0||size_t(count)>owner.count)return std::nullopt; + const int player=g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(index)*2); + if(player<0||size_t(player)>=g.players.size()||player==0x0fff)return std::nullopt; + for(int i=0;i<12;++i)if(i!=index&&g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(i)*2)==player)return std::nullopt; + const uint32_t board=::bmh::layout::ClubInfo_FormatError_RuntimeField+uint32_t(index)*0x58; + for(uint32_t n=0;n<0x58;++n)if(!g.memory.has(board+n))return std::nullopt; + int borrower=-1; + for(int i=0;i<200;++i) { + const uint32_t at=::bmh::layout::Career_RemoveJoinLoans_RuntimeField+uint32_t(i)*4; + if(!g.memory.has(at)||!g.memory.has(at+3))return std::nullopt; + const uint32_t loan=g.memory.u32(at); + if(!loan||int(loan&0xfff)!=player)continue; + // Require exactly one genuine ledger and its authenticated owner. + if(borrower!=-1||int(loan>>12&0x3ff)!=runtime_club)return std::nullopt; + borrower=int(loan>>22&0x3ff); + if(borrower<0||borrower>=league_clubs()||borrower==runtime_club)return std::nullopt; + } + if(borrower<0)return std::nullopt; + const auto range=squad_range(borrower); + if(!range.count||range.first+range.count>g.squad_slots.size())return std::nullopt; + int source=-1; + for(size_t row=0;row=g.manager_teams.size()||request.manager>=4|| + !g.memory.has(::bmh::layout::ActiveManager)||g.memory.u8(::bmh::layout::ActiveManager)!=request.manager) + return unsupported("market preview: stale active manager"); + const size_t record=size_t(request.manager)*kRecordSize; + if(record+0x318>g.manager_records.size()||request.runtime_club<0|| + g.manager_teams[size_t(request.manager)]!=request.runtime_club) + return unsupported("market preview: stale runtime club/record"); + const uint16_t native_team=uint16_t(g.manager_records[record+0x290])| + uint16_t(uint16_t(g.manager_records[record+0x291])<<8); + if(native_team!=request.runtime_club) + return unsupported("market preview: Native record disagrees with runtime club"); + if(request.source_slot<0||size_t(request.source_slot)>=g.squad_slots.size()|| + request.expected_player<0||request.expected_player==0x0fff|| + size_t(request.expected_player)>=g.players.size()|| + (g.squad_slots[size_t(request.source_slot)]&0x0fff)!=request.expected_player) + return unsupported("market preview: stale Source player/slot"); + if(request.purchase) { + if(request.snapshot_index!=-1)return unsupported("market preview: snapshot is not a purchase row"); + if(request.source_slot=int(transfer_list_slot())+40) + return unsupported("market preview: purchase is not an ordinary market row"); + const uint32_t seller_at=::bmh::layout::EditorList+uint32_t(request.source_slot-int(transfer_list_slot()))*0x58+8; + if(!g.memory.has(seller_at)||!g.memory.has(seller_at+1)) + return unsupported("market preview: missing Source seller word"); + const uint16_t raw=g.memory.u16(seller_at); + // Existing UI's -1 identity represents only an observed FULLWORD FFFF. + // Canonical0FFF remains4095; a high-bit seller flag is masked by18c22. + const int seller=raw==0xffff?-1:int(raw&0x7fff); + if(request.seller!=seller)return unsupported("market preview: stale Source seller"); + } else if(request.snapshot_index>=0) { + const auto identity=modern::transfer_market_snapshot_preview(g,request.manager,request.runtime_club,request.snapshot_index); + if(!identity||identity->source_slot!=request.source_slot||identity->player!=request.expected_player||request.seller!=request.runtime_club) + return unsupported("market preview: stale lender snapshot/borrower identity"); + // Intentional correction: Original19c1c/TransferMarketScreen uses the displayed tail + // row, which can be empty0FFF. Value the authenticated borrower slot + // with the unchanged42307 formula; do not synthesize a Native slot. + } else { + if(request.snapshot_index!=-1)return unsupported("market preview: invalid snapshot index"); + if(request.seller!=request.runtime_club||request.runtime_club>=league_clubs()) + return unsupported("market preview: outgoing club is not an ordinary owned squad"); + const auto range=squad_range(request.runtime_club); + if(range.count==0||range.first+range.count>g.squad_slots.size()|| + !g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+23)||!g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2+11)) + return unsupported("market preview: incomplete outgoing/loan roster"); + size_t borrowed=0; + for(uint32_t n=0;n<12;++n) { + if(!g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+n*2)||!g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+n*2+1)||!g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2+n)) + return unsupported("market preview: incomplete outgoing loan ownership"); + if(g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+n*2)!=0x0fff&&g.memory.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2+n)==request.manager)++borrowed; + } + if(borrowed>range.count||size_t(request.source_slot)=range.first+range.count-borrowed) + return unsupported("market preview: outgoing Source slot is not an ordinary roster row"); + } + // EXE raw23922 (MarketValue): NEG32; 2393a IDIV ecx(10000), + // 2393c IMUL32, 23959 ADD32. Salary is computed before42307's loan quarter. + modern::market_value(g,request.source_slot,int(request.loan),100,result.fee,result.salary,1,0,rand); + const uint32_t sign=request.purchase?0u-result.fee:result.fee; + const int32_t quotient=std::bit_cast(sign)/10000; + const uint32_t rounded=uint32_t(quotient)*10000u; + result.delta=std::bit_cast(rounded); + result.projected_balance=std::bit_cast(std::bit_cast(rd32(g.manager_records,record+0x314))+rounded); + result.supported=true; + return result; +} + +namespace { +constexpr uint32_t kEditorList=::bmh::layout::EditorList; +uint32_t editor_list(const TransferOfferEditorRequest& r){return kEditorList+uint32_t(r.list_entry)*0x58;} +int editor_slot(const ModernState& g,const TransferOfferEditorRequest& r) { + const uint32_t at=editor_list(r); + for(int slot=0;slot<4;++slot) { + const uint16_t buyer=g.memory.u16(at+uint32_t(slot)*2); + if(buyer==0xffff||buyer==r.runtime_club)return slot; + } + return -1; +} +std::string editor_identity(const ModernState& g,const TransferOfferEditorRequest& r) { + if(r.manager<0||r.manager>=4||size_t(r.manager)>=g.manager_teams.size()|| + !g.memory.has(::bmh::layout::ActiveManager)||g.memory.u8(::bmh::layout::ActiveManager)!=r.manager|| + g.manager_teams[size_t(r.manager)]!=r.runtime_club||r.runtime_club<0||r.runtime_club>=league_clubs()) + return "OpenTransferEditor: stale ordinary manager/team"; + const size_t record=size_t(r.manager)*kRecordSize; + if(record+kRecordSize>g.manager_records.size()|| + (uint16_t(g.manager_records[record+0x290])|uint16_t(uint16_t(g.manager_records[record+0x291])<<8))!=r.runtime_club) + return "OpenTransferEditor: inconsistent Native buyer record"; + // ordinary rows 0..39; poaching uses the special rows 40..43 (and only those) + const bool ordinary_entry = r.list_entry >= 0 && r.list_entry < 40 && !r.poach && !r.loan_return_entry; + const bool poach_entry = r.list_entry >= 40 && r.list_entry < 44 && r.poach && !r.loan_return_entry; + const bool return_entry = r.list_entry >= 40 && r.list_entry < 44 && r.loan_return_entry && !r.poach; + if((!ordinary_entry&&!poach_entry&&!return_entry)||r.source_slot!=int(transfer_list_slot())+r.list_entry|| + size_t(r.source_slot)>=g.squad_slots.size()||r.expected_player<0||r.expected_player>=0x0fff|| + size_t(r.expected_player)>=g.players.size()|| + int(g.squad_slots[size_t(r.source_slot)]&0x0fff)!=r.expected_player) + return "OpenTransferEditor: stale ordinary Source slot/player"; + if(return_entry) { + const uint32_t marker=::bmh::layout::OfferSlots+uint32_t(r.list_entry-40)*4; + if(!g.memory.has(marker+3)||g.memory.u32(marker)!=uint32_t(r.expected_player)*0x400u+uint32_t(r.manager)) + return "OpenTransferEditor: stale DayStepRest2 return-offer marker"; + } + const uint32_t list=editor_list(r); + for(uint32_t n=0;n<0x58;++n)if(!g.memory.has(list+n))return "OpenTransferEditor: missing Native list row"; + if(g.memory.u16(list+8)!=r.expected_seller_word)return "OpenTransferEditor: stale raw seller word"; + const int seller=int(r.expected_seller_word&0x7fff); + if(r.expected_seller_word==0xffff||seller==r.runtime_club) + return "OpenTransferEditor: targeted/invalid seller is outside ordinary editor"; + if(seller!=0x0fff&&seller>=league_clubs())return kOrdinarySellerBoundary; + // OpenTransferEditor: the original refuses a loan from a free agent (seller 0x0fff) with the message + // DeskActionsRuntimeField6 (SDLFlushEvents3) - a rule of the game, not a gap: the code names it + if(r.loan&&r.expected_seller_word==0x0fff)return "free_agent_loan_refused"; + const int seller_manager=seller==0x0fff?-1:g.manager_of(seller); + if(seller_manager>=0) { + const auto range=squad_range(seller);bool found=false; + if(range.first+range.count>g.squad_slots.size())return "OpenTransferEditor: incomplete human seller squad"; + for(size_t n=range.first;n3) + return "OpenTransferEditor: missing supported Native negotiation mode"; + return {}; +} +TransferOfferEditorState editor_fail(TransferOfferEditorState state,const std::string& reason) { + state.supported=false;state.reason=reason;return state; +} +TransferOfferInputProfile editor_profile(uint32_t minimum,uint32_t encoded_max,uint32_t first, + uint32_t multiplier,uint32_t increment,uint32_t initial,uint32_t text) { + TransferOfferInputProfile p;p.minimum=minimum;p.currency=(encoded_max&0x40000000u)!=0; + uint32_t maximum=encoded_max^(p.currency?0x40000000u:0u); + const auto signed32=[](uint32_t n){return std::bit_cast(n);}; + if(signed32(maximum)99999999)initial=99999999; + if(signed32(maximum)>99999999)maximum=99999999; + if(signed32(maximum)=0&&g.memory.u16(list+uint32_t(state.bid_slot)*2)==state.request.runtime_club; + state.editable=state.bid_slot>=0; + if(state.editable) { + const uint32_t bid=uint32_t(state.bid_slot); + state.fee=g.memory.u32(list+0x1c+bid*4);state.salary=g.memory.u32(list+0x0c+bid*4); + state.term=g.memory.u8(list+0x34+bid);state.years=uint8_t((int(state.term&127)-1)/12+1); + for(uint32_t n=0;n<7;++n)state.bonuses[n]=g.memory.u8(list+0x38+bid*7+n); + } else {state.years=1;state.term=0;state.fee=0;state.salary=0;state.bonuses.fill(0);} + // RateTransferBidSource: explicit byte years and Source32 unsigned products. + const uint8_t year_index=state.editable?uint8_t((int(state.term&127)-1)/12):uint8_t(1); + state.asking_fee=(g.memory.u32(list+0x2c)/10000u)*12500u; + if(state.editable&&(state.term&128))state.asking_fee>>=2; + state.asking_salary=((uint32_t(year_index)*20u+100u)*g.memory.u32(list+0x30)/10000u)*100u; + state.money_profiles[0]=editor_profile(0,state.asking_fee*2u|0x40000000u,0xffffffffu,10000,0,state.asking_fee,::bmh::layout::DeskActions_EditorProject_RuntimeField); + state.money_profiles[1]=editor_profile(0,0x40030d40u,0xffffffffu,500,0,state.asking_salary,::bmh::layout::DeskActions_EditorProject_ExecutableField2); + state.mode3_profiles[0]=editor_profile(1,state.request.loan?2u:4u,1,1,1,state.years,::bmh::layout::DeskActions_EditorProject_ExecutableField); + for(size_t n=0;n<7;++n) { + const uint32_t first=n<3?1u:50u-uint32_t(n-3)*10u; + state.mode3_profiles[n+1]=editor_profile(0,n<3?20u:1000u,first,1,first,state.bonuses[n],::bmh::layout::Contracts_Out_ExecutableField4+uint32_t(n)*4); + } + for(uint32_t n=0;n<0x58;++n)state.native_entry[n]=g.memory.u8(list+n); +} +std::string editor_current(const ModernState& g,const TransferOfferEditorState& state) { + if(!state.supported||state.closed)return "OpenTransferEditor: editor is unsupported or closed"; + if(const auto reason=editor_identity(g,state.request);!reason.empty())return reason; + if(g.memory.u8(::bmh::layout::GameMode)!=state.mode)return "OpenTransferEditor: Native mode changed during editor"; + const uint32_t list=editor_list(state.request); + for(uint32_t n=0;n<0x58;++n)if(g.memory.u8(list+n)!=state.native_entry[n])return "OpenTransferEditor: stale Native editor entry"; + return {}; +} +void editor_initialize_empty_bid(ModernState& g,TransferOfferEditorState& state) { + if(state.initialized_empty_bid||state.bid_slot<0)return; + const uint32_t list=editor_list(state.request),bid=uint32_t(state.bid_slot); + if(g.memory.u16(list+bid*2)!=0xffff)return; + // BacLocalFirstEmptySelectionOnlyBuyer..1bac7 / local1c: the first empty selection only. Buyer and + // all seven stale bonus bytes remain unchanged; loan is the original action. + g.memory.set32(list+0x0c+bid*4,0);g.memory.set32(list+0x1c+bid*4,0); + g.memory.set8(list+0x34+bid,uint8_t(24|(state.request.loan?128:0))); + state.initialized_empty_bid=true; +} +void editor_quote(const ModernState& g,TransferOfferEditorState& state,WatcomRandom& rand) { + uint32_t fee=0,salary=0; + modern::market_value(g,state.request.source_slot,int(state.quote_loan),state.percent,fee,salary,state.years,0,rand); + // OpenBMH deviates from the original: uses the supported transfer-fee arithmetic and designated set-piece fields. +// supported rule profile MakeRequest ->PlayerCardMarketValue ->422f4; unsigned Source32 fee addition. + state.quoted_fee=((fee+(fee>>2))/10000u)*10000u; + state.quoted_salary=(salary/100u)*100u; +} +} // namespace + +TransferOfferEditorState open_transfer_offer_editor_source(ModernState& g, + const TransferOfferEditorRequest& request,GameRandom& game,WatcomRandom& rand) { + TransferOfferEditorState state;state.request=request;state.quote_loan=request.loan; + if(const auto reason=editor_identity(g,request);!reason.empty())return editor_fail(state,reason); + state.bid_slot=editor_slot(g,request); + if(state.bid_slot!=request.expected_bid_slot)return editor_fail(state,"OpenTransferEditor: stale first free/own raw bid slot"); + if(!g.memory.has(::bmh::layout::CareerSession_Invalid_RuntimeField2)||!g.memory.has(::bmh::layout::DeskActions_OpenTransferOfferEditorSource_RuntimeField)) + return editor_fail(state,"OpenTransferEditor: missing saved opening G seed"); + state.mode=g.memory.u8(::bmh::layout::GameMode);state.supported=true; + // InitializesOrdinaryEntryMarkerAbsenceStaysAbsent initializes the ordinary entry marker; absence stays absent. + if(g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2))g.memory.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2,0); + const uint32_t seed=g.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2); + // CareerSession_Save_RuntimeField is the Source transient G state, not a serialized Native field. + // GameRandom owns it; mirror only when an explicit memory block exists. + const bool mirror_g=g.memory.has(::bmh::layout::CareerSession_Save_RuntimeField)&&g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField); + game.set_seed(std::bit_cast(seed)); + if(mirror_g)g.memory.set32(::bmh::layout::CareerSession_Save_RuntimeField,seed); + state.percent=uint8_t(game.range(92,108)); + if(mirror_g)g.memory.set32(::bmh::layout::CareerSession_Save_RuntimeField,std::bit_cast(game.seed())); + editor_initialize_empty_bid(g,state); + editor_project(g,state); + state.player_info_selection=modern::transfer_offer_player_info_selection_source(g,state); + editor_quote(g,state,rand);return state; +} +TransferOfferEditorState edit_transfer_offer_editor_source(ModernState& g, + const TransferOfferEditorState& previous,const TransferOfferEditorEvent& event,GameRandom& game,WatcomRandom& rand) { + (void)game;auto state=previous; + if(const auto reason=editor_current(g,state);!reason.empty())return editor_fail(state,reason); + if(event.field==TransferOfferEditorField::toggle_quote_loan) { + state.quote_loan=!state.quote_loan;editor_quote(g,state,rand);return state; + } + const unsigned field=unsigned(event.field); + if(!state.editable||field>unsigned(TransferOfferEditorField::bonus6))return editor_fail(state,"OpenTransferEditor: noneditable field"); + if(field>=2&&state.mode!=3)return editor_fail(state,"OpenTransferEditor: years/bonuses require Native mode3"); + if(!event.accepted) { + if(field<2)editor_quote(g,state,rand); + return state; + } + const auto& profile=field<2?state.money_profiles[field]:state.mode3_profiles[field-2]; + if(!profile.supported||event.valueprofile.maximum) + return editor_fail(state,"OpenTransferEditor: calculator value outside Source field bounds"); + const uint32_t list=editor_list(state.request),bid=uint32_t(state.bid_slot); + if(field==0)g.memory.set32(list+0x1c+bid*4,event.value); + else if(field==1)g.memory.set32(list+0x0c+bid*4,event.value); + else if(field==2)g.memory.set8(list+0x34+bid,uint8_t(event.value*12u)|(state.request.loan?128:0)); + else {const unsigned bonus=field-3;g.memory.set8(list+0x38+bid*7+bonus,uint8_t(bonus<3?event.value:event.value/5u));} + editor_project(g,state);editor_quote(g,state,rand);return state; +} +TransferOfferEditorState resume_transfer_offer_team_info_source(ModernState& g, + const TransferOfferEditorState& previous,WatcomRandom& rand) { + auto state=previous; + if(!state.supported||state.closed)return editor_fail(state,"OpenTransferEditor: closed TeamInfo owner"); + if(const auto reason=editor_identity(g,state.request);!reason.empty())return editor_fail(state,reason); + if(g.memory.u8(::bmh::layout::GameMode)!=state.mode)return editor_fail(state,"OpenTransferEditor: TeamInfo changed Native negotiation mode"); + // 1c18b rescans first FFFF/own. local1c may still be zero after an + // existing-own/read-only opening; initialize the first empty choice once. + // This resume never repeats CareerSession_Save_RuntimeField reset or the opening G draw. + state.bid_slot=editor_slot(g,state.request); + state.request.expected_bid_slot=state.bid_slot; + editor_initialize_empty_bid(g,state); + editor_project(g,state);editor_quote(g,state,rand); + return state; +} +ClubPlayerDetailSelection transfer_offer_player_info_selection_source(const ModernState& g, + const TransferOfferEditorState& owner) { + if(const auto reason=editor_current(g,owner);!reason.empty())throw std::invalid_argument(reason); + const auto& r=owner.request; + const int seller=r.expected_seller_word&0x7fff; + // Literal68ca0 count and Nationalcoach special owner4, independently of + // buyer identity and of any retained pending offer for the same player. + if(!g.memory.has(::bmh::layout::ManagerCount))throw std::invalid_argument("OpenTransferEditor: missing Source manager count"); + const size_t count=g.memory.u8(::bmh::layout::ManagerCount); + if(count>4||count>g.manager_teams.size())throw std::invalid_argument("OpenTransferEditor: invalid Source manager count"); + int manager=-1; + for(size_t m=0;mg.manager_records.size())throw std::invalid_argument("OpenTransferEditor: missing Nationalcoach owner4"); + if((uint16_t(g.manager_records[at])|(uint16_t(g.manager_records[at+1])<<8))==seller)manager=4; + } + if(owner.player_info_selection) { + const auto& retained=*owner.player_info_selection; + if(retained.player_id!=r.expected_player|| + (manager<0&&!r.poach&&(retained.origin!=ClubPlayerDetailOrigin::market_pool||retained.market_pool_slot!=r.source_slot))|| + ((manager>=0||r.poach)&&(retained.origin!=ClubPlayerDetailOrigin::squad||retained.runtime_team!=seller))) + throw std::invalid_argument("OpenTransferEditor: retained local40 owner changed"); + (void)modern::club_player_detail_context(g,retained); + return retained; + } + ClubPlayerDetailSelection selection; + selection.player_id=r.expected_player; + // A poaching row (40..43) is outside the market pool the detail screen knows; its + // player is shown at his club instead, like a managed seller's player. + if(manager<0&&!r.poach&&!r.loan_return_entry) { + selection.origin=ClubPlayerDetailOrigin::market_pool; + selection.market_pool_slot=r.source_slot; + selection.rendered_row=r.list_entry; // Logical entry only; Native identity is explicit. + } else { + const auto range=squad_range(seller); + if(range.first+range.count>g.squad_slots.size())throw std::invalid_argument("OpenTransferEditor: truncated seller squad"); + size_t row=0; + while(rowavailable) { + notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField);if(own_exists){g.memory.set32(list+0x1c+bid*4,0);editor_project(g,state);} + action.status=TransferActionStatus::insufficient_funds;return result; + } + if(own_exists) {action.status=TransferActionStatus::pending;action.fee=std::bit_cast(state.fee);action.annual_salary=std::bit_cast(state.salary);return result;} + // Editor writes may retain Source stale bonuses outside their interactive + // controls; qualifier reads all7 as bytes, without a <=100 clamp. + TransferBidRequest request;request.manager=state.request.manager;request.list_entry=state.request.list_entry; + request.player=state.request.expected_player;request.source_slot=state.request.source_slot; + request.fee=int32_t(state.fee);request.annual_salary=int32_t(state.salary);request.contract_years=state.years; + request.poach=state.request.poach;request.loan=state.request.loan; + request.loan_return_entry=state.request.loan_return_entry; + for(size_t n=0;n<7;++n)request.bonuses[n]=state.bonuses[n]; + bool entered_accounts=false;const auto present=hooks.notice;auto owned=hooks; + owned.notice=[present,&entered_accounts](const ModernState& staged,const HumanBuyerSaleNotice& event){ + if(event.source_text_address==::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField||event.source_text_address==::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_ExecutableField)entered_accounts=true; + present(staged,event); + }; + action=modern::submit_transfer_bid_source_human_buyer(g,request,rand,owned,report); + if(report.unsupported||action.status==TransferActionStatus::unsupported)return unsupported(report.reason.empty()?"OpenTransferEditor: unsupported Source qualification/settlement":report.reason); + if(entered_accounts)state.closed=true; + // a poaching offer is decided at once: SubmitTransferBidSourceHumanBuyer never leaves a pending row behind + else if(state.request.poach&&action.status!=TransferActionStatus::insufficient_funds&& + action.status!=TransferActionStatus::no_squad_room)state.closed=true; + else if(action.status==TransferActionStatus::pending){editor_project(g,state);editor_quote(g,state,rand);} + return result; +} + +TransferActionResult submit_transfer_bid(ModernState& g, const TransferBidRequest& request, WatcomRandom& rand) { + return submit_transfer_bid_impl(g, request, rand, nullptr, nullptr); +} + +TransferActionResult submit_transfer_bid_source_human_buyer(ModernState& g, + const TransferBidRequest& request, WatcomRandom& rand, + const HumanBuyerSaleHooks& hooks, MinuteReport& report) { + return submit_transfer_bid_source_impl(g, request, rand, hooks, report); +} + +TrainingCampBookingBlock training_camp_booking_block(const ModernState& g, int manager) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size()) + return TrainingCampBookingBlock::invalid_request; + const uint8_t stays = g.manager_records.at(size_t(manager) * kRecordSize + kStays); + if (stays & 0x80) return TrainingCampBookingBlock::booked_this_week; + if ((stays & 0x7f) >= 3) return TrainingCampBookingBlock::visit_limit; + return TrainingCampBookingBlock::none; +} + +bool book_training_camp(ModernState& g, int manager, int resort, WatcomRandom& rand) { + if (resort < 0 || resort >= kTrainingCampResorts || + modern::training_camp_booking_block(g, manager) != TrainingCampBookingBlock::none) return false; + const int32_t cost = modern::training_camp_price(g, manager, resort); + if (!modern::book_money(g, manager, cost, false)) return false; + const size_t rec = size_t(manager) * kRecordSize; + wr32(g.manager_records, rec + kCampExpenses, rd32(g.manager_records, rec + kCampExpenses) + cost); + uint8_t& stays = g.manager_records.at(rec + kStays); + stays = uint8_t((stays + 1) | 0x80); + modern::training_camp_effect(g, manager, resort, rand); + return true; +} + +void training_camp_effect(ModernState& g, int manager, int resort, WatcomRandom& rand) { + const size_t rec = size_t(manager) * kRecordSize; + const int team = int8_t(g.manager_records.at(rec + kTeam)); + const auto& grade = g.training_camp_quality[size_t(resort)]; + + // Morale (bits 0-5) + 12 * grade * 20 %, clamped to 0..0x2f (ClampSignedWord with a word + // sum of the sign extended byte); the flag bits 6-7 are kept. + uint8_t& tm = g.team_morale.at(size_t(team)); + const int morale = std::clamp(int(tm & 0x3f) + int(int16_t(scaled(12, grade[2]))), 0, 0x2f); + tm = uint8_t((tm & 0xc0) | uint8_t(morale)); + + // The maximum step of each value: the slider times its grade (stored as a byte), the + // familiarity one 7 lower, the freshness one from the fourth grade. + int8_t delta[5]; + for (int u = 0; u < 4; u++) + delta[u] = int8_t(scaled(g.manager_records.at(rec + kFocus + size_t(u)), grade[kSliderGrade[u]])); + delta[3] = int8_t(delta[3] - 7); + delta[4] = int8_t(scaled(12, grade[3])); + + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t id = g.squad_slots.at(s) & 0x0fff; + if (id == kEmptySlot) continue; + Player& p = g.players.at(id); + uint8_t* board = &g.tactics.at(size_t(manager) * 0x840 + (s - range.first) * 0x58); + // Chance to train: 100 % up to age 29 (raw age 13), then 10 % less per year - + // computed in 8 bits, so from raw age 25 on the value wraps above 100 (always). + const uint8_t age = uint8_t(p.w364 >> 21 & 0x1f); + const uint8_t chance = age < 14 ? 100 : uint8_t(100 - uint8_t((age - 14) * 10)); + int8_t v[5] = {int8_t(p.w35c >> 14 & 0x7f), int8_t(p.w35c >> 7 & 0x7f), int8_t(p.w35c & 0x7f), + int8_t(board[0xf]), int8_t(board[0xe] & 0x3f)}; + for (int i = 0; i < 5; i++) { + const int lo = delta[i] < 0 ? 0 : 8; + if (rand.range(0, 100) <= chance) { + // values below 83..87 (88 in the better resorts 6 and 7) can still improve + const int limit = rand.range(0x53, 0x57) + (resort >= 6 ? 1 : 0); + if (v[i] < limit) { + const int k = rand.range(lo, delta[i] + 8); + v[i] = int8_t(v[i] + int8_t(kStep[k] * kDirection[i])); + } + } + v[i] = std::clamp(v[i], 0, 0x63); // Int8T + } + p.w35c = (p.w35c & 0xffe00000u) | uint32_t(v[0]) << 14 | uint32_t(v[1]) << 7 | uint32_t(v[2]); + board[0xf] = uint8_t(v[3]); + board[0xe] = uint8_t((board[0xe] & 0xc0) | std::min(uint8_t(v[4]), 0x3f)); + } +} + +} // namespace bmh::modern + +namespace bmh::modern { + +namespace { + +constexpr size_t kStockSize = 0x5c; +constexpr size_t kMoney = 0x314, kCredit = 0x31c, kStockBalance = 0x324; + +uint16_t rd16(const std::vector& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); } +void wr16(std::vector& v, size_t o, int x) { + v.at(o) = uint8_t(x); + v.at(o + 1) = uint8_t(x >> 8); +} + +} // namespace + +int max_shares_to_buy(const ModernState& g, int manager, int stock) { + const size_t rec = size_t(manager) * kRecordSize, s = size_t(stock) * kStockSize; + const int price = rd16(g.stocks, s + 0x4e); + int n = (rd32(g.manager_records, rec + kMoney) + rd32(g.manager_records, rec + kCredit)) / price; + const int held = rd16(g.stocks, s + 0x50 + size_t(manager) * 2); + if (n + held > 9999) n = 9999 - held; + return n; +} + +bool buy_shares(ModernState& g, int manager, int stock, int count) { + const size_t rec = size_t(manager) * kRecordSize, s = size_t(stock) * kStockSize; + // the paid amounts of all shares the manager holds (computed when the screen is drawn) + int32_t portfolio = 0; + for (int k = 0; k < kStocks; k++) + if (rd16(g.stocks, size_t(k) * kStockSize + 0x50 + size_t(manager) * 2) != 0) + portfolio += rd32(g.stocks, size_t(k) * kStockSize + 4 + size_t(manager) * 4); + int32_t cost = rd16(g.stocks, s + 0x4e) * count; + if (portfolio + cost >= rd32(g.manager_records, rec + kMoney) / 20) return false; + wr16(g.stocks, s + 0x50 + size_t(manager) * 2, rd16(g.stocks, s + 0x50 + size_t(manager) * 2) + count); + cost += cost * 15 / 1000; + modern::book_money(g, manager, cost, false); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) - cost); + const size_t paid = s + 4 + size_t(manager) * 4; + wr32(g.stocks, paid, rd32(g.stocks, paid) + cost); + return true; +} + +void sell_shares(ModernState& g, int manager, int stock, int count) { + const size_t rec = size_t(manager) * kRecordSize, s = size_t(stock) * kStockSize; + const size_t paid = s + 4 + size_t(manager) * 4, held = s + 0x50 + size_t(manager) * 2; + wr32(g.stocks, paid, int32_t(uint32_t(rd32(g.stocks, paid)) - uint32_t(rd32(g.stocks, paid)) / rd16(g.stocks, held) * uint32_t(count))); + wr16(g.stocks, held, rd16(g.stocks, held) - count); + const int32_t income = count * rd16(g.stocks, s + 0x4e); + modern::book_money(g, manager, -income, true); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) + income); +} + +int stock_tip(ModernState& g, int manager, int stock, WatcomRandom& rand) { + const size_t s = size_t(stock) * kStockSize; + int tip = int(g.stocks.at(s + 0x16)) - 1; + if (g.stocks.at(s + 0x59) < 3) tip = 0; + const int value = int16_t(uint32_t(rd32(g.stocks, s)) / 100); + const int price = rd16(g.stocks, s + 0x4e); + if (price < value - 5) tip++; + if (value + 5 < price) tip--; + if (price < value - 30) tip = 2; + if (value + 30 < price) tip = -2; + tip += 2; + if (rand.range(0, 2) == 0) tip += rand.range(0, 2) * 2 - 2; + tip = std::clamp(tip, 0, 4); + modern::book_money(g, manager, 5000, true, true); + return tip; +} + +} // namespace bmh::modern + +namespace bmh::modern { + +namespace { + +// StadiumPriceTable: base price of the 14 periphery objects. +constexpr int32_t kPeripheryPrice[14] = {2500000, 1700000, 2200000, 1000000, 1100000, 1500000, 280000, + 280000, 280000, 280000, 350000, 350000, 350000, 350000}; +// CareerSession_DispatchStadium_RuntimeField2[object * 5]: construction time in days. +constexpr uint8_t kPeripheryDays[14] = {45, 30, 28, 40, 30, 20, 6, 6, 6, 6, 5, 5, 5, 5}; + +} // namespace + +int construction_price_percent(const ModernState& g, int manager, GameRandom& game) { + game.set_seed(int32_t(g.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + const int r = int16_t(rd16(g.manager_records, size_t(manager) * kRecordSize + 0x8b4)) / 100; + return 100 - game.range(r, r + 5); +} + +int32_t periphery_offer(const ModernState& g, int object, GameRandom& game) { + game.set_seed(int32_t(g.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + for (int i = 0; i < object; i++) game.range(0, 100); + const int percent = game.range(0x55, 0x73); + return kPeripheryPrice[object] * percent / 1000000 * 10000; +} + +bool pay_construction(ModernState& g, int manager, uint32_t price, bool sponsor, WatcomRandom& rand, + const ConstructionNoticeHook& notice) { + const size_t rec = size_t(manager) * kRecordSize; + uint8_t& share = g.manager_records.at(rec + 0x171); + ConstructionNotice details{manager, ConstructionNoticeKind::InsufficientFunds, price, 0, 0}; + if (sponsor && price <= uint32_t(rd32(g.manager_records, rec + kMoney)) && share != 0) { + if (price < uint32_t((share >> 2) & 7) * 0x4f588 + 26000) { + details.kind = ConstructionNoticeKind::SponsorContribution; + details.percent = int((share >> 5) + 3) * 10; + details.subsidy = uint32_t(details.percent) * price / 100; + } else { + details.kind = ConstructionNoticeKind::SponsorExploited; + const int sponsor_roll = rand.range(2, 4); + details.percent = sponsor_roll * 5; + details.subsidy = price * uint32_t(sponsor_roll) * 5 / 100; + } + price -= details.subsidy; + // PayConstruction waits for the notice while the original share is still live. + if (notice) notice(g, details); + share = 0; + } + const bool paid = modern::book_money(g, manager, int32_t(price), false, true); + if (!paid && notice) { + details.kind = ConstructionNoticeKind::InsufficientFunds; + notice(g, details); + } + return paid; +} + +bool build_periphery(ModernState& g, int manager, int object, uint32_t price, WatcomRandom& rand, + const ConstructionNoticeHook& notice) { + if (!modern::pay_construction(g, manager, price, true, rand, notice)) return false; + g.manager_records.at(size_t(manager) * kRecordSize + 0x1e + size_t(object)) = kPeripheryDays[object]; + return true; +} + +StandBlockOffer prepare_stand_block_offer(uint32_t base_price, int construction_days, WatcomRandom& rand) { + const int percent = rand.range(6, 14); // PrepareStandBlockOffer draws before showing the prompt + const uint32_t offered = uint32_t(uint64_t(base_price) * uint32_t(100 + percent) / 100); + return {percent, base_price, offered, base_price, construction_days, construction_days, + StandBlockOfferDecision::Pending}; +} + +bool resolve_stand_block_offer(StandBlockOffer& offer, bool accept, WatcomRandom& rand) { + if (offer.decision != StandBlockOfferDecision::Pending || offer.percent < 6 || offer.percent > 14 || + offer.construction_days < 0 || offer.construction_days > 255 || offer.base_days != offer.construction_days || + offer.price != offer.base_price || offer.offered_price != + uint32_t(uint64_t(offer.base_price) * uint32_t(100 + offer.percent) / 100)) + return false; + offer.decision = accept ? StandBlockOfferDecision::Accepted : StandBlockOfferDecision::Declined; + if (!accept) return false; + offer.price = offer.offered_price; + offer.construction_days -= rand.range(offer.base_days >> 3, offer.base_days >> 1); + return true; +} + +std::vector stadium_investment_options_source( + const ModernState& g, int manager, StadiumInvestment investment, int construction_percent, + const StadiumInvestmentConstants& constants) { + const size_t choice = size_t(investment); + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size() || choice >= 8 || + construction_percent < 1 || construction_percent > 427 || constants.price[choice] == 0 || + constants.weeks[choice] == 0) + throw FormatError("stadium: invalid investment owner or constants"); + const size_t rec = size_t(manager) * kRecordSize; + if (g.manager_teams[size_t(manager)] < 0 || g.manager_teams[size_t(manager)] == no_team() || + rd16(g.manager_records, rec + kTeam) != g.manager_teams[size_t(manager)]) + throw FormatError("stadium: investment manager club differs from record"); + if (g.manager_records.at(rec + 0x2c + choice) != 0) return {}; + const uint8_t status = g.manager_records.at(rec + 0x3c + choice); + const uint8_t current = status & 7; + const bool binary = choice == 2 || choice == 3; + if ((status & 0xf0) != 0) + throw FormatError("stadium: invalid idle investment level"); + std::vector options; + // ConstructionPricePercent tests the masked terminal level, but its ordinary sprite loop + // starts at the full raw byte. Bit3 cannot manufacture an ordinary tier. + const int count = binary ? (current == 2 ? 0 : 1) : std::max(0, std::min(3, 4 - int(status))); + for (int increment = 1; increment <= count; ++increment) { + // ConstructionPricePercent uses a 32-bit multiplied base/discount before /100. The + // authentic tables fit; reject malformed constants instead of wrapping. + const uint64_t multiplied = uint64_t(constants.price[choice]) * uint32_t(increment) * + uint32_t(construction_percent); + if (multiplied > std::numeric_limits::max()) + throw FormatError("stadium: investment price multiplication overflows Native width"); + const uint32_t price = uint32_t(multiplied) / 100; + if (price == 0 || price > uint32_t(INT32_MAX)) + throw FormatError("stadium: investment price outside Native money range"); + options.push_back({status, current, uint8_t(increment), uint8_t((status + increment) & 7), + price, constants.weeks[choice]}); + } + return options; +} + +bool build_stadium_investment_source(ModernState& g, int manager, StadiumInvestment investment, + int construction_percent, const StadiumInvestmentConstants& constants, + const StadiumInvestmentOption& option, const StandBlockOffer& offer, WatcomRandom& rand, + const ConstructionNoticeHook& notice) { + try { + const auto options = modern::stadium_investment_options_source( + g, manager, investment, construction_percent, constants); + if (std::find(options.begin(), options.end(), option) == options.end() || + offer.base_price != option.base_price || offer.base_days != option.base_weeks || + offer.percent < 6 || offer.percent > 14 || + offer.offered_price != uint32_t(uint64_t(option.base_price) * uint32_t(100 + offer.percent) / 100) || + offer.price > uint32_t(INT32_MAX) || + (offer.decision != StandBlockOfferDecision::Declined && + offer.decision != StandBlockOfferDecision::Accepted) || + (offer.decision == StandBlockOfferDecision::Declined && + (offer.price != option.base_price || offer.construction_days != option.base_weeks)) || + (offer.decision == StandBlockOfferDecision::Accepted && + (offer.price != offer.offered_price || + offer.construction_days > option.base_weeks - (option.base_weeks >> 3) || + offer.construction_days < option.base_weeks - (option.base_weeks >> 1)))) + return false; + } catch (const FormatError&) { + return false; + } + // Validation alone converts FormatError into a neutral rejection. Payment + // and presenters must remain outside that catch so App can roll back a + // failed notice instead of acknowledging it as a consumed funds refusal. + if (!modern::pay_construction(g, manager, offer.price, true, rand, notice)) return false; + const size_t rec = size_t(manager) * kRecordSize; + const size_t choice = size_t(investment); + g.manager_records.at(rec + 0x2c + choice) = uint8_t(offer.construction_days); + uint8_t& status = g.manager_records.at(rec + 0x3c + choice); + status = uint8_t(status | uint8_t(uint8_t(status + option.increment) << 4)); + return true; +} + +} // namespace bmh::modern + +namespace bmh::modern { + +namespace { + +constexpr uint32_t kFundBlock = ::bmh::layout::FundBlock; +constexpr uint32_t kFundSize = 0x1c; +constexpr size_t kAssets = 0x30c, kDeposit = 0x318; + +} // namespace + +int max_fund_units(const ModernState& g, int manager, int fund) { + const size_t rec = size_t(manager) * kRecordSize; + const uint32_t e = kFundBlock + uint32_t(fund) * kFundSize; + const uint32_t price = g.memory.u32(e); + const uint32_t each = price + price / 20; + // (unsigned division as in the original) + int n = int(uint32_t(rd32(g.manager_records, rec + kMoney) + rd32(g.manager_records, rec + kCredit)) / each); + const int room = 10 - g.memory.u16(e + 0x14 + uint32_t(manager) * 2); + return std::min(n, room); +} + +int32_t buy_fund_units(ModernState& g, int manager, int fund, int count, GameRandom& game) { + const size_t rec = size_t(manager) * kRecordSize; + const uint32_t e = kFundBlock + uint32_t(fund) * kFundSize; + const uint32_t held = e + 0x14 + uint32_t(manager) * 2, paid = e + 4 + uint32_t(manager) * 4; + auto add = [&](size_t o, int32_t x) { wr32(g.manager_records, rec + o, rd32(g.manager_records, rec + o) + x); }; + g.memory.set16(held, uint16_t(g.memory.u16(held) + count)); + const int32_t price = int32_t(g.memory.u32(e)); + const int32_t fee = count * price / 20; + add(kAssets, fee); + const int32_t total = count * price + fee; + add(kStockBalance, -total); + modern::book_money(g, manager, total, false); + add(kAssets, count * price / 9); + g.memory.set32(paid, g.memory.u32(paid) + uint32_t(total)); + if (fund == 0) return 0; + const int32_t surcharge = count * game.range(price / 40, price / 10); + add(kAssets, surcharge); + modern::book_money(g, manager, surcharge, true); + return surcharge; +} + +void sell_fund_units(ModernState& g, int manager, int fund, int count) { + const size_t rec = size_t(manager) * kRecordSize; + const uint32_t e = kFundBlock + uint32_t(fund) * kFundSize; + const uint32_t held = e + 0x14 + uint32_t(manager) * 2, paid = e + 4 + uint32_t(manager) * 4; + g.memory.set32(paid, g.memory.u32(paid) - g.memory.u32(paid) / g.memory.u16(held) * uint32_t(count)); + g.memory.set16(held, uint16_t(g.memory.u16(held) - count)); + const int32_t income = count * int32_t(g.memory.u32(e)); + modern::book_money(g, manager, -income, true); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) + income); + wr32(g.manager_records, rec + kAssets, rd32(g.manager_records, rec + kAssets) - income / 9); +} + +void move_to_deposit(ModernState& g, int manager, int32_t amount) { + const size_t rec = size_t(manager) * kRecordSize; + modern::book_money(g, manager, amount, true); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) - amount); + wr32(g.manager_records, rec + kDeposit, rd32(g.manager_records, rec + kDeposit) + amount); +} + +void open_lineup_screen(ModernState& g, int manager) { + uint8_t* rec = &g.manager_records.at(size_t(manager) * 0xb0c); + if ((rec[0xb0a] | rec[0xb0b] << 8) == 0x3253) return; + for (int i = 0; i < 4; i++) rec[0xafc + i] = 0; + rec[0xb08] = 0, rec[0xb09] = 0, rec[0xb0a] = 0x53, rec[0xb0b] = 0x32; +} + +} // namespace bmh::modern + +namespace bmh::modern { + +bool submit_pools_coupon(ModernState& g, int manager, uint32_t stake, + const std::array& tips) { + constexpr size_t kRecord = 0xb0c; + constexpr uint32_t kCoupon = ::bmh::layout::Coupon; + constexpr uint32_t kCouponBytes = 5 * 0x14; + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecord > g.manager_records.size() || + !g.memory.has(kCoupon) || !g.memory.has(kCoupon + kCouponBytes - 1) || + !g.memory.has(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField) || !g.memory.has(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + 43) || + g.memory.u8(::bmh::layout::CareerSession_DispatchToto_RuntimeField) != 11 || + (stake != 0 && (stake < 10'000 || stake > 400'000)) || + std::any_of(tips.begin(), tips.end(), [](uint8_t pick) { return pick > 2; })) + return false; + + const uint32_t at = kCoupon + uint32_t(manager) * 0x14; + g.memory.set32(at, stake); + for (uint32_t i = 0; i < tips.size(); ++i) g.memory.set8(at + 8 + i, tips[i]); + return true; +} + +} // namespace bmh::modern + +namespace bmh::modern { +namespace { +constexpr size_t kAdRecord = 0xb0c; +constexpr size_t kAdPool = 0x8cc; +constexpr size_t kAdContracts = 0xa34; +constexpr size_t kAdContractBytes = 0x0c; +constexpr uint32_t kAdGroupId = ::bmh::layout::AdGroupId; + +uint32_t ad_u32(const std::vector& bytes, size_t at) { + return uint32_t(bytes.at(at)) | uint32_t(bytes.at(at + 1)) << 8 | + uint32_t(bytes.at(at + 2)) << 16 | uint32_t(bytes.at(at + 3)) << 24; +} + +bool ad_replaceable(const std::vector& bytes, size_t at) { + return ad_u32(bytes, at) == 0 || (bytes.at(at + 6) & 0x80) != 0; +} + +struct AdBoardOrder { + std::array keys{}; + std::array slots{}; +}; + +void ad_sort_order(AdBoardOrder& order, int first, int count) { + while (count > 1) { + const uint32_t pivot = order.keys[size_t(first + count / 2)]; + int left = -1; + int right = count; + do { + do { ++left; } while (pivot < order.keys[size_t(first + left)]); + do { --right; } while (order.keys[size_t(first + right)] < pivot); + if (right <= left) break; + std::swap(order.keys[size_t(first + left)], order.keys[size_t(first + right)]); + std::swap(order.slots[size_t(first + left)], order.slots[size_t(first + right)]); + } while (true); + ad_sort_order(order, first, left); + first += left; + count -= left; + } +} + +AdBoardOrder ad_board_order(const std::vector& records, size_t rec) { + AdBoardOrder order; + for (int slot = 0; slot < 14; ++slot) { + const size_t at = rec + kAdContracts + size_t(slot) * kAdContractBytes; + const uint32_t amount = ad_u32(records, at); + uint32_t key = amount; + if (amount != 0 && (records.at(at + 6) & 0x80) == 0) key += 1'000'000u; + order.keys[size_t(slot)] = key; + order.slots[size_t(slot)] = slot; + } + ad_sort_order(order, 0, 14); + return order; +} + +bool ad_manager_record_valid(const ModernState& g, int manager) { + return manager >= 0 && size_t(manager) < g.manager_teams.size() && + (size_t(manager) + 1) * kAdRecord <= g.manager_records.size(); +} + +bool ad_extension_requires_unsupported_prompt(const std::vector& records, size_t at) { + return (records.at(at + 6) & 0x7f) != 0 && records.at(at + 5) == 0; +} +} // namespace + +AdvertisingOfferList advertising_offers(const ModernState& g, int manager, int display_slot) { + AdvertisingOfferList out; + out.manager = manager; + out.display_slot = display_slot; + if (!ad_manager_record_valid(g, manager)) { + out.status = AdvertisingOfferStatus::invalid_manager; + return out; + } + if (display_slot < 0 || display_slot > 15) { + out.status = AdvertisingOfferStatus::invalid_display_slot; + return out; + } + const size_t rec = size_t(manager) * kAdRecord; + const int pool_group = display_slot < 14 ? 0 : (display_slot == 14 ? 1 : 2); + const int pool_count = pool_group == 2 ? 5 : 10; + const size_t pool = rec + kAdPool + size_t(pool_group) * 0x78; + if (pool + size_t(pool_count) * kAdContractBytes > rec + kAdRecord || + rec + kAdContracts + 16 * kAdContractBytes > g.manager_records.size()) { + out.status = AdvertisingOfferStatus::invalid_state; + return out; + } + out.pool_group = pool_group; + + const AdBoardOrder order = ad_board_order(g.manager_records, rec); + if (display_slot < 14) { + out.contract_slot = order.slots[size_t(display_slot)]; + for (int slot = 0; slot < 14; ++slot) { + const size_t at = rec + kAdContracts + size_t(slot) * kAdContractBytes; + if (ad_replaceable(g.manager_records, at)) ++out.free_boards; + } + } else { + out.contract_slot = display_slot; + } + const size_t target = rec + kAdContracts + size_t(out.contract_slot) * kAdContractBytes; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(target), kAdContractBytes, + out.contract_bytes.begin()); + if (ad_extension_requires_unsupported_prompt(g.manager_records, target)) { + out.status = AdvertisingOfferStatus::unsupported_extension; + } else if (pool_group != 0 && !ad_replaceable(g.manager_records, target)) { + out.status = AdvertisingOfferStatus::unavailable_target; + } else { + out.status = AdvertisingOfferStatus::available; + } + + bool has_offer = false; + const bool selected_target_available = pool_group == 0 || + ad_replaceable(g.manager_records, rec + kAdContracts + size_t(out.contract_slot) * kAdContractBytes); + for (int raw = 0; raw < pool_count; ++raw) { + const size_t at = pool + size_t(raw) * kAdContractBytes; + AdvertisingOfferCandidate candidate; + candidate.raw_slot = raw; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(at), kAdContractBytes, + candidate.bytes.begin()); + candidate.monthly_amount = ad_u32(g.manager_records, at); + candidate.bundle_units = g.manager_records.at(at + 4); + candidate.months = g.manager_records.at(at + 5); + candidate.sponsor_id = g.manager_records.at(at + 7); + candidate.present = candidate.monthly_amount != 0; + has_offer |= candidate.present; + const bool valid_offer = candidate.sponsor_id < 10 && + (pool_group != 0 || (candidate.bundle_units > 0 && candidate.bundle_units <= 14)); + const bool enough_boards = pool_group != 0 || candidate.bundle_units <= out.free_boards; + bool insertion_targets_available = true; + if (pool_group == 0 && candidate.bundle_units <= 14) { + for (int i = 0; i < candidate.bundle_units; ++i) { + const int raw_target = order.slots[size_t(13 - i)]; + const size_t at = rec + kAdContracts + size_t(raw_target) * kAdContractBytes; + if (!ad_replaceable(g.manager_records, at)) insertion_targets_available = false; + } + } + candidate.can_accept = candidate.present && valid_offer && enough_boards && + selected_target_available && insertion_targets_available && + out.status == AdvertisingOfferStatus::available; + out.offers.push_back(candidate); + } + if (out.status == AdvertisingOfferStatus::available && !has_offer) + out.status = AdvertisingOfferStatus::no_offers; + return out; +} + +AdvertisingOfferResult accept_advertising_offer(ModernState& g, + const AdvertisingOfferRequest& request) { + AdvertisingOfferResult result; + result.manager = request.manager; + result.display_slot = request.display_slot; + result.contract_slot = request.contract_slot; + result.raw_slot = request.raw_slot; + if (!ad_manager_record_valid(g, request.manager)) { + result.status = AdvertisingOfferStatus::invalid_manager; + return result; + } + const AdvertisingOfferList view = modern::advertising_offers(g, request.manager, request.display_slot); + if (view.status != AdvertisingOfferStatus::available) { + result.status = view.status; + return result; + } + if (view.contract_slot != request.contract_slot || request.contract_slot < 0 || + request.contract_slot > 15 || request.raw_slot < 0) { + result.status = AdvertisingOfferStatus::invalid_request; + return result; + } + const size_t rec = size_t(request.manager) * kAdRecord; + const size_t target = rec + kAdContracts + size_t(request.contract_slot) * kAdContractBytes; + const auto order = ad_board_order(g.manager_records, rec); + if (request.display_slot < 14 && order.slots[size_t(request.display_slot)] != request.contract_slot) { + result.status = AdvertisingOfferStatus::stale_offer; + return result; + } + if (request.expected_contract != [&] { + std::array bytes{}; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(target), kAdContractBytes, bytes.begin()); + return bytes; + }()) { + result.status = AdvertisingOfferStatus::stale_offer; + return result; + } + + const int pool_group = view.pool_group; + const int pool_count = pool_group == 2 ? 5 : 10; + if (request.raw_slot >= pool_count) { + result.status = AdvertisingOfferStatus::invalid_request; + return result; + } + const size_t pool = rec + kAdPool + size_t(pool_group) * 0x78 + size_t(request.raw_slot) * kAdContractBytes; + std::array offer{}; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(pool), kAdContractBytes, offer.begin()); + if (offer != request.expected_offer || ad_u32(g.manager_records, pool) == 0) { + result.status = AdvertisingOfferStatus::stale_offer; + return result; + } + const uint8_t sponsor = offer[7]; + const uint8_t bundle = offer[4]; + if (sponsor >= 10 || (pool_group == 0 && (bundle == 0 || bundle > 14))) { + result.status = AdvertisingOfferStatus::malformed_offer; + return result; + } + if (pool_group == 0 && bundle > view.free_boards) { + result.status = AdvertisingOfferStatus::insufficient_boards; + return result; + } + if (pool_group == 0 && !g.memory.has(kAdGroupId)) { + result.status = AdvertisingOfferStatus::invalid_state; + return result; + } + + // Prepare all writes in owned bytes first. Source AdBoardOrder sorts descending and + // moves option-marked rows without the +1,000,000 active-contract priority. + std::vector next = g.manager_records; + { + const auto staged_order = ad_board_order(next, rec); + std::array, 14> sorted{}; + for (int i = 0; i < 14; ++i) { + const size_t from = rec + kAdContracts + size_t(staged_order.slots[size_t(i)]) * kAdContractBytes; + std::copy_n(next.begin() + std::ptrdiff_t(from), kAdContractBytes, sorted[size_t(i)].begin()); + } + for (int i = 0; i < 14; ++i) { + const size_t to = rec + kAdContracts + size_t(i) * kAdContractBytes; + std::copy(sorted[size_t(i)].begin(), sorted[size_t(i)].end(), next.begin() + std::ptrdiff_t(to)); + } + } + const size_t sorted_target = rec + kAdContracts + size_t(request.display_slot) * kAdContractBytes; + if (pool_group != 0 && !ad_replaceable(next, sorted_target)) { + result.status = AdvertisingOfferStatus::unavailable_target; + return result; + } + if (ad_extension_requires_unsupported_prompt(next, sorted_target)) { + result.status = AdvertisingOfferStatus::unsupported_extension; + return result; + } + if (pool_group == 0) { + const uint8_t group_id = g.memory.u8(kAdGroupId); + for (int i = 0; i < bundle; ++i) { + const size_t to = rec + kAdContracts + size_t(13 - i) * kAdContractBytes; + if (!ad_replaceable(next, to)) { + result.status = AdvertisingOfferStatus::unavailable_target; + return result; + } + std::copy(offer.begin(), offer.end(), next.begin() + std::ptrdiff_t(to)); + next[to + 4] = group_id; + } + std::vector before_resort = next; + const auto final_order = ad_board_order(before_resort, rec); + std::array, 14> sorted{}; + for (int i = 0; i < 14; ++i) { + const size_t from = rec + kAdContracts + size_t(final_order.slots[size_t(i)]) * kAdContractBytes; + std::copy_n(before_resort.begin() + std::ptrdiff_t(from), kAdContractBytes, sorted[size_t(i)].begin()); + } + for (int i = 0; i < 14; ++i) { + const size_t to = rec + kAdContracts + size_t(i) * kAdContractBytes; + std::copy(sorted[size_t(i)].begin(), sorted[size_t(i)].end(), next.begin() + std::ptrdiff_t(to)); + } + } else { + std::copy(offer.begin(), offer.end(), next.begin() + std::ptrdiff_t(sorted_target)); + } + for (size_t i = 0; i < 4; ++i) next[pool + i] = 0; // Source clears the offer amount only. + + std::copy(next.begin() + std::ptrdiff_t(rec), next.begin() + std::ptrdiff_t(rec + kAdRecord), + g.manager_records.begin() + std::ptrdiff_t(rec)); + if (pool_group == 0) g.memory.set8(kAdGroupId, uint8_t(g.memory.u8(kAdGroupId) + 1)); + result.status = AdvertisingOfferStatus::accepted; + return result; +} + +AdvertisingSpendingView advertising_spending(const ModernState& g, int manager, int target_slot) { + AdvertisingSpendingView view; + view.manager = manager; + view.target_slot = target_slot; + if (!ad_manager_record_valid(g, manager)) return view; + if (target_slot < 16 || target_slot > 18) return view; + const size_t rec = size_t(manager) * kAdRecord; + const size_t field = rec + (target_slot == 16 ? 0x850 : target_slot == 17 ? 0x854 : 0x858); + if (field + 4 > g.manager_records.size() || !g.memory.has(::bmh::layout::ActiveManager) || + int(g.memory.u8(::bmh::layout::ActiveManager)) != manager) return view; + view.current_amount = ad_u32(g.manager_records, field); + view.maximum_amount = target_slot == 16 ? 350000u : 35000u; + if (target_slot == 16) view.delivery_weeks = g.manager_records.at(rec + 0x287); + // BalanceFromGame clamps a legacy current value to the widget maximum; it does + // not make an otherwise available field uneditable. + view.available = target_slot != 16 || view.delivery_weeks == 0; + return view; +} + +AdvertisingSpendingResult set_advertising_spending(ModernState& g, + const AdvertisingSpendingRequest& request, + WatcomRandom& rand) { + AdvertisingSpendingResult result; + const auto reject = [&](AdvertisingSpendingStatus status) { + result.status = status; + return result; + }; + if (!ad_manager_record_valid(g, request.manager) || !g.memory.has(::bmh::layout::ActiveManager) || + int(g.memory.u8(::bmh::layout::ActiveManager)) != request.manager) + return reject(AdvertisingSpendingStatus::invalid_manager); + if (request.target_slot < 16 || request.target_slot > 18) + return reject(AdvertisingSpendingStatus::invalid_target); + const size_t rec = size_t(request.manager) * kAdRecord; + const size_t field = rec + (request.target_slot == 16 ? 0x850 : + request.target_slot == 17 ? 0x854 : 0x858); + if (field + 4 > g.manager_records.size()) return reject(AdvertisingSpendingStatus::invalid_state); + const uint32_t current = ad_u32(g.manager_records, field); + uint8_t delivery = 0; + if (request.target_slot == 16) { + if (rec + 0x288 > g.manager_records.size()) return reject(AdvertisingSpendingStatus::invalid_state); + delivery = g.manager_records.at(rec + 0x287); + } + if (current != request.expected_amount || delivery != request.expected_delivery_weeks) + return reject(AdvertisingSpendingStatus::stale_request); + const uint32_t maximum = request.target_slot == 16 ? 350000u : 35000u; + if (request.amount > maximum) + return reject(AdvertisingSpendingStatus::invalid_amount); + if (request.target_slot == 16 && delivery != 0) + return reject(AdvertisingSpendingStatus::delivery_pending); + + if (request.target_slot == 16) { + // BalanceFromGame may return zero; the merchandise branch then performs no writes. + if (request.amount == 0) return reject(AdvertisingSpendingStatus::no_change); + ModernState staged = g; + WatcomRandom staged_rand = rand; + if (!modern::book_money(staged, request.manager, int32_t(request.amount), false, true)) { + // CheckAdvertisingRenewal clears +0x850 on insufficient funds but does not draw delivery RNG. + wr32(staged.manager_records, field, 0); + g.manager_records = std::move(staged.manager_records); + result.status = AdvertisingSpendingStatus::insufficient_funds; + result.changed = current != 0; + result.message_address = ::bmh::layout::Advertising_FormatError_TextPointer18; + return result; + } + wr32(staged.manager_records, field, int32_t(request.amount)); + staged.manager_records.at(rec + 0x287) = uint8_t(staged_rand.range(6, 9)); + g.manager_records = std::move(staged.manager_records); + rand = staged_rand; + result.status = AdvertisingSpendingStatus::accepted; + result.changed = true; + result.message_address = ::bmh::layout::DeskActions_Reject_ExecutableField; + return result; + } + + if (current == request.amount) return reject(AdvertisingSpendingStatus::no_change); + wr32(g.manager_records, field, int32_t(request.amount)); + result.status = AdvertisingSpendingStatus::accepted; + result.changed = true; + return result; +} + +namespace { + +void wr32_ad(std::vector& b, size_t at, uint32_t v) { + for (int i = 0; i < 4; ++i) b.at(at + size_t(i)) = uint8_t(v >> (8 * i)); +} + +// The end of a renewal (CheckAdvertisingRenewal): byte +6 cleared, the other boards of the same +// bundle (group byte +4, non-empty) take a copy of the contract (renewed or freed). +void settle_advertising_renewal(ModernState& g, size_t rec, int contract_slot) { + std::vector& r = g.manager_records; + const size_t at = rec + kAdContracts + size_t(contract_slot) * kAdContractBytes; + r.at(at + 6) = 0; + if (contract_slot >= 14) return; + for (int other = 0; other < 14; ++other) { + if (other == contract_slot) continue; + const size_t o = rec + kAdContracts + size_t(other) * kAdContractBytes; + if (r.at(o + 4) == r.at(at + 4) && ad_u32(r, o) != 0) + std::copy_n(r.begin() + std::ptrdiff_t(at), kAdContractBytes, r.begin() + std::ptrdiff_t(o)); + } +} + +} // namespace + +AdvertisingRenewal check_advertising_renewal(ModernState& g, int manager, int display_slot, WatcomRandom& rand) { + AdvertisingRenewal out; + if (!ad_manager_record_valid(g, manager) || display_slot < 0 || display_slot > 15) return out; + const size_t rec = size_t(manager) * kAdRecord; + out.contract_slot = display_slot < 14 ? ad_board_order(g.manager_records, rec).slots[size_t(display_slot)] : display_slot; + const size_t at = rec + kAdContracts + size_t(out.contract_slot) * kAdContractBytes; + std::vector& r = g.manager_records; + if (!ad_extension_requires_unsupported_prompt(r, at)) { + out.status = AdvertisingRenewal::Status::not_expired; + return out; + } + // the sponsor name: board/shirt firms from Advertising_FormatError_ExecutableField3, TV stations ten entries later + const uint32_t name = ::bmh::layout::Advertising_FormatError_ExecutableField3 + uint32_t((out.contract_slot == 15 ? 10 : 0) + std::min(r.at(at + 7), 9)) * 4; + const int demand = int(uint32_t(r.at(at + 8)) | uint32_t(r.at(at + 9)) << 8); + const int scaled = demand * int(rand.range(0x5f, 0x69)) / 100; + if (scaled < modern::club_attraction(g, g.manager_teams.at(size_t(manager)))) { + out.status = AdvertisingRenewal::Status::offered; + out.question = message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer) + message_text(g, name) + message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer2); + return out; + } + out.status = AdvertisingRenewal::Status::declined_by_sponsor; + out.notice = message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer3) + message_text(g, name) + message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer4) + message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer5); + post_composed(g, manager, out.notice); + wr32_ad(r, at, 0); + settle_advertising_renewal(g, rec, out.contract_slot); + return out; +} + +bool answer_advertising_renewal(ModernState& g, int manager, int contract_slot, bool renew) { + if (!ad_manager_record_valid(g, manager) || contract_slot < 0 || contract_slot > 15) return false; + const size_t rec = size_t(manager) * kAdRecord; + const size_t at = rec + kAdContracts + size_t(contract_slot) * kAdContractBytes; + std::vector& r = g.manager_records; + if (!ad_extension_requires_unsupported_prompt(r, at)) return false; + if (renew) r.at(at + 5) = uint8_t(r.at(at + 6) & 0x7f); + else wr32_ad(r, at, 0); + settle_advertising_renewal(g, rec, contract_slot); + return true; +} + +} // namespace bmh::modern diff --git a/src/modern/game/desk_actions.hpp b/src/modern/game/desk_actions.hpp new file mode 100644 index 0000000..911fd0f --- /dev/null +++ b/src/modern/game/desk_actions.hpp @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/desk_actions.hpp" +// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules. +// Actions a human manager can take at his desk that change the game state and draw random +// numbers (BMH.exe V2.24 + supported rule profile patch). The screens themselves belong to the UI; these +// functions are what happens when the manager confirms. + +#include +#include +#include +#include +#include +#include + +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" +#include "game/human_buyer_sale.hpp" +#include "modern/game/club_player_detail.hpp" + +namespace bmh::modern { + + +// The eight training camp resorts of BookTrainingCamp (names DeskActionsRuntimeField7). +constexpr int kTrainingCampResorts = 8; + +// Resort names, qualities and prices are edition content, not shared rules. +// Install the loaded executable's tables after creating or loading a ModernState. +void configure_training_camp_data(ModernState&, const LeImage&); + +// DeskDate / menu 6 friendship booking. `manager_home` selects which team is first in +// the saved pair; the manager of the home team pays the source cost. The national-team +// source-qualified overload below handles pseudo-team ratings and their W/G RNG separately. + + + + +// Source-qualified menu-6 national friendly owner. The UI/session supplies the +// revision and request identity; the engine binds them to the selected runtime nation. + + + + +// Pure source-derived quote for the pre-calendar price/venue prompt. It performs no writes +// or RNG draws. Bind this quote to the UI request ID/revision until the user chooses a day. +FriendlyBookingQuote quote_friendly_match(const ModernState& g, int manager, int opponent, + bool manager_home); + +// Original menu-6 national quote. A successful accepted quote advances W exactly for +// QuoteNationalFriendlyMatch's ratings. Preview runs the same calculation on a copy and never advances W. +NationalFriendlyQuote quote_national_friendly_match(const ModernState& g, + const NationalFriendlyOwner&, int opponent, bool manager_home, WatcomRandom& rand); +NationalFriendlyQuote preview_national_friendly_match(const ModernState& g, + const NationalFriendlyOwner&, int opponent, bool manager_home, const WatcomRandom& rand); +FriendlyDateStatus national_friendly_match_date_status(const ModernState&, + const NationalFriendlyQuote&, const NationalFriendlyOwner&, const WatcomRandom&, + uint16_t season_day); +NationalFriendlyBookingResult book_national_friendly_match(ModernState&, + const NationalFriendlyBookingRequest&, const WatcomRandom&, GameRandom&); + +// Conservative saved-state projection for days 0..365. `available_with_calendar_event` is +// the source color class for a selectable day whose calendar word has 0x1c0 set. The +// original calendar also carries a transient, sequentially projected bit 15 that is not in +// ModernState; dates with ambiguous neighboring calendar flags may therefore be over-rejected. +FriendlyDateStatus friendly_match_date_status(const ModernState& g, + const FriendlyBookingQuote& quote, + uint16_t season_day); + +// Book the accepted quote on the chosen day atomically. The quote is recomputed and must +// still match; approval is explicit. A successful home booking permanently debits the fee +// and records expense-other (+0x8a0). No RNG is used for club-vs-club bookings. +FriendlyBookingResult book_friendly_match(ModernState& g, const FriendlyBookingRequest& request); + +// UI-free human transfer actions (menu 17). List-entry indices address the 44-entry +// transfer table; money and contracts are stored in the normal engine state. + + + +// Authenticated lender snapshot -> real borrower squad identity. This is preview +// only; the snapshot never becomes a listing/sale row. +std::optional transfer_market_snapshot_preview( + const ModernState&,int manager,int runtime_club,int snapshot_index); +// TransferMarketScreen quote identity: ordinary Native slot, or an explicitly authenticated +// lender snapshot mapped by the read-only resolver above. +// No Native writes or G draws. W is0 or1 (42307 fallback). The owner stages W +// and rolls it back on unsupported/exception; repeated-hover caching belongs +// to that owner, not to this primitive or a render method. +TransferMarketPreviewResult quote_transfer_market_preview_source( + const ModernState& g,const TransferMarketPreviewRequest& request,WatcomRandom& rand); + +// Exact ordinary OpenTransferEditor/KB31 state owner. UI events contain calculator +// results in Native units; all quotes and Native row writes belong here. +TransferOfferEditorState open_transfer_offer_editor_source(ModernState&, + const TransferOfferEditorRequest&,GameRandom&,WatcomRandom&); +TransferOfferEditorState edit_transfer_offer_editor_source(ModernState&, + const TransferOfferEditorState&,const TransferOfferEditorEvent&,GameRandom&,WatcomRandom&); +// OpenTransferEditor TeamInfo return: 1c5b7 -> 1c186 -> 1c18b. Rescan and +// redraw the current row, preserving initial percent/G. A first empty selection +// initializes only fee/salary/term once; all seven Native bonus bytes survive. +TransferOfferEditorState resume_transfer_offer_team_info_source(ModernState&, + const TransferOfferEditorState&,WatcomRandom&); +// OpenTransferEditor:6936..6953 resolves the direct footer's actual player slot. +// Unmanaged sellers use the Native pool slot; managed sellers use the first +// masked-ID match in their real 24/16-slot squad. The opened owner retains +// Source local40; stale retained rows reject instead of silently reselecting. +ClubPlayerDetailSelection transfer_offer_player_info_selection_source(const ModernState&, + const TransferOfferEditorState&); +// After player information returns: zero return flags preserve the entire editor and quote; +// otherwise rescan/requote by rebuilding the quote without repeating the initial G draw. +TransferOfferEditorState resume_transfer_offer_player_info_source(ModernState&, + const TransferOfferEditorState&,uint8_t player_info_primary_refresh,uint8_t player_info_secondary_refresh,WatcomRandom&); +TransferOfferEditorState cancel_transfer_offer_editor_source(const ModernState&, + const TransferOfferEditorState&); +TransferOfferEditorSubmitResult submit_transfer_offer_editor_source(ModernState&, + const TransferOfferEditorState&,WatcomRandom&,const HumanBuyerSaleHooks&,MinuteReport&); + +// Submit a manager bid on an existing list entry. A full-value fee and salary meeting +// the demand complete an immediate agreement; lower viable offers persist for weekly review. +TransferActionResult submit_transfer_bid(ModernState& g, const TransferBidRequest& request, WatcomRandom& rand); + +// Explicit opt-in Source SubmitTransferBidSourceHumanBuyer ordinary bid-submit path. Unlike the legacy +// overload, the caller owns staged Native/W state, supplies the exact source +// pool slot, actual career mode is present in Native, and the session provides +// its allocator/entry ownership plus Original notice presenter. Source-approved +// AI/free-agent purchases use the exact shared settlement; other sellers retain +// a pending bid. Unsupported contexts require caller rollback. +TransferActionResult submit_transfer_bid_source_human_buyer(ModernState& g, + const TransferBidRequest& request, WatcomRandom& rand, + const HumanBuyerSaleHooks& hooks, MinuteReport& report); + +// Put one of the manager's squad rows on the list. The request consumes the original +// listing-price RNG and returns the new stable entry index through the result. +TransferActionResult list_manager_player(ModernState& g, int manager, int squad_row, + WatcomRandom& rand, MinuteReport& report); + + +// SetTrainingCampFocus: persist the four focus sliders (+0xc1..+0xc4) without drawing or +// applying training. Rejects an invalid manager or any value outside the original 0..15 range. +bool set_training_camp_focus(ModernState& g, int manager, const std::array& focus); + +// BookTrainingCamp controller gates, before payment and training effects. +TrainingCampBookingBlock training_camp_booking_block(const ModernState& g, int manager); + +// Text: price of a stay at `resort` for the manager's team - the resort's base +// price (DeskActions_ConfigureTrainingCampData_RuntimeField2 of the loaded game) plus 5 000 per player of the squad +// (QuoteNationalFriendlyMatch with 0xff, the player count). Draws nothing. +int32_t training_camp_price(const ModernState& g, int manager, int resort); + +// BookTrainingCamp on "Buchen": the price is booked (BookMoney2, not forced). If the money is +// there, record +0x890 (training camp expenses) grows by it, record +0x21f counts the stays +// (bit 7 = "already in a camp this week", cleared by the day step) and the camp takes +// effect (training_camp_effect). Returns false if the booking failed. The four focus +// sliders (record +0xc1..+0xc4, 0..15) are set on the screen before. +// The screen allows a booking only if bit 7 of +0x21f is clear and fewer than 3 stays +// were made (+0x21f & 0x7f < 3) - checked by the caller. +bool book_training_camp(ModernState& g, int manager, int resort, WatcomRandom& rand); + +// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules. +// TrainingCampEffect (with the supported rule profile patch TrainingCampEffect2 / TrainingCampEffect3 / TrainingCampEffect4): the +// effect of a training camp. The team morale rises by 12 * quality * 20 % (clamped to +// 0..47), then every player of the squad may improve in condition, technique, form, +// familiarity (tactics board +0xf) and freshness (board +0x0e bits 0-5). See the .cpp. +// Ends with the message DeskActionsRuntimeField8 (SystemIdentity, no draws). +void training_camp_effect(ModernState& g, int manager, int resort, WatcomRandom& rand); + +} // namespace bmh::modern + +namespace bmh::modern { + +// The stock exchange screen MaxSharesToBuy (bank button). The twelve shares are entries of +// 0x5c bytes in GameState::stocks (StockExchange): +0x00 long-term value (u32, price * 100), +// +0x04 + manager * 4 the amount the manager paid for his shares (u32), +0x16 trend byte, +// +0x4e current price (u16), +0x50 + manager * 2 shares held (u16), +0x59 age of the trend. +constexpr int kStocks = 12; + +// Largest number of shares of `stock` the manager may buy: (money + credit line) / price, +// with at most 9999 shares of one company. +int max_shares_to_buy(const ModernState& g, int manager, int stock); + +// Buying `count` shares: the price times count plus 1.5 % fee is booked (BookMoney2, not +// forced) - but only while the paid amount of all shares held stays below 5 % of the +// money (record +0x314 / 20), else the message Bank_OriginalToUtf8_TextPointer8 ("too much") and nothing +// happens (returns false). Record +0x324 (stock balance) falls by the amount. +bool buy_shares(ModernState& g, int manager, int stock, int count); + +// Selling `count` shares at the current price: the paid amount shrinks by its average per +// share, the money (forced booking) and record +0x324 rise. +void sell_shares(ModernState& g, int manager, int stock, int count); + +// The "Tip" button (costs 5 000, booked forced with statistics): 0 (sell) .. 4 (buy), +// from the trend byte and the price against the long-term value, then with chance 1/3 +// moved by -2, 0 or +2 (WatcomRandom(0, 2) twice). The text is Bank_FormatError_RuntimeField19[tip]. +int stock_tip(ModernState& g, int manager, int stock, WatcomRandom& rand); + +} // namespace bmh::modern + +namespace bmh::modern { + +// The stadium screen ConstructionPricePercent (stadium button) - the parts that draw numbers or book. +// The manager record holds 14 periphery objects (+0x00..+0x0d condition, +0x1e..+0x2b +// construction weeks), eight Facility/Maintain investments (+0x0e.. condition, +// +0x2c.. construction weeks, +0x3c.. current/pending level), and eight stand blocks +// (+0x34.. construction weeks, +0x44.. seat/roof flags, +0x4c.. current capacity in +// thousands, +0x54.. future capacity). These are distinct Source branches. + +// On opening: the game generator restarts from the saved seed CareerSession_Invalid_RuntimeField2 and draws the +// building company's discount, DeskActionsRuntimeField9 = 100 - G(r / 100, r / 100 + 5) with r = +// record +0x8b4 (int16). Returns the price percentage (100 - discount). +int construction_price_percent(const ModernState& g, int manager, GameRandom& game); + +// The offer for periphery object `object` (0..13) when it is clicked: the game generator +// restarts from CareerSession_Invalid_RuntimeField2, draws G(0, 100) once per object before it and then the +// price percentage G(85, 115); price = base (StadiumPriceTable) * percentage / 1 000 000 * +// 10 000. +int32_t periphery_offer(const ModernState& g, int object, GameRandom& game); + +// PayConstruction: pays a construction. With `sponsor` and a sponsor share (record +0x171) +// the price is reduced once - by ((share >> 5) + 3) * 10 % below a limit of ((share >> 2) +// & 7) * 325 000 + 26 000, else by WatcomRandom(2, 4) * 5 % ("Der Sponsor fühlt sich +// ausgenutzt") - and the share is cleared. Booked with statistics, not forced. + +// PayConstruction presents the sponsor notice before clearing+171. A genuine +// BookMoney2 refusal presents funds after that clearing. Presenter exceptions +// propagate; the caller owns the whole transaction checkpoint/rollback. +bool pay_construction(ModernState& g, int manager, uint32_t price, bool sponsor, WatcomRandom& rand, + const ConstructionNoticeHook& notice = {}); + +// "Ja" on the offer: pay_construction(price, sponsor) and the construction time of the +// object (CareerSession_DispatchStadium_RuntimeField2[object * 5]) is entered at record +0x1e + object. +bool build_periphery(ModernState& g, int manager, int object, uint32_t price, WatcomRandom& rand, + const ConstructionNoticeHook& notice = {}); + + + +// PrepareStandBlockOffer, before its Yes/No prompt: consumes exactly W(6,14) and returns the +// percentage and quoted price. The quote is a value; displaying it consumes no more RNG. +// The path has not been compared with a matching original recording. +StandBlockOffer prepare_stand_block_offer(uint32_t base_price, int construction_days, WatcomRandom& rand); + +// Resolve the PrepareStandBlockOffer answer once. No leaves the base price/time and draws nothing; +// Yes applies the quoted price and consumes exactly W(days>>3, days>>1) to shorten time. +// Repeated resolution is ignored, so a duplicated input cannot consume another draw. +bool resolve_stand_block_offer(StandBlockOffer& offer, bool accept, WatcomRandom& rand); + +// ConstructionPricePercent choices 0..7: TEXTD734..741. Choices 8..15 are separate stand +// expansion editors and must never use the Facility/Maintain record arithmetic. +// Pure projection. Busy or terminal investments have no options. Invalid owner, +// constants or a nonzero idle high nibble raise FormatError. Heating/VIP offer +// one tier unless (raw status &7)==2, including raw0. Ordinary tiers start at +// the full raw status byte and stop before5; bit3 yields no ordinary options. +// target_level is the accepted level after weekly completion's &7 narrowing. +std::vector stadium_investment_options_source( + const ModernState&, int manager, StadiumInvestment, int construction_percent, + const StadiumInvestmentConstants&); +// Revalidate the owned option against the current record and trusted Original +// constants before payment. Both resolved tip answers build: Declined means no +// tip, not cancel. Source sponsor draws/consumption can precede payment refusal; +// only successful payment writes +2c/+3c. No actual block capacity/flags +// (+34/+44/+54), GameRandom or weekly compensation is touched. +bool build_stadium_investment_source(ModernState&, int manager, StadiumInvestment, + int construction_percent, const StadiumInvestmentConstants&, + const StadiumInvestmentOption&, const StandBlockOffer& resolved_tip, WatcomRandom&, + const ConstructionNoticeHook& notice = {}); + +// LeagueTableRangeDialog: persist the active 11-match pools coupon. The stake sits at +// Coupon + manager*0x14 and picks at +8..+0x12. Money is only charged by +// settle_pools_coupon at matchday end; this confirmation itself draws no RNG. +// BuildPoolsCoupon makes the screen unavailable unless all eleven fixtures exist. +// BalanceFromGame bounds stake to 10,000..400,000 (zero clears it). +bool submit_pools_coupon(ModernState& g, int manager, uint32_t stake, + const std::array& tips); + +} // namespace bmh::modern + +namespace bmh::modern { + +// Source-backed advertising contracts (DeskActionsOperation/CheckAdvertisingRenewal). Offers are +// generated elsewhere and live in the manager's saved +0x8cc pool. Projection +// is read-only: it never generates offers or consumes RNG. + + + + + +// A group of identical offers may require several boards. Empty boards and rows +// marked replaceable by source flag +6 bit 7 count toward capacity. +AdvertisingOfferList advertising_offers(const ModernState& g, int manager, int display_slot); + +// Accept an existing offer atomically. Board rows are source-sorted before the +// bundle is installed; the group byte at +4 receives AdGroupId and that counter +// advances once. Shirt/TV offers replace their corresponding slot. This commit +// books no immediate cash and draws no RNG. Option-extension offers are excluded. +AdvertisingOfferResult accept_advertising_offer(ModernState& g, + const AdvertisingOfferRequest& request); + +// CheckAdvertisingRenewal: a click on a contract whose months ran out (sponsor set, months 0 - the +// month change posted "kann verlängert werden", Month_MonthChange_TextPointer). The sponsor's demand (word +// +8, the club attraction it wants) is scaled by W(95, 105) % (WatcomRandom); if it stays +// below the club's attraction (ClubAttraction) the manager is asked "Möchten Sie den Vertrag +// mit verlängern ?" (DeskActions_CheckAdvertisingRenewal_TextPointer/DeskActions_CheckAdvertisingRenewal_TextPointer2), otherwise the sponsor declines ("Die Firma +// wird den Vertrag nicht verlängern.", DeskActions_CheckAdvertisingRenewal_TextPointer3..DeskActions_CheckAdvertisingRenewal_TextPointer5, a mailbox message) and the +// place becomes free. Step one draws the random number and settles the refusal; step two +// applies the manager's answer: yes = the old duration again (byte +6 & 0x7f), no = free. +// Either way byte +6 is cleared and the other boards of the same bundle (group byte +4) +// get a copy of the result. +AdvertisingRenewal check_advertising_renewal(ModernState& g, int manager, int display_slot, WatcomRandom& rand); +bool answer_advertising_renewal(ModernState& g, int manager, int contract_slot, bool renew); + +// CheckAdvertisingRenewal advertising spend fields (manager record +0x850/+0x854/+0x858, +// delivery countdown +0x287). Projection is read-only; only goods purchasing draws. + + + + +AdvertisingSpendingView advertising_spending(const ModernState& g, int manager, int target_slot); +AdvertisingSpendingResult set_advertising_spending(ModernState& g, + const AdvertisingSpendingRequest& request, + WatcomRandom& rand); + +} // namespace bmh::modern + +namespace bmh::modern { + +// The funds of the same screen (block FundBlock in GameState::memory, six entries of 0x1c +// bytes): +0x00 price of a unit ((1 << k) * 100 000), +0x04 + manager * 4 the amount the +// manager paid (u32), +0x14 + manager * 2 units held (u16, at most 10 per fund). +constexpr int kFunds = 6; + +// Units of fund `fund` the manager can buy: (money + credit line) / (price * 1.05), at most +// 10 minus the units held. +int max_fund_units(const ModernState& g, int manager, int fund); + +// Buying `count` units: price * count plus 5 % fee is booked (not forced) - record +0x324 +// falls by it, record +0x30c rises by the fee and by price * count / 9. Every fund but +// the first costs a surcharge as well: count * G(price / 40, price / 10), paid (forced) and +// added to +0x30c, with the message CareerSession_Int32T_TextPointer2. Returns the surcharge. +int32_t buy_fund_units(ModernState& g, int manager, int fund, int count, GameRandom& game); + +// Selling `count` units at the price: the paid amount shrinks by its average per unit, the +// money (forced) and +0x324 rise, +0x30c falls by price * count / 9. +void sell_fund_units(ModernState& g, int manager, int fund, int count); + +// The fixed-term deposit (record +0x318): a positive amount moves money from the account +// to the deposit, a negative one back (both booked forced; +0x324 changes by the same). +// The deposit earns interest in daily_interest. +void move_to_deposit(ModernState& g, int manager, int32_t amount); + +// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules. +// NormalizePitchSetPieceSource (supported rule profile patch), when the line-up screen opens (PitchScreen, desk menu 3 and +// before matches): a manager record without the set-piece marker 0x3253 at +0xb0a gets it, +// with the takers cleared (+0xafc..+0xaff = 0, +0xb08 = designated-taker signature). +void open_lineup_screen(ModernState& g, int manager); + +} // namespace bmh::modern diff --git a/src/modern/game/driver.cpp b/src/modern/game/driver.cpp new file mode 100644 index 0000000..d31c4dc --- /dev/null +++ b/src/modern/game/driver.cpp @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/game/driver.hpp" +#include "modern/game/modern_state.hpp" + +#include +#include +#include + +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" +#include "modern/game/season.hpp" + +namespace bmh::modern { + +int cup_tie(const MatchGroup& grp, int m) { + const uint16_t r = grp.cup_results.at(size_t(m)); + int home = r >> 5 & 0x1F, away = r & 0x1F; + int other_home = 0, other_away = 0; + if (!grp.cup_other_leg.empty()) { + other_home = grp.cup_other_leg.at(size_t(m)) >> 5 & 0x1F; + other_away = grp.cup_other_leg.at(size_t(m)) & 0x1F; + } + // this match's home team was the away team of the other leg + if ((grp.flags() & 0x10) && other_home + away == home + other_away && (r >> 11) == 0) { + away *= 2; // away goals of this match ... + other_away *= 2; // ... and of the other leg count double + } + const int home_total = home + other_away, away_total = other_home + away; + return (unsigned(home_total) < unsigned(away_total) ? 1 : 0) + (home_total == away_total ? 2 : 0); +} + +bool cup_screen_shown(const std::vector& buttons, int cup_id, int minute) { + if (buttons.empty()) return true; + const int kind = (minute > 45) + 1; + const int row = cup_id + 5; + if (row == 0x12) return buttons.at(size_t(0x12 + kind)) == 0 || buttons.at(size_t(0x1b + kind)) == 0; + return buttons.at(size_t(kind + row * 9)) == 0; +} + +void play_phase(MatchEngine& engine, std::vector& groups, int first, int last, int stoppage, int phase, + MinuteReport& report, const std::function& after_minute) { + for (MatchGroup& grp : groups) grp.ended = 0, grp.phase = phase; + for (int minute = first; minute <= last + stoppage && !report.unsupported; minute++) { + bool running = false; + for (const MatchGroup& grp : groups) + for (int m = 0; m < grp.matches(); m++) + if (!((grp.void_mask() | grp.ended) >> m & 1)) running = true; + if (!running) break; // the original leaves the phase after a minute without matches + report = engine.minute(minute, last, stoppage); + if (after_minute) after_minute(minute); + } +} + +namespace { + +void set_void(MatchGroup& grp, int m) { + const uint32_t v = grp.void_mask() | 1u << m; + for (int i = 0; i < 4; i++) grp.desc.at(0xb8 + size_t(i)) = uint8_t(v >> (8 * i)); +} + +} // namespace + +namespace { + +bool group_played(const MatchGroup& grp) { + for (int m = 0; m < grp.matches(); m++) + if (grp.ended >> m & 1) return true; + return false; +} + +bool result_visible(ModernState& g, const MatchGroup& grp, int last, + const std::vector& buttons, PhaseResultKind& kind, + int& competition_id) { + const uint32_t id = le32(grp.desc, 0xcc); + if (id < 0x15) { + kind = PhaseResultKind::League; + competition_id = int(id); + return modern::league_screen_shown(buttons, 2, last, int(id)); + } + kind = PhaseResultKind::Cup; + competition_id = int16_t(g.memory.u16(id + 0x18)); + return modern::cup_screen_shown(buttons, competition_id, last); +} + +PhaseResultRequest make_result_request(const MatchGroup& grp, uint64_t phase_id, + uint32_t group_index, uint64_t revision, + PhaseResultKind kind, int competition_id, int last) { + PhaseResultRequest req; + req.phase_id = phase_id; + req.group_index = group_index; + req.revision = revision; + req.kind = kind; + req.competition_id = competition_id; + req.phase_end_minute = last; + req.matches.reserve(size_t(grp.matches())); + for (int m = 0; m < grp.matches(); ++m) { + PhaseResultMatch score; + score.home_team = grp.fixtures.at(size_t(m * 2)); + score.away_team = grp.fixtures.at(size_t(m * 2 + 1)); + score.score_known = modern::match_score(grp, m, score.home_score, score.away_score); + req.matches.push_back(score); + } + return req; +} + +void finish_group_phase(ModernState& g, MatchGroup& grp, int last, GameRandom& game) { + const bool full_time = last == 90 || last == 120 || last == 40; + if (!full_time) return; + const bool final_phase = last == 40 || last == 120; + for (int m = 0; m < grp.matches(); m++) { + if ((grp.flags() & 8) && modern::cup_tie(grp, m) == 2) { + uint16_t& r = grp.cup_results.at(size_t(m)); + if (r != 0xCCCC) r = uint16_t((final_phase ? 2 : 1) * 0x400 + (r & 0x3FF)); + if (final_phase) modern::finish_match(g, grp, m, last, game); + continue; + } + if (grp.void_mask() >> m & 1) continue; + modern::finish_match(g, grp, m, last, game); + set_void(grp, m); + } +} + +PhaseEndOutput rejected(const char* why) { + PhaseEndOutput out; + out.status = PhaseEndStatus::Rejected; + out.reason = why; + return out; +} + +PhaseEndOutput advance_phase_end(PhaseEndCursor& c) { + while (c.next_group < c.groups->size()) { + MatchGroup& grp = c.groups->at(c.next_group); + if (c.phase_played) { + PhaseResultKind kind; + int competition_id = 0; + if (result_visible(static_cast(static_cast(*c.state)), grp, c.last, c.buttons, kind, competition_id)) { + c.pending = make_result_request(grp, c.phase_id, c.next_group, c.revision, + kind, competition_id, c.last); + // CupGroupOverviewEffects initializes the cup viewer before presenting it. + // Keep this once at entry, so closing cannot erase viewer edits. + if (kind == PhaseResultKind::Cup) modern::cup_overview_effects(static_cast(*c.state)); + PhaseEndOutput out; + out.status = PhaseEndStatus::Waiting; + out.request = c.pending; + return out; + } + } + finish_group_phase(static_cast(static_cast(*c.state)), grp, c.last, *c.game); + ++c.next_group; + } + c.complete = true; + c.pending.reset(); + PhaseEndOutput out; + out.status = PhaseEndStatus::Complete; + return out; +} + +} // namespace + +PhaseEndOutput begin_phase_end(PhaseEndCursor& c, uint64_t phase_id, ModernState& g, + std::vector& groups, int last, + const std::vector& buttons, GameRandom& game, + WatcomRandom& rand, MinuteReport& report) { + if (c.initialized) { + const bool same = c.phase_id == phase_id && c.state == &g && c.groups == &groups && c.last == last && + c.buttons_source == &buttons && c.game == &game && c.rand == &rand && c.report == &report; + if (!c.complete) { + if (!same) return rejected("phase already active with different identity or borrowed objects"); + if (c.pending) { + PhaseEndOutput out; + out.status = PhaseEndStatus::Waiting; + out.request = c.pending; + return out; + } + return rejected("active phase has no pending result"); + } + if (same) { + PhaseEndOutput out; + out.status = PhaseEndStatus::Complete; + return out; + } + } + c.initialized = true; + c.complete = false; + // Original local_48 belongs to EndPhase, not to a group. Preserve this + // gate throughout the barrier even as each acknowledged group settles. + c.phase_played = std::any_of(groups.begin(), groups.end(), group_played); + c.phase_id = phase_id; + c.revision = 1; + c.next_group = 0; + c.last = last; + c.buttons = buttons; + c.buttons_source = &buttons; + c.state = &g; + c.groups = &groups; + c.game = &game; + c.rand = &rand; + c.report = &report; + c.pending.reset(); + c.last_ack.reset(); + c.after_last_ack.reset(); + return advance_phase_end(c); +} + +PhaseEndOutput continue_phase_end(PhaseEndCursor& c, const std::optional& reply) { + if (!c.initialized) return rejected("phase not started"); + if (!reply) { + if (c.complete) return rejected("phase already complete"); + if (!c.pending) return rejected("no result is pending"); + PhaseEndOutput out; + out.status = PhaseEndStatus::Waiting; + out.request = c.pending; + return out; + } + if (c.last_ack && reply->phase_id == c.last_ack->phase_id && + reply->group_index == c.last_ack->group_index && reply->revision == c.last_ack->revision) { + return *c.after_last_ack; + } + if (c.complete) return rejected("phase already complete"); + if (!c.pending || reply->phase_id != c.pending->phase_id || + reply->group_index != c.pending->group_index || reply->revision != c.pending->revision) + return rejected("stale or mismatched result acknowledgement"); + + MatchGroup& grp = c.groups->at(c.pending->group_index); + if (c.pending->kind == PhaseResultKind::League) { + modern::stir_random(*c.game, *c.rand); + } + finish_group_phase(static_cast(static_cast(*c.state)), grp, c.last, *c.game); + c.next_group = c.pending->group_index + 1; + c.last_ack = *reply; + ++c.revision; + c.pending.reset(); + PhaseEndOutput out = advance_phase_end(c); + c.after_last_ack = out; + return out; +} + +void end_phase(ModernState& g, std::vector& groups, int last, const std::vector& buttons, + GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function&, + const ModernState&)>& presenter) { + PhaseEndCursor cursor; + PhaseEndOutput out = modern::begin_phase_end(cursor, 1, g, groups, last, buttons, game, rand, report); + while (out.status == PhaseEndStatus::Waiting && out.request) { + const PhaseResultRequest& req = *out.request; + if (presenter) presenter(req, groups, g); + out = modern::continue_phase_end(cursor, PhaseResultReply{req.phase_id, req.group_index, req.revision}); + } +} + +void play_matchday(MatchEngine& engine, ModernState& g, std::vector& groups, + const std::vector& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& after_minute, int stop_at) { + // EndPhase calls of the matchday: outdoors two halves (4 minutes of stoppage in the + // second) and extra time; the indoor tournament (CareerSessionRuntimeField) plays 2 x 20 minutes + const int outdoor[4][4] = {{1, 45, 0, 0}, {46, 90, 4, 0}, {91, 105, 0, 1}, {106, 120, 1, 1}}; + const int indoor[2][4] = {{1, 20, 0, 0}, {21, 40, 0, 0}}; + engine.indoor = g.indoor; + std::vector> phases; + if (g.indoor) + for (const auto& p : indoor) phases.push_back({p[0], p[1], p[2], p[3]}); + else + for (const auto& p : outdoor) phases.push_back({p[0], p[1], p[2], p[3]}); + for (const auto& p : phases) { + modern::play_phase(engine, groups, p[0], p[1], p[2], p[3], report, after_minute); + if (report.unsupported) return; + if (p[1] == stop_at) return; + modern::end_phase(g, groups, p[1], buttons, game, rand, report, engine.phase_results); + if (report.unsupported) return; + // FinishEvent / BuildSideRecords: EvaluatePoolsCoupon(0) after the second half (outdoors) + if (!g.indoor && p[1] == 90) modern::evaluate_pools_coupon(g, groups); + } + // CupTie2: penalty shoot-outs + for (MatchGroup& grp : groups) + for (int m = 0; m < grp.matches() && !report.unsupported; m++) + if ((grp.flags() & 8) && !grp.cup_results.empty() && (grp.cup_results[size_t(m)] >> 11) != 0) + engine.penalty_shootout(grp, m, report); +} + +} // namespace bmh::modern diff --git a/src/modern/game/driver.hpp b/src/modern/game/driver.hpp new file mode 100644 index 0000000..c340963 --- /dev/null +++ b/src/modern/game/driver.hpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/driver.hpp" +// The matchday driver after the kick-off (FinishEvent + BuildSideRecords, BMH.exe V2.24). +// +// The driver plays the phases one after another with EndPhase(first, last, +// stoppage, phase): +// 1..45 (no stoppage), 46..90 (+ up to 4), then 91..105 and 106..120 (+ up to 1, +// phase 1 = extra time; indoor tournaments play 1..20 and 21..40 instead). +// A phase ends when every match has ended; a phase in which no match is running draws +// nothing. At the end of a phase (end_phase): +// - if any match played in the phase, the result screen of every group is called +// unless switched off at the desk, including groups already settled in regular +// time; leaving a league screen stirs the random numbers (stir_random), +// - at full time (90, 120, and 40 indoors) every match gets FinishMatch and is marked +// done, except cup ties decided on the day (descriptor flag 8) that are still level +// on aggregate (cup_tie): they go into extra time, after 120 minutes into the +// penalty shoot-out (CupTie2). + +#include +#include +#include +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// CupTie: state of a cup tie after match m of a group: 0 the home side is through, +// 1 the away side, 2 still level. Two-legged ties add the other leg (its home team is +// this match's away team); with descriptor flag 0x10 away goals count double while the +// match is in regular time. +int cup_tie(const MatchGroup& grp, int m); + +// Whether the result screen of a cup (CupGroupOverviewEffects with a phase end minute) is shown. +bool cup_screen_shown(const std::vector& buttons, int cup_id, int minute); + +// One phase: minutes first..last+stoppage until every match has ended. `after_minute` +// is called after each simulated minute (for checks). Stops early if the engine reports +// an unsupported path. +void play_phase(MatchEngine& engine, std::vector& groups, int first, int last, int stoppage, int phase, + MinuteReport& report, const std::function& after_minute = {}); + +// The end of EndPhase for a phase that ended at minute `last`. +void end_phase(ModernState& g, std::vector& groups, int last, const std::vector& buttons, + GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function&, + const ModernState&)>& presenter = {}); + +// Nonblocking end-of-phase result barrier. The cursor borrows the original mutable +// objects for its whole lifetime; do not copy/move it or independently mutate those +// objects while pending. Native viewer actions use the owning synchronous App dispatcher; +// it must preserve group identity and never resume simulation. Cup entry effects precede +// presentation; league exit RNG and match settlement belong to the single ACK. +// Only presentation metadata and a bounded last-ACK record are owned. + +// First call starts/resumes the phase; repeating begin with the same phase while waiting +// polls the identical request. A completed cursor may be reused for a later phase. +PhaseEndOutput begin_phase_end(PhaseEndCursor& cursor, uint64_t phase_id, ModernState& g, + std::vector& groups, int last, + const std::vector& buttons, GameRandom& game, + WatcomRandom& rand, MinuteReport& report); +// An empty reply polls without effects. Only an exact current (phase, group, revision) +// reply resumes the group. Duplicate last ACK returns its cached continuation; older or +// mismatched replies are rejected without state/RNG/cursor advancement. +PhaseEndOutput continue_phase_end(PhaseEndCursor& cursor, + const std::optional& reply = std::nullopt); + +// All phases of a matchday (not indoor): regular time, extra time where needed. +// `stop_at` (45, 90, 105 or 120) stops at the whistle of that phase, before its result +// screens and match bookkeeping (end_phase); 0 plays everything. +void play_matchday(MatchEngine& engine, ModernState& g, std::vector& groups, + const std::vector& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& after_minute = {}, int stop_at = 0); + +} // namespace bmh::modern diff --git a/src/modern/game/environment.cpp b/src/modern/game/environment.cpp new file mode 100644 index 0000000..74d52ef --- /dev/null +++ b/src/modern/game/environment.cpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/environment.hpp" +#include +#include + +namespace bmh::modern { +namespace { +uint32_t youth_at(int manager) { return layout::EnvironmentYouthTeams + uint32_t(manager) * 0x24; } +uint32_t spending_at(int manager, int item) { + return layout::Spending + uint32_t(manager) * 0x24 + uint32_t(item) * 4; +} +void validate_manager(const ModernState& g, int manager) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + !g.memory.has(youth_at(manager) + 8) || !g.memory.has(spending_at(manager, 5) + 3)) + throw FormatError("environment: invalid manager or truncated budgets"); +} +int direction(int value) { return (value > 0) - (value < 0); } +int signed_clamp(int value, int low, int high) { + return std::clamp(int(int8_t(uint8_t(value))), low, high); +} +bool legacy_academy(const ModernState& g, int manager) { + const auto value = g.memory.u32(spending_at(manager, kYouthAcademy)); + return value == 1500000 || value == 1000000 || value == 580000 || value == 280000; +} +uint32_t academy_paid(const ModernState& g, int manager) { + const auto at = size_t(manager) * 0xb0c + 0x880; + return uint32_t(g.manager_records.at(at)) | uint32_t(g.manager_records.at(at + 1)) << 8 | + uint32_t(g.manager_records.at(at + 2)) << 16 | uint32_t(g.manager_records.at(at + 3)) << 24; +} +} +int32_t environment_monthly_cost(const ModernState& g, int manager, int item) { + const auto value = g.memory.u32(spending_at(manager, item)); + if (item == kYouthAcademy && legacy_academy(g, manager) && academy_paid(g, manager) >= value) return 0; + return int32_t(value); +} +bool environment_academy_active(const ModernState& g, int manager) { + const auto value = g.memory.u32(spending_at(manager, kYouthAcademy)); + return value != 0 && (!legacy_academy(g, manager) || academy_paid(g, manager) >= value); +} +EnvironmentState environment_state(const ModernState& g, int manager) { + validate_manager(g, manager); + EnvironmentState result; + for (int i = 0; i < kEnvironmentItems; ++i) { + result.monthly[size_t(i)] = int32_t(g.memory.u32(spending_at(manager, i))); + result.level[size_t(i)] = std::clamp(result.monthly[size_t(i)] / kEnvironmentStep[size_t(i)], 0, 6); + } + for (uint32_t i = 0; i < 3; ++i) { + result.youth_strength[i] = g.memory.u8(youth_at(manager) + i); + result.youth_position[i] = g.memory.u8(youth_at(manager) + 3 + i); + result.youth_league[i] = g.memory.u8(youth_at(manager) + 6 + i); + if (result.youth_position[i] > 11 || result.youth_league[i] > 2) + throw FormatError("environment: invalid youth table"); + } + return result; +} +EnvironmentResult set_environment(ModernState& g, int manager, int item, int level, std::string* message) { + if (message) message->clear(); + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || item < 0 || item >= kEnvironmentItems || + level < 0 || level > 6 || !g.memory.has(spending_at(manager, item) + 3)) + return EnvironmentResult::invalid; + const auto at = spending_at(manager, item); + const auto value = uint32_t(level * kEnvironmentStep[size_t(item)]); + if (g.memory.u32(at) == value) return EnvironmentResult::unchanged; + g.memory.set32(at, value); + return EnvironmentResult::changed; +} +void advance_youth_teams(ModernState& g, int manager, WatcomRandom& rand) { + const auto observed = modern::environment_state(g, manager); + std::array movement{}; + uint8_t step = 4; + for (auto& value : movement) { + value = step; + if (step != 0 && rand.range(0, 8) == 0) --step; + } + const auto round = g.league_rounds.at(0); + if (round >= movement.size()) throw FormatError("environment: youth round outside season"); + constexpr int division_strength[] = {85, 70, 57}; + for (size_t i = 0; i < 3; ++i) { + int strength = observed.youth_strength[i]; + int position = observed.youth_position[i]; + const int opponent = uint8_t(division_strength[observed.youth_league[i]] - position); + const int ratio = strength == 0 ? 100 : + int((((int64_t(observed.monthly[i]) * 100 / ((1 << i) * 10000)) >> 1) + 40) * 100 / strength); + int change = direction(ratio - 100); + if (rand.range(0, 4) == 0) change = rand.range(0, 2) - 1; + if (std::abs(ratio - 100) <= rand.range(0, 30)) change = 0; + if (rand.range(0, 2) == 0) strength = uint8_t(strength + change); + strength = signed_clamp(strength, 10, 85); + g.memory.set8(youth_at(manager) + uint32_t(i), uint8_t(strength)); + const int difference = strength - opponent; + change = direction(difference); + if (rand.range(0, 4) == 0) change = rand.range(0, 2) - 1; + if (rand.range(0, 3) != 0 && std::abs(difference) * 2 < rand.range(1, 18)) change = 0; + position = signed_clamp(uint8_t(position - change * rand.range(1, movement[round])), 0, 11); + g.memory.set8(youth_at(manager) + 3 + uint32_t(i), uint8_t(position)); + } +} +void finish_youth_season(ModernState& g, int manager) { + const auto observed = modern::environment_state(g, manager); + for (int i = 2; i >= 0; --i) { + auto division = observed.youth_league[size_t(i)]; + const int position = observed.youth_position[size_t(i)]; + int next_position = 5; + if (position < 2 && division != 0) { --division; next_position = position + 10; } + if (position > 10 && division < 2) { ++division; next_position = position - 10; } + if (i != 0) g.memory.set8(youth_at(manager) + uint32_t(i), + uint8_t((int(observed.youth_strength[size_t(i - 1)]) + observed.youth_strength[size_t(i)] * 2) / 3)); + g.memory.set8(youth_at(manager) + 3 + uint32_t(i), uint8_t(next_position)); + g.memory.set8(youth_at(manager) + 6 + uint32_t(i), division); + } +} +} // namespace bmh::modern diff --git a/src/modern/game/environment.hpp b/src/modern/game/environment.hpp new file mode 100644 index 0000000..7a22b1b --- /dev/null +++ b/src/modern/game/environment.hpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/environment.hpp" +#include +#include +#include +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { +constexpr int kEnvironmentItems = 6; +// OpenBMH deviates from the original: uses six monthly environment budgets across data editions while retaining the shared staff prices and academy player-generation strength bands. +inline constexpr std::array kEnvironmentStep = {2000, 4000, 5000, 5000, 5000, 5000}; +EnvironmentState environment_state(const ModernState& g, int manager); +// Preserve already saved lump-sum academy contracts until the user edits them. +int32_t environment_monthly_cost(const ModernState& g, int manager, int item); +bool environment_academy_active(const ModernState& g, int manager); +// Set a monthly budget to level 0..6, without an immediate debit or random draw. +EnvironmentResult set_environment(ModernState& g, int manager, int item, int level, std::string* message = nullptr); +// Youth results advance with first-division matchdays. Promotion/relegation and +// the handover to the next age group happen before annual accounts. +void advance_youth_teams(ModernState& g, int manager, WatcomRandom& rand); +void finish_youth_season(ModernState& g, int manager); +} // namespace bmh::modern diff --git a/src/modern/game/highscore.cpp b/src/modern/game/highscore.cpp new file mode 100644 index 0000000..45ee761 --- /dev/null +++ b/src/modern/game/highscore.cpp @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/highscore.hpp" +#include "formats/native_state.hpp" +#include "formats/native_file.hpp" + +#include +#include +#include +#include +#include + +#include "modern/game/weekly.hpp" + +namespace bmh::modern { +namespace { +constexpr size_t kRecord = 0xb0c; +// OpenBMH deviates from the original: reads the supported edition-specific high-score format from the loaded image. +// supported rule profile executable HighscoreRuntimeField..a5144, verified against the installed LE image. +constexpr std::array kHistoryWeights{3, 5, 4, 30, 20, 10, 5, 40}; +constexpr std::array kNationalWeights{30, 20, 10, 5}; +constexpr std::array kTitleWeights{40, 30, 50}; +int32_t signed32(uint32_t v) { return std::bit_cast(v); } +uint16_t rec16(const ModernState& g, int m, size_t offset) { + const size_t at = size_t(m) * kRecord + offset; + return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); +} +uint32_t rec32(const ModernState& g, int m, size_t offset) { + return uint32_t(rec16(g, m, offset)) | uint32_t(rec16(g, m, offset + 2)) << 16; +} +uint8_t rec8(const ModernState& g, int m, size_t offset) { + return g.manager_records.at(size_t(m) * kRecord + offset); +} +std::string record_name(const ModernState& g, int m) { + std::string name; + for (size_t i = 0; i < 30; ++i) { + const auto c = rec8(g, m, 0xa8 + i); + if (!c) return name; + name.push_back(char(c)); + } + throw std::invalid_argument("highscore: unterminated manager name"); +} +// HighscoreScore(0x1f,0,0xff), deliberately using the Source global asset-manager. +int32_t net_assets(const ModernState& g, int m) { + uint32_t sum = rec32(g, m, 0x314) + rec32(g, m, 0x318); + for (uint32_t k = 0; k < 6; ++k) + sum += uint32_t(g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + k * 0x1c)) * + g.memory.u32(::bmh::layout::FundBlock + k * 0x1c); + for (size_t k = 0; k < 12; ++k) { + const size_t at = k * 0x5c; + const uint32_t held = uint16_t(g.stocks.at(at + 0x50 + size_t(m) * 2) | + g.stocks.at(at + 0x51 + size_t(m) * 2) << 8); + const uint32_t price = uint16_t(g.stocks.at(at + 0x4e) | g.stocks.at(at + 0x4f) << 8); + sum += held * price; + } + for (uint32_t k = 0; k < 5; ++k) + sum -= g.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(m) * 0x78 + k * 0x18); + return signed32(sum); +} +uint32_t read32(const uint8_t* p) { + return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; +} +void put32(uint8_t* p, uint32_t v) { + for (int k = 0; k < 4; ++k) p[k] = uint8_t(v >> (8 * k)); +} +std::string read_name(const uint8_t* p) { + size_t n = 0; + while (n < 30 && p[n]) ++n; + if (n == 30) throw std::invalid_argument("highscore: unterminated file name"); + return {reinterpret_cast(p), n}; +} +void put_name(uint8_t* p, const std::string& s) { + if (s.size() >= 30 || s.find('\0') != std::string::npos) + throw std::invalid_argument("highscore: name does not fit Source row"); + // strcpy preserves bytes beyond the terminator of an existing row. + std::copy(s.begin(), s.end(), p); + p[s.size()] = 0; +} +} // namespace + +HighscoreScore highscore_score(const ModernState& g, int manager, HighscoreContext context) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) + throw std::invalid_argument("highscore: manager is outside active slots"); + HighscoreScore result; + const int team = g.manager_teams.at(size_t(manager)); + if (team == no_team()) { + // CareerSession_DispatchLineup_RuntimeField+CareerSession_InstallLeagueSizes_RuntimeField6+ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 == no_team() in the supported Original database; + // national honours store (team-no_team())|0x80, so Germany's index is0. + for (uint32_t year = 0; year < 20; ++year) + for (uint32_t place = 0; place < 4; ++place) { + const uint8_t v = g.memory.u8(::bmh::layout::Placements + year * 4 + place); + if ((v & 0x80) && (v & 0x7f) == 0) + result.history += int32_t(kNationalWeights[place]) * 10; + } + } else { + if (g.season < 0) throw std::invalid_argument("highscore: negative season index"); + const int asset_manager = context == HighscoreContext::SeasonBoundary + ? int(g.manager_teams.size()) : int(g.memory.u8(::bmh::layout::ActiveManager)); + result.assets = std::min(net_assets(g, asset_manager) / 50000, 100); + result.patience = rec8(g, manager, 0x26f); + ModernState facility_state = g; // facility_rating's public API takes mutable state. + int second = 0; + result.facilities = modern::facility_rating(facility_state, manager, &second) * 4; + result.team = int(uint16_t(team_average(g, team, 0x2ff).value)) / 10; + const uint32_t count = std::min(uint32_t(g.season) + 1, 50u); + uint32_t history = 0; + for (uint32_t year = 0; year < count; ++year) { + const size_t at = 0xda + year * 3; + const uint8_t v = rec8(g, manager, at + 2); + history += uint32_t(rec8(g, manager, at)) + uint32_t(rec8(g, manager, at + 1)) * 2 + + uint32_t(kHistoryWeights[v >> 5]) * (v & 0x1f); + } + result.history = int32_t((history & 0xffff) / count); + } + uint32_t total = uint32_t(result.assets) + uint32_t(result.patience) + + uint32_t(result.facilities) + uint32_t(result.team) + uint32_t(result.history); + for (size_t k = 0; k < 3; ++k) + result.titles += int32_t(kTitleWeights[k]) * rec16(g, manager, 0x8a4 + k * 2); + total += uint32_t(result.titles); + result.total = std::max(signed32(total), 0); + return result; +} + +HighscoreRow highscore_candidate(const ModernState& g, int manager, HighscoreContext context) { + if (g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) == 0) return {}; + HighscoreRow row; + row.score = modern::highscore_score(g, manager, context).total; + row.club_name = g.club_name(g.manager_teams.at(size_t(manager))); + row.manager_name = record_name(g, manager); + for (size_t k = 0; k < 3; ++k) row.titles[k] = rec16(g, manager, 0x8a4 + k * 2); + return row; +} + +void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate) { + size_t target = rows.size(); + for (size_t k = 0; k < rows.size(); ++k) + if (rows[k].manager_name == candidate.manager_name && rows[k].club_name == candidate.club_name) { + target = k; + break; + } + if (target == rows.size() && rows.back().score < candidate.score) target = rows.size() - 1; + if (target == rows.size()) return; + rows[target] = candidate; + // Swap uses these pairwise swaps; preserve equal-score ordering exactly. + for (size_t a = 0; a < 4; ++a) + for (size_t b = a + 1; b < 5; ++b) + if (rows[a].score < rows[b].score) std::swap(rows[a], rows[b]); +} + +HighscoreProjection make_highscore_projection(const ModernState& g, HighscoreTable rows, HighscoreContext context) { + HighscoreProjection out; + out.signature = g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7); + out.ranked = out.signature != 0; + out.rows = std::move(rows); + if (!out.ranked) return out; + // GameEndAlternateScoreScreen gates the entire manager loop using slot0, not each candidate's team. + if (!g.manager_teams.empty() && + (g.manager_teams[0] != no_team() || (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) == 0)) + for (size_t m = 0; m < g.manager_teams.size(); ++m) + modern::insert_highscore(out.rows, modern::highscore_candidate(g, int(m), context)); + return out; +} + +HighscoreBytes encode_highscore_table(const HighscoreTable& rows) { + HighscoreBytes bytes{}; + for (size_t k = 0; k < rows.size(); ++k) { + uint8_t* p = bytes.data() + k * 72; + std::copy(rows[k].original_bytes.begin(), rows[k].original_bytes.end(), p); + put32(p, uint32_t(rows[k].score)); + put_name(p + 4, rows[k].club_name); + put_name(p + 0x22, rows[k].manager_name); + for (size_t t = 0; t < 3; ++t) { + p[0x40 + t * 2] = uint8_t(rows[k].titles[t]); + p[0x41 + t * 2] = uint8_t(rows[k].titles[t] >> 8); + } + } + return bytes; +} +HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) { + HighscoreTable rows{}; + for (size_t k = 0; k < rows.size(); ++k) { + const uint8_t* p = bytes.data() + k * 72; + std::copy(p, p + 72, rows[k].original_bytes.begin()); + rows[k].score = signed32(read32(p)); + rows[k].club_name = read_name(p + 4); + rows[k].manager_name = read_name(p + 0x22); + for (size_t t = 0; t < 3; ++t) rows[k].titles[t] = uint16_t(p[0x40 + t * 2] | p[0x41 + t * 2] << 8); + } + return rows; +} +std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature, + const std::string &prefix, bool native) { + if (!signature) throw std::invalid_argument("highscore: signature0 has no ranked file"); + if (native) + return base / ("highscore-" + std::to_string(signature) + ".obscore"); + return base / (prefix + std::to_string(signature)); +} +HighscoreTable load_highscore_table(const std::filesystem::path& file) { + if (file.extension() == ".obscore") { + const auto data = read_file(file); + const auto j = cli::parse_json(std::string(data.begin(), data.end())); + if (!j.object() || !j.object()->contains("schema") || !j.object()->at("schema").string() || + *j.object()->at("schema").string() != "classic-highscore@1.0" || !j.object()->contains("payload")) + throw FormatError("Invalid native highscore"); + const auto raw = decode_native_bytes(j.object()->at("payload"), 360); + HighscoreBytes bytes; + std::copy(raw.begin(), raw.end(), bytes.begin()); + return modern::decode_highscore_table(bytes); + } + std::ifstream in(file, std::ios::binary); + if (!in) { + HighscoreTable empty{}; + modern::save_highscore_table(file, empty); // Read creates a zero table on a missing file. + return empty; + } + HighscoreBytes bytes{}; + in.read(reinterpret_cast(bytes.data()), bytes.size()); + return modern::decode_highscore_table(bytes); +} +bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) { + const auto bytes = modern::encode_highscore_table(rows); + if (file.extension() == ".obscore") { + try { + content::write_atomic(file, + cli::dump_json(cli::Json::Object{ + {"schema", "classic-highscore@1.0"}, + {"payload", encode_native_bytes(Bytes(bytes.begin(), bytes.end()))}}), + true); + return true; + } catch (const std::exception &) { + return false; + } + } + std::ofstream out(file, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(reinterpret_cast(bytes.data()), bytes.size()); + return bool(out); +} +} // namespace bmh::modern diff --git a/src/modern/game/highscore.hpp b/src/modern/game/highscore.hpp new file mode 100644 index 0000000..5f756bd --- /dev/null +++ b/src/modern/game/highscore.hpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/highscore.hpp" + +#include +#include +#include +#include + +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// HighscoreOperation / GameEndAlternateScoreScreen. Names retain Original ISO646-DE bytes. + + + +// Assets in HighscoreScore use global ActiveManager even when scoring another manager. At the +// season boundary DailyInterest's preceding manager loop leaves ActiveManager=manager_count. +// Pass that context explicitly without modifying the caller's continuation state. +HighscoreScore highscore_score(const ModernState& g, int manager, + HighscoreContext context = HighscoreContext::ActiveManager); +HighscoreRow highscore_candidate(const ModernState& g, int manager, + HighscoreContext context = HighscoreContext::ActiveManager); +void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate); +HighscoreProjection make_highscore_projection(const ModernState& g, HighscoreTable rows = {}, + HighscoreContext context = HighscoreContext::ActiveManager); + +HighscoreBytes encode_highscore_table(const HighscoreTable& rows); +HighscoreTable decode_highscore_table(const HighscoreBytes& bytes); +// The caller supplies the configured installation base and Original TEXTD889 prefix. +std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature, + const std::string &prefix = "high/h.", bool native = false); +HighscoreTable load_highscore_table(const std::filesystem::path& file); +bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows); + +} // namespace bmh::modern diff --git a/src/modern/game/league_pairings.cpp b/src/modern/game/league_pairings.cpp new file mode 100644 index 0000000..c999c5c --- /dev/null +++ b/src/modern/game/league_pairings.cpp @@ -0,0 +1,548 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/league_pairings.hpp" + +#include +#include +#include +#include + +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" +#include "game/match_engine.hpp" +#include "game/schedule.hpp" +#include "modern/game/source_tip.hpp" +#include "game/table.hpp" + +namespace bmh::modern { +namespace { +void require(bool value,const char* reason) { + if(!value) throw std::invalid_argument(reason); +} +void clear_computer_tip(LeaguePairingsOwner& owner) { + owner.computer_tip_active=false;owner.computer_tip_league=owner.computer_tip_round=-1; + owner.computer_tip_original.fill(0);owner.computer_tip_results.clear(); +} +void prepare_computer_tip(ModernState& g,LeaguePairingsOwner& owner, + const LeaguePairingsConstants& c,GameRandom& game) { + const uint32_t preferences_at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(owner.manager); + require(!owner.filter_active&&!owner.postponed_active&& + (g.memory.u8(preferences_at)&0x0f)<=3, + "pairings: Computer Tip supports only ordinary/search modes 0..3"); + require(owner.round>=0&&size_t(owner.league)=kResultsSize, + "pairings: Computer Tip Native seed/results unavailable"); + const auto page=modern::league_pairings_view_source(g,owner,c); + const size_t expected=league_fixtures(owner.league,owner.round+1).size(); + require(page.rows.size()==expected&&page.total_rows==int(expected), + "pairings: Computer Tip requires the complete ordinary fixture row set"); + for(const auto& row:page.rows) + require(row.raw_result==0xcc,"pairings: Computer Tip requires every visible result to be 0xcc"); + const int32_t source_seed=std::bit_cast(g.memory.u32(::bmh::layout::CurrentMatchday)); + require(source_seed>=0&&source_seed<=10000, + "pairings: Computer Tip rejects an unqualified signed Native seed"); + + const size_t first=result_index(owner.league,owner.round+1,0); + require(first+10<=g.results.size(),"pairings: Computer Tip ten-byte Source backup is unavailable"); + std::array original{}; + if(owner.computer_tip_active) { + require(owner.computer_tip_league==owner.league&&owner.computer_tip_round==owner.round&& + owner.computer_tip_results.size()==expected, + "pairings: stale Computer Tip forecast identity"); + original=owner.computer_tip_original; + for(size_t i=0;i<10;++i) + require(g.results[first+i]==original[i],"pairings: Native result slice changed under Computer Tip"); + } else { + std::copy_n(g.results.begin()+static_cast(first),10,original.begin()); + } + + struct Input { const LeaguePairingsRow* row; int home_rating,away_rating,home_secondary,away_secondary; }; + std::vector inputs;inputs.reserve(expected); + for(const auto& row:page.rows) { + require(row.source_round==owner.round&&row.fixture_index>=0&& + size_t(row.fixture_index) results;results.reserve(expected); + for(const auto& input:inputs) { + const auto& row=*input.row; + results.push_back({owner.league,row.source_round,row.fixture_index, + row.home.runtime_team,row.home.club_identity,row.away.runtime_team,row.away.club_identity, + row.raw_result,modern::source_tip_result(staged_game,c.computer_tip_gap,input.home_rating,input.away_rating, + input.home_secondary,input.away_secondary)}); + } + game=staged_game;owner.computer_tip_active=true; + owner.computer_tip_league=owner.league;owner.computer_tip_round=owner.round; + owner.computer_tip_original=original;owner.computer_tip_results=std::move(results); + g.memory.set8(preferences_at,uint8_t(g.memory.u8(preferences_at)|0x10)); +} +int filtered_fixture_count(int league,int team) { + int count=0; + for(int round=0;round=0&&o.manager<4&& + size_t(o.manager)=0&&o.runtime_club=0&&o.league<9&&o.round>=0&&o.round=-1&&(!o.active_phase||o.active_group>=0), + "pairings: invalid active presentation phase"); + require(g.memory.has(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&& + (((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0c)==0)|| + (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==4|| + (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==8)&& + g.memory.has(::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2+1), + "pairings: missing preferences or unsupported saved list mode"); + require(g.results.size()>=kResultsSize&&g.club_ids.size()>=size_t(league_clubs())&&g.league_rounds.size()>=9&& + g.memory.has(::bmh::layout::Postponed+0xef)&&g.memory.has(::bmh::layout::CompetitionCalendar+365*2+1), + "pairings: incomplete Native schedule"); + const auto selection_valid=[&](int team,int identity) { + return team<0 ? team>=-2&&identity==-1 : + team=0&&o.search_second>=-1)), + "pairings: stale or invalid search selection"); + const uint8_t mode=uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f); + const bool mode8=mode==8; + if(mode8) { + require(o.postponed_active&&!o.filter_active&&o.filter_team==-1&&o.filter_identity==-1&&o.filter_offset==0&& + o.search_first==-1&&o.search_second==-1&&o.search_first_identity==-1&&o.search_second_identity==-1&& + !o.search_second_click&&o.postponed_offset>=0&&o.postponed_offset%10==0, + "pairings: invalid postponed-list owner"); + const int count=postponed_fixture_count(g,o.league); + require((count==0&&o.postponed_offset==0)||(count>0&&o.postponed_offset=int(g.league_rounds.at(size_t(o.league)))&& + o.computer_tip_results.size()==expected&&g.memory.has(::bmh::layout::CurrentMatchday), + "pairings: invalid Computer Tip owner scope"); + const size_t first=result_index(o.league,o.round+1,0); + require(first+10<=g.results.size(),"pairings: Computer Tip result backup is unavailable"); + for(size_t n=0;n<10;++n) + require(g.results[first+n]==o.computer_tip_original[n], + "pairings: Computer Tip original result slice changed"); + const auto fixtures=league_fixtures(o.league,o.round+1); + require(fixtures.size()==expected,"pairings: Computer Tip fixture count changed"); + for(size_t n=0;n=0&&o.filter_offset%10==0&&o.filter_team>=-2, + "pairings: invalid Source club-filter mode"); + if(o.filter_team>=0) { + require(o.filter_team(g.league_rounds.at(size_t(league)),league_matchdays(league)-1); +} +LeaguePairingsTeam team_view(const ModernState& g,int team,int played) { + LeaguePairingsTeam out; out.runtime_team=team;out.club_identity=g.club_ids.at(size_t(team)); + if(played) { + const int r=played-1; + const size_t at=(size_t(team)*13+size_t(r/3))*2; + require(at+1>((r%3)*5))&31)+1; + } + constexpr std::array flags{0x1f1,0x1f2,0x1f4,0x1f8,0x1ff}; + for(size_t n=0;n0&&c.domestic_league_count<=9, + "pairings: unsupported Source calendar constants"); + require(c.calendar_class.at(size_t(league))<32,"pairings: invalid calendar mask shift"); + const uint32_t mask=league>=c.domestic_league_count?0x10u:1u<0xcc;} + +std::optional league_pairings_active_packet_source( + const ModernState& g,const LeaguePairingsOwner& owner,const std::vector& groups, + std::span referee_profiles) { + validate(g,owner); + // Mode4's armed -2 sentinel still uses the ordinary selected-round list. + // A selected filter and Mode8 explicitly clear local74 in Move. + if(owner.postponed_active||(owner.filter_active&&owner.filter_team>=0))return std::nullopt; + const auto fixtures=league_fixtures(owner.league,owner.round+1); + int found=-1; + for(size_t n=0;n=2&&group.fixtures[0]==fixtures.front().home&& + group.fixtures[1]==fixtures.front().away)found=int(n); + } + if(found<0)return std::nullopt; + const auto& group=groups[size_t(found)]; + require(group.fixtures.size()==fixtures.size()*2, + "pairings: incomplete active fixture vector"); + LeaguePairingsActivePacket packet; + packet.league=owner.league;packet.round=owner.round;packet.group_index=found; + packet.rows.reserve(fixtures.size()); + for(size_t n=0;n0x50+n, + "pairings: incomplete active referee/weather descriptor"); + const uint8_t referee=group.desc[0x10+n]; + require(size_t(referee)=0)&& + packet.league==owner.league&&packet.round==owner.round&&packet.group_index>=0&& + packet.group_index==owner.active_group,"pairings: stale active descriptor owner"); + const auto fixtures=league_fixtures(owner.league,owner.round+1); + require(packet.rows.size()==fixtures.size(),"pairings: incomplete active presentation rows"); + for(size_t n=0;n=0&&manager<4&&size_t(manager)=0&&out.runtime_club=0&&(e.value==0||e.value==1)&&bool(e.value)!=before.active_phase, + "pairings: invalid active presentation redraw"); + out.active_phase=bool(e.value);break; + case LeaguePairingsAction::reset: out.round=current_round(g,out.league);out.title_round=g.league_rounds.at(size_t(out.league));reset();break; + case LeaguePairingsAction::previous: + if(out.postponed_active) {if(out.postponed_offset>=10)out.postponed_offset-=10;break;} + if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&3)==0) { + if(out.filter_active&&out.filter_offset>=10)out.filter_offset-=10; + break; + } + out.round=(out.round+league_matchdays(out.league)-1)%league_matchdays(out.league);out.title_round=out.round;break; + case LeaguePairingsAction::next: + if(out.postponed_active) { + const auto page=modern::league_pairings_view_source(g,before,c); + if(page.rows.size()==10&&out.postponed_offset+10=0&& + out.filter_offset+10=0&&out.league<9,"pairings: invalid manager league preference"); + [[fallthrough]]; + case LeaguePairingsAction::select_league: + if(e.kind==LeaguePairingsAction::select_league) { + require(e.value>=0&&e.value<9,"pairings: invalid league selection");out.league=e.value; + } + if(out.league!=before.league) { + // LeagueMatchdays: retained round must be in the league and at/before + // its next round. Directparam0 does not apply the automatic reset. + if(out.round>=league_matchdays(out.league)||out.round>g.league_rounds.at(size_t(out.league))) + out.round=current_round(g,out.league); + out.title_round=out.round; + reset(); + } + break; + case LeaguePairingsAction::team_info: + case LeaguePairingsAction::search_team: { + require(!out.filter_active&&!(e.kind==LeaguePairingsAction::search_team&&out.postponed_active), + "pairings: filtered rows cannot open ordered search"); + require((e.kind==LeaguePairingsAction::search_team)==(out.search_first!=-1), + "pairings: row action does not match Source search ownership"); + const auto view=modern::league_pairings_view_source(g,before,c);bool found=false; + for(const auto& row:view.rows)for(const auto* team:{&row.home,&row.away}) + found|=team->runtime_team==e.value&&team->club_identity==e.expected_club_identity; + require(found,"pairings: stale fixture team identity"); + if(e.kind==LeaguePairingsAction::team_info)break; + if(!out.search_second_click) { + out.search_first=e.value;out.search_first_identity=e.expected_club_identity; + out.search_second=-1;out.search_second_identity=-1;out.search_second_click=true; + } else { + out.search_second=e.value;out.search_second_identity=e.expected_club_identity; + // LeagueMatchdays2 scans directed home/away fixtures in ascending round + // then row order. A missing self-pair keeps round and local30=1. + for(int round=0;roundruntime_team==e.value&&team->club_identity==e.expected_club_identity; + require(found,"pairings: stale filtered-row team identity"); + out.filter_team=e.value;out.filter_identity=e.expected_club_identity; + while(out.filter_offset>=filtered_fixture_count(out.league,out.filter_team)&&out.filter_offset>0) + out.filter_offset-=10; + break; + } + case LeaguePairingsAction::close: + reset();g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager), + uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xef)); + out.active_phase=false;out.active_group=-1; + out.closed=true;modern::stir_random(game,rand);return out; + case LeaguePairingsAction::unsupported: + throw std::invalid_argument("pairings: Original Zusatzaktion ist noch nicht verfügbar"); + } + validate(g,out); + const uint32_t at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager); + if(e.kind!=LeaguePairingsAction::computer_tip) + g.memory.set8(at,uint8_t(g.memory.u8(at)&0xef)); + return out; +} + +LeaguePairingsView league_pairings_view_source(const ModernState& g,const LeaguePairingsOwner& o, + const LeaguePairingsConstants& c) { + validate(g,o);LeaguePairingsView out;out.owner=o;out.played_rounds=g.league_rounds.at(size_t(o.league)); + out.total_rounds=league_matchdays(o.league);out.preferences=g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager)); + const bool postponed=o.postponed_active; + if(!postponed)out.match_date=round_date(g,o.league,o.round,c); + auto append_row=[&](int round,size_t n,const Fixture& fixture) { + LeaguePairingsRow row; + row.source_round=round;row.fixture_index=int(n); + row.home=team_view(g,fixture.home,out.played_rounds); + row.away=team_view(g,fixture.away,out.played_rounds); + row.raw_result=g.results.at(result_index(o.league,round+1,int(n))); + if(o.computer_tip_active) { + const auto match=std::find_if(o.computer_tip_results.begin(),o.computer_tip_results.end(), + [&](const auto& tip) {return tip.league==o.league&&tip.source_round==round&& + tip.fixture_index==int(n)&&tip.home_runtime_team==row.home.runtime_team&& + tip.home_club_identity==row.home.club_identity&& + tip.away_runtime_team==row.away.runtime_team&& + tip.away_club_identity==row.away.club_identity;}); + if(match!=o.computer_tip_results.end()) { + require(row.raw_result==match->original_result, + "pairings: Native result changed under Computer Tip forecast"); + row.computer_tip_result=match->predicted_result; + } + } + if(postponed) { + for(uint32_t k=0;k<40;++k) { + const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at); + if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) { + row.postponed_queue_slot=uint8_t(k);row.postponed_day=day; + row.postponed_date=g.season_start+day;break; + } + } + } else if(!modern::league_pairings_played_source(row.raw_result)&&row.raw_result!=0xcc) { + for(uint32_t k=0;k<40;++k) { + const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at); + if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) { + row.postponed_date=g.season_start+day;break; + } + } + } + if(!o.active_phase&&!postponed&&!(o.filter_active&&o.filter_team>=0)&&round>=out.total_rounds/2) { + const uint8_t raw=g.results.at(result_index(o.league,round+1-out.total_rounds/2,int(n))); + if(modern::league_pairings_played_source(raw))row.first_leg_result=raw; + } + if(o.filter_active&&o.filter_team>=0&&row.raw_result==0xcc) + row.scheduled_date=round_date(g,o.league,round,c); + out.rows.push_back(std::move(row)); + }; + if(postponed) { + out.page_offset=o.postponed_offset; + for(int round=0;round=o.postponed_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]); + ++out.total_rows; + } + } + } else if(o.filter_active&&o.filter_team>=0) { + out.page_offset=o.filter_offset; + for(int round=0;round=o.filter_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]); + ++out.total_rows; + } + } + } else { + const auto fixtures=league_fixtures(o.league,o.round+1); + out.total_rows=int(fixtures.size()); + for(size_t n=0;n +#include +#include +#include +#include + +#include "modern/game/modern_state.hpp" +#include "game/random.hpp" + +namespace bmh::modern { + + +// Normal LeagueScreenShown(2,0)->Move(0) only. The App owns the staged Native/W/G +// transaction. No mutator here calls a presenter, advances a day, or saves. + +LeaguePairingsOwner open_league_pairings_source(ModernState&,int manager,const LeaguePairingsConstants&); +LeaguePairingsOwner edit_league_pairings_source(ModernState&,const LeaguePairingsOwner&, + const LeaguePairingsEvent&,const LeaguePairingsConstants&,GameRandom&,WatcomRandom&); +// Pure, bounded Source projection; renderers never call a Native/RNG mutator. +LeaguePairingsView league_pairings_view_source(const ModernState&,const LeaguePairingsOwner&, + const LeaguePairingsConstants&); +// Read only active process descriptors, never reconstruct weather/referees from +// saved bytes or run event preparation. Last first-pair match follows Move. +std::optional league_pairings_active_packet_source( + const ModernState&,const LeaguePairingsOwner&,const std::vector&, + std::span referee_profiles); +void validate_league_pairings_active_packet_source(const ModernState&,const LeaguePairingsOwner&, + const LeaguePairingsActivePacket&); +bool league_pairings_played_source(uint8_t raw); +bool league_pairings_postponed_source(uint8_t raw); + +} // namespace bmh::modern diff --git a/src/modern/game/matchday.cpp b/src/modern/game/matchday.cpp new file mode 100644 index 0000000..3759833 --- /dev/null +++ b/src/modern/game/matchday.cpp @@ -0,0 +1,794 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/environment.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" + +#include +#include +#include +#include + +#include "modern/game/cup.hpp" +#include "game/schedule.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/table.hpp" + +namespace bmh::modern { + +namespace { + +// Competition class of each descriptor type (MatchEngineRuntimeField9): 0 league (cards count per +// team), 1-4 cup competitions with their own card counters, 0xFF = none. +constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255, + 4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0}; +// Clubs per league (LeagueSizes): five leagues of 18, four regional leagues of 12. +// (the clubs per league are kLeagueSizes, schedule.hpp) +// Three points for a win in every league (CareerSession_BeginFriendlyOpponentTable_RuntimeField, index 9 = "no league" reads the +// following table byte 18, also non-zero). +constexpr bool kThreePoints[10] = {true, true, true, true, true, true, true, true, true, true}; +constexpr size_t kClubRecord = 0x4a; +constexpr size_t kManagerRecord = 0xB0C; +constexpr size_t kBoard = 0x840, kBoardSlot = 0x58; + +uint32_t rd32(const std::vector& v, size_t o) { + return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16 | uint32_t(v.at(o + 3)) << 24); +} +void wr32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(x >> (8 * i)); +} +uint16_t rd16(const std::vector& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); } +void wr16(std::vector& v, size_t o, uint16_t x) { + v.at(o) = uint8_t(x); + v.at(o + 1) = uint8_t(x >> 8); +} + +int competition_class(int type) { return type >= 0 && type < 24 ? kCompetitionClass[type] : 255; } + +// TeamLeague2: league (0-8) of a club id, 9 for clubs outside the leagues. +int league_of(int team) { + if (team > 0x164) return 0; + int end = 0; + for (int l = 0; l < 9; l++) { + end += kLeagueSizes[l]; + if (team < end) return l; + } + return 9; +} + +// ClubRecord: record result `idx` of a club. The value of a result is +// home * home_weight - away * away_weight; `lower` keeps the smallest instead of the +// largest value. The stored result uses away_weight 1 if it was negative. +void club_record(ModernState& g, int club, int idx, int home, int away, bool lower, int home_weight, int away_weight, int opponent) { + size_t base = size_t(club) * kClubRecord; + uint8_t& r = g.club_table.at(base + 0x15 + idx); + int old_value = (r >> 4) * home_weight - (r & 0x0F) * away_weight; + int new_value = home * home_weight - away * away_weight; + if (!lower ? new_value <= old_value : old_value <= new_value) return; + if (away_weight < 0) away_weight = 1; + r = uint8_t((uint8_t(home * home_weight) << 4) + uint8_t(away * away_weight)); + wr16(g.club_table, base + 0x2a + idx * 2, g.club_ids.at(opponent)); + wr16(g.club_table, base + 0x3a + idx * 2, uint16_t(std::min(g.date, 0xFFFF))); +} + +} // namespace + +bool match_score(const MatchGroup& g, int m, int& home, int& away) { + if (!g.results.empty()) { + home = g.results.at(m) >> 4; + away = g.results.at(m) & 0x0F; + return true; + } + if (g.cup_results.size() == size_t(g.matches())) { + home = g.cup_results[m] >> 5 & 0x1F; + away = g.cup_results[m] & 0x1F; + return true; + } + return false; +} + +int sportschau_source_setting_index(const ModernState& state, const MatchGroup& group) { + const uint32_t id = le32(group.desc, 0xcc); + if (id <= 0x14) return id < 5 ? int(id) : std::min(int(id) + 12, 0x13); + const uint32_t source = id + 0x18; + return state.memory.has(source) ? int(uint8_t(state.memory.u8(source) + 5)) : -1; +} + +SportschauFixtureView sportschau_fixture_view(const ModernState& state, const MatchGroup& group, + int group_index, int fixture_index, + const std::vector& show_events) { + SportschauFixtureView view; + if (group_index < 0 || group_index > 0xff || fixture_index < 0 || fixture_index > 0xff || + size_t(fixture_index * 2 + 1) >= group.fixtures.size()) + return view; + + view.group = uint8_t(group_index); + view.fixture = uint8_t(fixture_index); + view.competition_type = group.desc.at(0); + view.fixture_flags = group.desc.at(1); + view.source_footer_variant = state.indoor ? 2 : ((group.desc.at(1) & 8) != 0 ? 1 : 0); + view.has_replay_progression_mode = state.memory.has(::bmh::layout::ReplayProgressionMode); + if (view.has_replay_progression_mode) view.replay_progression_mode = state.memory.u8(::bmh::layout::ReplayProgressionMode); + view.has_replay_chance_mode = state.memory.has(::bmh::layout::ReplayChanceMode); + if (view.has_replay_chance_mode) view.replay_chance_mode = state.memory.u8(::bmh::layout::ReplayChanceMode); + view.source_selection_available = state.sportschau_selection_available; + view.competition_id = le32(group.desc, 0xcc); + view.source_setting_index = int16_t(modern::sportschau_source_setting_index(state, group)); + view.home_team = int16_t(group.fixtures.at(size_t(fixture_index * 2))); + view.away_team = int16_t(group.fixtures.at(size_t(fixture_index * 2 + 1))); + view.source_selected = view.source_selection_available && modern::sportschau_selected(state, view.home_team); + if (size_t(fixture_index) < group.end_minute.size()) + view.source_played_minute = group.end_minute[size_t(fixture_index)]; + auto as_bytes = [](const std::string& s) { + return std::vector(s.begin(), s.end()); + }; + auto set_team = [&](int team, std::vector& full, std::vector& short_name, + bool& short_name_available, + bool& requires_font_fit, bool& requires_longest_word, uint16_t& badge_word) { + const std::string name = state.club_name(team); + full = as_bytes(name); + if (team >= 0 && size_t(team) * 2 + 1 < state.club_heap_78.size()) + badge_word = uint16_t(state.club_heap_78[size_t(team) * 2] | + uint16_t(state.club_heap_78[size_t(team) * 2 + 1]) << 8); + if (team >= 0 && team < first_foreign_cup()) { + requires_font_fit = true; + if (state.memory.has(::bmh::layout::ClubShortNameOffsets + uint32_t(team))) { + const uint8_t source = state.memory.u8(::bmh::layout::ClubShortNameOffsets + uint32_t(team)); + const size_t offset = source >> 4; + const size_t length = (source & 0x0f) + 1; + if (offset <= full.size()) { + short_name_available = true; + const size_t count = std::min(length, full.size() - offset); + short_name.assign(full.begin() + std::ptrdiff_t(offset), + full.begin() + std::ptrdiff_t(offset + count)); + } + } + } else { + short_name = full; + short_name_available = !short_name.empty(); + requires_font_fit = true; + requires_longest_word = true; + } + }; + set_team(view.home_team, view.home_name, view.home_short_name, view.home_short_name_available, + view.home_name_requires_font_fit, view.home_name_requires_longest_word, view.home_badge_word); + set_team(view.away_team, view.away_name, view.away_short_name, view.away_short_name_available, + view.away_name_requires_font_fit, view.away_name_requires_longest_word, view.away_badge_word); + int home = 0, away = 0; + view.score_known = modern::match_score(group, fixture_index, home, away); + if (view.score_known) { + view.home_goals = uint8_t(home); + view.away_goals = uint8_t(away); + } + + uint16_t ordinal = 0; + for (size_t i = 0; i + 1 < group.log.size(); i += 2) { + const uint16_t code_player = group.log[i]; + const uint16_t team_value = group.log[i + 1]; + const int team = team_value >> 7; + if (team != view.home_team && team != view.away_team) continue; + SportschauLogEvent event; + event.group = view.group; + event.fixture = view.fixture; + event.event_ordinal = ordinal++; + event.source_word_index = uint16_t(i); + event.source_code_player_word = code_player; + event.source_team_value_word = team_value; + event.source_code = uint8_t(code_player >> 12); + event.player_id = uint16_t(code_player & 0x0fff); + event.team_id = int16_t(team); + event.source_value = uint8_t(team_value & 0x7f); + event.consumes_following_pair = event.source_code == 0 || event.source_code == 1; + event.has_following_word = i + 2 < group.log.size(); + event.has_following_pair = i + 3 < group.log.size(); + if (event.has_following_word) { + event.following_code_player_word = group.log[i + 2]; + const int player = event.following_code_player_word & 0x0fff; + if (player != 0x0fff) event.following_player_name = as_bytes(state.player_name(player)); + } + if (event.has_following_pair) event.following_team_value_word = group.log[i + 3]; + if (event.player_id != 0x0fff) event.player_name = as_bytes(state.player_name(event.player_id)); + view.log_events.push_back(std::move(event)); + } + + for (const ShowEvent& event : show_events) + if (event.group == view.group && event.match == view.fixture) view.show_events.push_back(event); + return view; +} + +bool book_money(ModernState& g, int manager, int32_t amount, bool force, bool statistics) { + if (g.level == 0) return true; + size_t rec = size_t(manager) * kManagerRecord; + const uint32_t balance = rd32(g.manager_records, rec + 0x314); + const uint32_t credit = rd32(g.manager_records, rec + 0x31c); + // BookMoney2 adds the Native dwords before a signed comparison and subtracts + // the amount in the same 32-bit register width. Preserve that wrap without + // C++ signed-overflow undefined behavior at the account limits. + if (!force && amount >= 0 && std::bit_cast(balance + credit) < amount) return false; + wr32(g.manager_records, rec + 0x314, balance - uint32_t(amount)); + if (statistics) { + if (amount < 0) + wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) - uint32_t(amount)); + else + wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + uint32_t(amount)); + } + return true; +} + +uint32_t pay_bonus(ModernState& g, int manager, int board_slot, int index, bool pay) { + size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot; + uint32_t rate = g.tactics.at(slot + 0x12 + index); + if (rate == 0) return 0; + uint32_t factor = index > 2 ? 5 : 1; + uint32_t amount = factor * (rate * rd32(g.tactics, slot + 0x50)) / 100; + if (pay) { + size_t rec = size_t(manager) * kManagerRecord; + uint32_t tax = g.manager_records.at(rec + 0x172); + if (tax != 0) amount -= ((tax >> 5 & 7) + 3) * amount * 10 / 100; + modern::book_money(g, manager, int32_t(amount), true); + wr32(g.manager_records, rec + 0x334, rd32(g.manager_records, rec + 0x334) + amount); + } + return amount; +} + +void player_statistic(ModernState& g, int type, int player, int manager, int slot, int kind, int minute) { + int cls = (type == 0xb && manager >= 0 && !g.manager_teams.empty() && g.manager_teams[0] == no_team()) + ? 3 + : int8_t(competition_class(type)); + if (cls < 0 || cls >= 4) return; + Player& p = g.players.at(player); + const uint32_t w364 = p.w364; + const size_t board = manager >= 0 ? size_t(manager) * kBoard + size_t(slot) * kBoardSlot : 0; + if (kind == 0) { // appearance + if (cls == 3 && (g.player_bonus.at(player) & 0x7F) < 0x7F) g.player_bonus.at(player)++; + if (manager >= 0) { + modern::pay_bonus(g, manager, slot, 2, true); + if (cls < 3) g.tactics.at(board + 7 + cls)++; + wr16(g.tactics, board + 0x48, uint16_t(rd16(g.tactics, board + 0x48) + 1)); + } + if (cls == 0) p.w364 = (w364 & 0x03FFFFFFu) | ((w364 >> 26) + 1) << 26; // league games + } else if (kind == 1) { // goal + if (manager >= 0) { + modern::pay_bonus(g, manager, slot, 0, true); + wr16(g.tactics, board + 0x4a, uint16_t(rd16(g.tactics, board + 0x4a) + 1)); + if (cls == 0) g.manager_records.at(size_t(manager) * kManagerRecord + 0x1ae + std::min(minute, 89) / 5)++; + } + // league goals in bits 2-7 (a 64th goal carries into bit 8, as in the original) + if (cls == 0) p.w364 = (w364 & 0xFFFFFF03u) | ((((w364 >> 2) & 0x3F) << 2) + 4); + } else if (kind == 2) { // assist + if (manager >= 0) wr16(g.tactics, board + 0x4c, uint16_t(rd16(g.tactics, board + 0x4c) + 1)); + if (cls == 0) p.w368 = (p.w368 & 0xFF03FFFFu) | ((((p.w368 >> 18) & 0x3F) + 1) << 18); + } +} + +void finish_match(ModernState& g, MatchGroup& grp, int m, int minute, GameRandom& game) { + if (grp.end_minute.at(m) == 0) grp.end_minute.at(m) = uint8_t(minute); + for (int side = 0; side < 2; side++) { + int manager = g.manager_of(grp.fixtures.at(m * 2 + side)); + if (manager < 0) continue; + int home = 0, away = 0; + modern::match_score(grp, m, home, away); + int own = side ? away : home, opp = side ? home : away; + int points = 0; + if (own == opp) points = 1; + if (int8_t(own) > int8_t(opp)) points = 2; + for (int slot = 0; slot < 24; slot++) { + size_t at = size_t(manager) * kBoard + size_t(slot) * kBoardSlot; + int start = int8_t(g.tactics.at(at + 0x10)); // minute the player came on + for (int i = 0; i < points; i++) modern::pay_bonus(g, manager, slot, 1, true); + if (start >= 126) continue; + // Getting used to the place: a quarter of the minutes played (half in the + // competitions 5 and 7), at most 99. + int8_t delta = int8_t((minute - start) / 4); + if (grp.desc.at(0) == 5 || grp.desc.at(0) == 7) delta = int8_t(delta / 2); + if (g.indoor) start = int8_t(start) >> 2; + int used = int8_t(g.tactics.at(at + 0xf)) + delta; + g.tactics.at(at + 0xf) = uint8_t(std::clamp(used, 0, 99)); + // The player's own place (bytes 0/1) moves one step towards the board place. + if (game.range(0, 90) < minute - start) { + for (int k = 0; k < 2; k++) { + uint8_t& cur = g.tactics.at(at + k); + uint8_t target = g.tactics.at(at + 0x41 + k); + if (cur < target) cur++; + if (cur > target) cur--; + } + } + } + } +} + +void update_club_table(ModernState& g, int home, int away, int hg, int ag) { + if (g.indoor || g.club_table.empty()) return; + const size_t H = size_t(home) * kClubRecord, A = size_t(away) * kClubRecord; + auto add16 = [&](size_t o, int v) { wr16(g.club_table, o, uint16_t(rd16(g.club_table, o) + v)); }; + // Only the first league and the regional leagues keep points in this table (the + // condition tests the home club only). + const bool league = home < kLeagueSizes[0] || (home >= german_clubs() && home < league_clubs()); + const int win_points = kThreePoints[league_of(home)] ? 3 : 2; + if (league) { + add16(H + 0x20, hg); + add16(H + 0x22, ag); + add16(A + 0x20, ag); + add16(A + 0x22, hg); + } + uint8_t h[21], a[21]; // streaks: t * 3 + (0 all, 1 home, 2 away) + std::copy_n(g.club_table.begin() + H, 21, h); + std::copy_n(g.club_table.begin() + A, 21, a); + club_record(g, home, 2, hg, ag, false, 1, 0, away); // most goals scored at home + club_record(g, away, 7, hg, ag, false, 1, 0, home); // most goals conceded away + club_record(g, home, 3, hg, ag, false, 0, -1, away); // most goals conceded at home + club_record(g, away, 6, hg, ag, false, 0, -1, home); // most goals scored away + auto bump = [](uint8_t* s, int t, int j) { s[t * 3 + j]++, s[t * 3]++; }; + auto clear = [](uint8_t* s, int t, int j) { s[t * 3 + j] = 0, s[t * 3] = 0; }; + // streak 5: without conceding, 6: without scoring + if (ag == 0) bump(h, 5, 1), bump(a, 6, 2); + else clear(h, 5, 1), clear(a, 6, 2); + if (hg == 0) bump(h, 6, 1), bump(a, 5, 2); + else clear(h, 6, 1), clear(a, 5, 2); + if (ag < hg) { // home win + if (league) { + add16(H + 0x1e, win_points); + add16(H + 0x24, 1); + add16(A + 0x28, 1); + } + bump(h, 0, 1); + for (int t = 1; t < 4; t++) clear(h, t, 1); + club_record(g, home, 0, hg, ag, false, 1, 1, away); // biggest home win + club_record(g, away, 5, hg, ag, false, 1, 1, home); // biggest away defeat + bump(h, 4, 1); + clear(a, 0, 2), clear(a, 2, 2), clear(a, 4, 2); + bump(a, 1, 2), bump(a, 3, 2); + } else if (hg == ag) { // draw + if (league) { + add16(H + 0x1e, 1); + add16(A + 0x1e, 1); + add16(H + 0x26, 1); + add16(A + 0x26, 1); + } + clear(h, 0, 1), clear(h, 1, 1); + for (int t = 2; t < 5; t++) bump(h, t, 1); + clear(a, 0, 2), clear(a, 1, 2); + for (int t = 2; t < 5; t++) bump(a, t, 2); + } else { // away win + if (league) { + add16(A + 0x1e, win_points); + add16(H + 0x28, 1); + add16(A + 0x24, 1); + } + bump(a, 0, 2); + for (int t = 1; t < 4; t++) clear(a, t, 2); + clear(h, 0, 1), clear(h, 2, 1), clear(h, 4, 1); + bump(a, 4, 2); + bump(h, 1, 1), bump(h, 3, 1); + club_record(g, home, 1, hg, ag, true, 1, 1, away); // biggest home defeat + club_record(g, away, 4, hg, ag, true, 1, 1, home); // biggest away win + } + std::copy_n(h, 21, g.club_table.begin() + H); + std::copy_n(a, 21, g.club_table.begin() + A); + // Human managers keep their club's best streaks (manager record +0x5e). + for (int side = 0; side < 2; side++) { + int club = side ? away : home; + const uint8_t* s = side ? a : h; + for (size_t k = 0; k < g.manager_teams.size(); k++) { + if (g.manager_teams[k] != club) continue; + for (int i = 0; i < 21; i++) { + uint8_t& best = g.manager_records.at(k * kManagerRecord + 0x5e + i); + if (best < s[i]) best = s[i]; + } + } + } +} + +void update_morale(ModernState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand) { + uint8_t& morale = g.team_morale.at(team); + const int value = morale & 0x3F; + int sign = 1; + int diff = int16_t(side + (own_goals - opp_goals) + (5 - value / 5)); + int step = std::abs(25 - value) / 5; + if (diff < 0 || (diff == 0 && value > 25)) { + sign = -1; + diff = -diff; + } + // Far from the middle (25) morale moves slowly towards the extremes. + if ((sign == 1 && value > 12) || (sign == -1 && value < 37)) step = 5 - step; + if (int16_t(step) == 0) step = 1; + diff = std::clamp(diff, 1, 3); + int range = int16_t(step * diff); + if (range > 12) range = 12; + if (range == 0) return; + int v = int16_t(value + sign * int16_t(rand.range(1, range))); + v = std::clamp(v, 0, 0x2f); + morale = uint8_t(v | (morale & 0xC0)); +} + +void develop_players(ModernState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand) { + const int type = grp.desc.at(0); + for (int side = 0; side < 2; side++) { + const int team = grp.fixtures.at(m * 2 + side); + if (!(team < first_foreign_cup() || team == no_team())) continue; + const uint8_t cls = (type == 0xb && team == no_team()) ? 3 : uint8_t(competition_class(type)); + const int manager = g.manager_of(team); + const SquadRange range = squad_range(team); + + // 1 in 11: the team gets the next trend of the rotation (none/down, neutral, up); + // the rotation is steered by the balance of all attribute changes so far. + if (game.range(0, 10) == 0) { + if (g.development_balance < -50) g.trend_rotation = 2; + if (g.development_balance > 50) g.trend_rotation = 0; + uint16_t& f = g.team_flags.at(team); + f = uint16_t(((f & 0xFFF8) + g.trend_rotation * 2) & 0xFFFF); + if (++g.trend_rotation == 3) g.trend_rotation = 0; + } + const int8_t trend = int8_t(((g.team_flags.at(team) >> 1) & 3) - 1); + int capped = 0; // local_30: attributes that hit 99 (carries over between players) + + for (size_t s = range.first; s < range.first + range.count; s++) { + const int player = g.squad_slots.at(s) & 0x0FFF; + if (player == 0xFFF) break; + Player& p = g.players.at(player); + const int odds = manager >= 0 ? 6 : 3; + + if (trend != 0 && game.range(0, 3) == 0) { + int8_t d = trend; + if (rand.range(0, 4) == 0) d = int8_t(-trend); + // form (shift 0, kept within 35-65), technique (7), condition (14) + uint32_t w = p.w35c; + for (int sh = 0; sh < 15; sh += 7) { + if (sh >= 7 && capped == 0 && game.range(0, odds) != 0) continue; + const int8_t old = int8_t((w >> sh) & 0x7F); + int8_t v = int8_t(old + d); + if (capped != 0 || game.range(0, 1) != 0) v = int8_t(v + d); + if (sh != 0) { + if (v < 0) v = 0; + if (v > 99) { + // Quirk of the original: the first attribute to pass 99 restarts + // the loop - 99 is written to the form and technique and + // condition are processed (again). + if (capped == 0) sh = 0; + v = 99; + capped++; + } else if (capped != 0) { + capped--; + } + } else { + v = int8_t(std::clamp(v, 0x23, 0x41)); + } + if (sh != 0) g.development_balance += v - old; + w = (w & ~(0x7Fu << sh)) + (uint32_t(int32_t(v)) << sh); + } + p.w35c = w; + // the seven skills follow the team trend (1 in 9 each) + uint32_t k = p.w368; + for (int sh = 0; sh < 13; sh += 2) { + if (game.range(0, 8) != 0) continue; + int v = int((p.w368 >> sh) & 3) + trend; + v = std::clamp(v, 0, 3); + k = (k & ~(3u << sh)) + (uint32_t(v) << sh); + } + p.w368 = k; + } + if (p.w364 & 0x1000) // played in this match + modern::player_statistic(g, type, player, manager, int(s - range.first), 0, 0x5a); + if (p.w35c >> 27) continue; // injured players are handled elsewhere + + if (cls != 0xFF) { + const int duration = (p.w364 >> 16) & 0xF; + if (duration != 0 && !(p.w364 & 0x100000)) { + // injury (not a ban) heals by one match; in cups the card counter restarts + if (cls != 0) { + if (p.w368 >> 24 & 1) p.w368 &= 0xF8FFFFFFu; + else p.w368 = (p.w368 & 0xF8FC3FFFu) | 0x4000u; + } + p.w364 = (p.w364 & 0xFFE0FFFFu) | uint32_t(duration - 1) << 16; + } else if (cls == 0) { + // league: every fifth yellow card (booked in this match) bans for one match + int yellow = (p.w368 >> 14) & 0xF; + if ((g.squad_slots.at(s) & 0x1000) && yellow > 4 && yellow % 5 == 0) p.w364 |= 0x10000u; + } + } + g.squad_slots.at(s) &= 0xCFFF; // clear the booked/substituted slot flags + if (cls == 0) continue; + + // Cups: move the card counters of this competition into the player's card word + // and load those of the next competition (the w368 card bits are shared). + if (p.w368 >> 24 & 1) p.w368 |= 0xC000u; + uint16_t& cards = g.player_cards.at(player); + switch (cls) { + case 1: p.w364 = (p.w364 & 0xFFFFFCFFu) | ((p.w368 >> 14) & 3) << 8; break; + case 2: p.w364 = (p.w364 & 0xFFFFF3FFu) | ((p.w368 >> 14) & 3) << 10; break; + case 3: cards = uint16_t((cards & 0x3FFF) | (p.w368 & 0xC000)); break; + case 4: cards = uint16_t((cards & 0xCFFF) | ((p.w368 >> 14) & 3) << 12); break; + default: break; + } + p.w368 = (p.w368 & 0xF8FC3FFFu) | uint32_t((cards >> 5) & 0xF) << 14 | uint32_t((cards >> 9) & 7) << 24; + if (p.w35c >> 27 == 0) p.w364 = (p.w364 & 0xFFE0FFFFu) | ((p.w364 >> 13) & 7) << 16; + } + } +} + +void process_group(ModernState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index, const SportschauFixtureHook& sportschau, + const std::vector* show_events, const SportschauReplayHooks* replay) { + auto owned = grp; + modern::process_group(g, owned, game, rand, report, group_index, sportschau, show_events, replay, nullptr); +} + +void process_group(ModernState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index, const SportschauFixtureHook& sportschau, + const std::vector* show_events, const SportschauReplayHooks* replay, + const SportschauRatingTables* ratings) { + const int type = grp.desc.at(0); + auto store_awards = [&] { + if (group_index < 0 || group_index >= 6) return; + const uint32_t base = ::bmh::layout::MatchdayGroupDescriptors + uint32_t(group_index) * 0xd0; + for (size_t i = 0; i < 11; ++i) { + if (g.memory.has(base + 0x70 + uint32_t(i))) + g.memory.set8(base + 0x70 + uint32_t(i), grp.desc.at(0x70 + i)); + if (g.memory.has(base + 0x9c + uint32_t(i * 2 + 1))) + g.memory.set16(base + 0x9c + uint32_t(i * 2), le16(grp.desc, 0x9c + i * 2)); + } + }; + if (ratings) { + // FinishEvent/BuildSideRecords reset eleven score bytes, retaining old slot ids. + std::fill_n(grp.desc.begin() + 0x70, 11, uint8_t(0)); + store_awards(); + } + // The original walks the fixtures with a pointer (puVar2) that only moves on in the + // morale step of a played match. After a match that was not played, the club records and + // the morale of every following match are therefore booked on the teams of the match + // before it (the player development and the manager records use the match index). + size_t cursor = 0; + for (int m = 0; m < grp.matches(); m++) { + // The original keeps local_70 (kickoff_void_mask) separately from the descriptor: + // desc+0xb8 also gains ended-match bits as the minute loop runs. Its fixture pointer + // advances only for played matches, so a void fixture must not advance `cursor`. + if (grp.kickoff_void_mask & (1u << m)) continue; + // A postponed league match can also retain its 0xCD result byte. + if (!grp.results.empty() && (grp.results.at(size_t(m)) & 0xCC) == 0xCC) continue; + int home = 0, away = 0; + if (!modern::match_score(grp, m, home, away)) { + report.fail("matchday processing needs the score"); + return; + } + const int ht = grp.fixtures.at(cursor), at = grp.fixtures.at(cursor + 1); + cursor += 2; + if (type == 0 || type == 10) modern::update_club_table(g, ht, at, home, away); + // MatchdayIntro sits between table updates and morale. Core owns its enabled + // replay scene draws; the old fixture callback remains a pure observer. + if ((sportschau || replay || ratings) && group_index >= 0) { + const auto view = sportschau_fixture_view(g, grp, group_index, m, + show_events ? *show_events : std::vector{}); + if (replay) present_sportschau_replay(g, grp, view, game, rand, *replay); + if (ratings) { rate_sportschau_players(g, grp, view, rand, *ratings); store_awards(); } + if (sportschau) sportschau(g, view); + } + modern::update_morale(g, ht, home, away, 0, rand); + modern::update_morale(g, at, away, home, 1, rand); + modern::manager_match_record(g, grp, m, home, away, report); + if (report.unsupported) return; + modern::develop_players(g, grp, m, game, rand); + } +} + +void stir_random(GameRandom& game, WatcomRandom& rand) { + int n = int16_t(rand.range(100, 300)); + for (int i = 0; i < n; i++) game.range(0, 1); +} + +bool league_screen_shown(const std::vector& buttons, int param_1, int param_2, int league) { + if (param_2 == 0 || param_2 >= 200) return true; // called from the desk: always shown + int kind = param_1 - 1; + if (param_1 == 2 && (param_2 == 90 || param_2 == 120)) kind = 2; + int row = league; + if (league > 4) row = std::min(league + 12, 19); + if (param_2 == 45 && kind == 0) return false; + return buttons.at(size_t(kind + row * 9)) == 0; +} + + +int table_position(const ModernState& g, int team) { + if (team >= league_clubs()) return 2; + int league = league_of(team); + int rounds = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0; + if (rounds == 0) return -1; + unsigned u = unsigned(rounds - 1); + int word = int16_t(rd16(g.position_history, (size_t(u / 3) + size_t(team) * 13) * 2)); + return (word >> ((u % 3) * 5)) & 0x1F; +} + +void rate_manager(ModernState& g, int manager, int rating, int competition) { + uint8_t* hist = g.manager_ratings.data() + size_t(competition) * 10 + size_t(manager) * 0x3c; + std::copy_backward(hist, hist + 9, hist + 10); // Int16T: shift the last 9 up + hist[0] = uint8_t(rating); + int sum = 0; + for (int s = 0; s < 10; s++) sum = int16_t(sum + ((100 - 10 * s) * hist[s]) / 100); + wr16(g.manager_records, size_t(manager) * kManagerRecord + 0x8aa + size_t(competition) * 2, uint16_t(sum)); +} + +void manager_match_record(ModernState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report) { + const int type = grp.desc.at(0); + for (size_t k = 0; k < g.manager_teams.size(); k++) { + const size_t rec = k * kManagerRecord; + int side = -1, opponent = 0; + for (int s = 0; s < 2; s++) + if (g.manager_teams[k] == grp.fixtures.at(m * 2 + s)) { + side = s; + opponent = grp.fixtures.at(m * 2 + 1 - s); + break; + } + if (side < 0) continue; + // opponent id as the original keeps it: its low byte (0xFE for ids >= 256) + const int opp = opponent < 0x100 ? opponent : 0xFE; + // last results (home | away << 4) and fixtures, newest first + std::copy_backward(g.manager_records.begin() + rec + 0x212, g.manager_records.begin() + rec + 0x217, + g.manager_records.begin() + rec + 0x218); + std::copy_backward(g.manager_records.begin() + rec + 0x292, g.manager_records.begin() + rec + 0x2a6, + g.manager_records.begin() + rec + 0x2aa); + g.manager_records.at(rec + 0x212) = uint8_t(home_goals + (away_goals << 4)); + for (int i = 0; i < 2; i++) wr16(g.manager_records, rec + 0x292 + i * 2, uint16_t(grp.fixtures.at(m * 2 + i))); + int own = side ? away_goals : home_goals, against = side ? home_goals : away_goals; + int rating = side ? 110 : 90; // an away game counts more + if (uint8_t(own) > uint8_t(against)) { + // league win bonus from the sponsor (record +0x173 thousands, less for + // higher +0x210 levels) + int bonus = g.manager_records.at(rec + 0x173); + if (type == 0 && bonus != 0) { + int level = g.manager_records.at(rec + 0x210); + if (level > 2) level--; + int32_t amount = (4 - level) * bonus * 1000; + if (g.level != 0) { + wr32(g.manager_records, rec + 0x314, rd32(g.manager_records, rec + 0x314) + uint32_t(amount)); + wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) + uint32_t(amount)); + } + } + rating += 20; + } + if (uint8_t(own) < uint8_t(against)) rating -= 20; + // MatchdayRuntimeField (u16 every 4 bytes): competitions that rate the manager. A league match + // counts the table place; a cup match its weight plus twice the rounds played in the + // stage and in every earlier one (link +0x15). All go into the league history (0). + static const uint16_t kRatingWeight[14] = {1, 12, 16, 20, 18, 0, 0, 0, 0, 14, 1, 0, 12, 10}; + const uint16_t weight = type < 14 ? kRatingWeight[type] : 0; + if (weight != 0) { + if (type != 0) { + int add = weight; + uint32_t e = le32(grp.desc, 0xcc); + for (int guard = 0; guard < 64; guard++) { + add += g.memory.u8(e + 0x1d) * 2; + const int8_t previous = int8_t(g.memory.u8(e + 0x15)); + if (previous == -1) break; + e = modern::cup_entry_address(previous); + } + rating += int16_t(add); + } else { + int league = league_of(g.manager_teams[k]); + int size = league < 9 ? kLeagueSizes[league] : 0; + rating += (size - modern::table_position(g, g.manager_teams[k])) * 4; + } + rating = std::clamp(int16_t(rating), int16_t(0), int16_t(200)); + modern::rate_manager(g, int(k), rating, 0); + } + if (opp < first_foreign_cup()) { + size_t at = k * 0x690 + size_t(opp) * 10 + (side == 1 ? 5 : 0); + std::copy_backward(g.manager_results.begin() + at, g.manager_results.begin() + at + 4, + g.manager_results.begin() + at + 5); + g.manager_results.at(at) = uint8_t(own + (against << 4)); + } + } +} + + +// ManagerOf(manager, 0, value): the manager's position of this season. +static void store_season_position(ModernState& g, int manager, int value) { + int season = std::min(g.season, 0x31); + g.manager_records.at(size_t(manager) * kManagerRecord + 0xda + size_t(season) * 3) = uint8_t(value); +} + +// StoreStrengthHistory: strength and position history of a human manager's club (38 entries). +static void store_strength_history(ModernState& g, int manager) { + const size_t rec = size_t(manager) * kManagerRecord; + const int team = g.manager_teams.at(manager); + int n = g.manager_records.at(rec + 0x284); + if (n < 0x26) { + g.manager_records.at(rec + 0x284) = uint8_t(n + 1); + } else { + std::copy(g.manager_records.begin() + rec + 0x223, g.manager_records.begin() + rec + 0x248, + g.manager_records.begin() + rec + 0x222); + std::copy(g.manager_records.begin() + rec + 0x249, g.manager_records.begin() + rec + 0x26e, + g.manager_records.begin() + rec + 0x248); + n = 0x25; + } + g.manager_records.at(rec + 0x222 + n) = uint8_t(team_average(g, team, 0xFF).value); + int pos = modern::table_position(g, team); + if (pos == -1) pos = (kLeagueSizes[g.manager_records.at(rec + 0x210)] - 1) >> 1; + g.manager_records.at(rec + 0x248 + n) = uint8_t(pos); +} + +void advance_league_rounds(ModernState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report, + const CompetitionWinnerHook& winner) { + // CalendarFirstLeague / CalendarLeagueCounts: first league and league count of competition bits 0-7 + const uint8_t* kFirst = kGroupLeague; // (schedule.hpp: the groups of the loaded game) + const uint8_t* kCount = kGroupLeagues; + for (int bit = 0; bit < 19; bit++) { + if (!(competitions >> bit & 1)) continue; + if (bit >= 5) { + report.fail("cup round bookkeeping (AdvanceCup)"); + return; + } + const int end = bit < 4 ? bit + 1 : 8; + for (int c = bit; c < end; c++) { + for (int league = kFirst[c]; league < kFirst[c] + kCount[c]; league++) { + if (league == 0) { + for (size_t m = 0; m < g.manager_teams.size(); m++) { + modern::advance_youth_teams(g, int(m), rand); + const size_t rec = m * kManagerRecord; + if (g.league_rounds.at(0) == 0x10) wr32(g.manager_records, rec + 0x320, rd32(g.manager_records, rec + 0x308)); + uint8_t& d = g.manager_records.at(rec + 0x220); // point deduction countdown + if (d >> 5 == 1) d = (d & 0x1F) < 2 ? 0 : uint8_t((d & 0xE0) | ((d & 0x1F) - 1)); + } + } + const int round = g.league_rounds.at(league); + g.league_rounds.at(league) = uint8_t(round + 1); + LeagueTable t = compute_league_table(g, league, 0, league_matchdays(league), 7, kThreePoints[league] ? 1 : 0); + const int first = league_first_team(league); + for (int i = 0; i < t.size; i++) { + const int team = first + i; + const int rank = t.rank(i); + size_t at = (size_t(round / 3) + size_t(team) * 13) * 2; + wr16(g.position_history, at, uint16_t(rd16(g.position_history, at) | rank << ((round % 3) * 5))); + const int manager = g.manager_of(team); + if (manager >= 0) { + int base = first; + if (league_first_team(3) <= base) base -= 18; + store_season_position(g, manager, base + rank + 1); + store_strength_history(g, manager); + } + } + // OnceSecondDivisionLeagueHasPlayedAll, once the second division (league 2) has played all its rounds + // (in the last competition of the loop, after each of its leagues): the + // clubs placed 1-2 in leagues 2 and 3 (TablePosition, positions counted from 0) + // go into the team list of the promotion play-off (Teams), its results + // (MatchdayGroupWorkspace) are cleared and competition MatchdayRuntimeField2 (0xd) starts + if (c + 1 == end && g.league_rounds.at(2) == league_matchdays(2)) { + uint32_t n = 0; + for (int l = 2; l < 4; l++) + for (int team = league_first_team(l); team < league_first_team(l) + kLeagueSizes[l]; team++) { + const uint8_t pos = uint8_t(modern::table_position(g, team)); + if (pos != 0 && pos < 3) g.memory.set16(::bmh::layout::Teams + n++ * 2, uint16_t(team)); + } + for (uint32_t i = 0; i < 0x20; i++) g.memory.set8(::bmh::layout::MatchdayGroupWorkspace + i, 0xcc); + for (uint32_t i = 0; i < 8; i++) { // AddCompetition(0xd) + if (int8_t(g.memory.u8(::bmh::layout::ActiveSelectors + i)) == 0xd) break; + if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + g.memory.set8(::bmh::layout::ActiveSelectors + i, 0xd); + break; + } + } + } + // the first division is over: its leader (OnTableJust(0, 0) on the table just + // computed) is champion - the winner screen (CompetitionWinnerScreen(0, 0), clears + // CareerSession_BeginFriendlyOpponentTable_ExecutableField2), the list of title holders (ListTitleHoldersAf(club, 0)), a human + // champion's record (+0x8a4) and Cup_AdvanceCup_RuntimeField6 + if (league == 0 && g.league_rounds.at(0) == league_matchdays(0)) { + int champion = -1; + for (int i = 0; i < t.size && champion < 0; i++) + if (t.rank(i) == 0) champion = first + i; + if (champion < 0) champion = 0; // (OnTableJust returns 0 when none is found) + if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner) + winner(g, {0, uint16_t(champion)}); + if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) g.memory.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + g.memory.set16(::bmh::layout::Titles + uint32_t(std::min(g.season, 0x31)) * 2, uint16_t(champion)); + const int manager = g.manager_of(champion); + if (manager >= 0) { + const size_t at = size_t(manager) * kManagerRecord + 0x8a4; + wr16(g.manager_records, at, uint16_t(rd16(g.manager_records, at) + 1)); + } + g.memory.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, uint16_t(champion)); + } + } + } + } +} + +} // namespace bmh::modern diff --git a/src/modern/game/matchday.hpp b/src/modern/game/matchday.hpp new file mode 100644 index 0000000..8b652b8 --- /dev/null +++ b/src/modern/game/matchday.hpp @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/matchday.hpp" +// What happens to a matchday after the final whistle (BMH.exe V2.24 + supported rule profile patch). +// +// The matchday driver (the function around 0x39xxx that calls EndPhase for every +// phase) continues after the last phase with, per match group and match: +// 1. UpdateClubTable league record of both clubs (points, goals, streaks, records) +// 2. morale both teams' morale moves towards the result (Watcom rand) +// 3. ManagerMatchRecord a human manager's match record, bonuses and rating +// 4. DevelopPlayers player development: team trends move form/technique/condition and +// skills (game RNG), appearances, injuries heal by one matchday, +// yellow card bans, card counters per competition +// Before that, the end of every phase calls FinishMatch per match: it stores the end +// minute and lets a human manager's players get used to their places on the tactics +// board and earn their bonus (game RNG). + +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/sportschau_presentation.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// Score of match m of a group (MatchScore, read mode): league result byte or the cup +// result of the current leg. Returns false if the score is not known. +bool match_score(const MatchGroup& g, int m, int& home, int& away); + +// BookMoney2: books `amount` from a human manager's account (record +0x314). Without +// `force` a payment larger than balance + credit (+0x31c) is refused (the original shows a +// message). Game level 0 has no money at all. +// With `statistics` (the caller sets FinanceStatisticsEnabled) the amount is also added to the +// income (+0x874, negative amounts) or expense (+0x8a0) statistics. +bool book_money(ModernState& g, int manager, int32_t amount, bool force, bool statistics = false); + +// PayBonus: bonus of one player on the tactics board: the board's bonus rate for +// `index` (slot byte 0x12 + index: 0 goal, 1 point, 2 appearance, ...) times the player's +// bonus base (slot +0x50) / 100, five-fold for index > 2. With `pay` the tax (record +// +0x172) is deducted and the amount is paid. Returns the amount. +uint32_t pay_bonus(ModernState& g, int manager, int board_slot, int index, bool pay); + +// PlayerStatistic: statistics of one player. kind 0 appearance, 1 goal, 2 assist. +// competition_type = descriptor byte 0; `manager` = human manager of the player's team +// or -1; `slot` = the player's slot relative to the squad start (tactics board index). +void player_statistic(ModernState& g, int competition_type, int player, int manager, int slot, int kind, int minute); + +// FinishMatch for match m at the end of a phase lasting `minute` minutes. +void finish_match(ModernState& g, MatchGroup& grp, int m, int minute, GameRandom& game); + +// UpdateClubTable: league record of home and away club after a result. +void update_club_table(ModernState& g, int home, int away, int home_goals, int away_goals); + +// Morale step of the matchday driver for one side (0 home, 1 away) of a finished match. +void update_morale(ModernState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand); + +// DevelopPlayers: player development and bookkeeping for both teams of match m. +void develop_players(ModernState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand); + +// Steps 1, 2 and 4 for every match of a group that was played (voided matches, e.g. +// awarded 0:2, are skipped). Human records and bonuses use manager_match_record. +void process_group(ModernState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index = -1, const SportschauFixtureHook& sportschau = {}, + const std::vector* show_events = nullptr, + const SportschauReplayHooks* replay = nullptr); +// Loaded Source caller retains mutable descriptor award ownership; legacy raw +// probes without executable policy keep their existing immutable input API. +void process_group(ModernState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index, const SportschauFixtureHook& sportschau, + const std::vector* show_events, const SportschauReplayHooks* replay, + const SportschauRatingTables* ratings); + +// ManagerMatchRecord: a human manager's record of match m (last results and fixtures, league +// win bonus, the manager rating via ManagerMatchRecord2 and the results per opponent). +void manager_match_record(ModernState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report); +// TablePosition: current table position of a team (-1 before the first round). +int table_position(const ModernState& g, int team); +// ManagerMatchRecord2: adds a match rating (0-200) to a manager's history of competition +// `competition` and stores the weighted average in the manager record (+0x8aa). +void rate_manager(ModernState& g, int manager, int rating, int competition); + +// StirRandom: when a result or table screen (LeagueScreenShown) is left, the game stirs its +// random numbers: WatcomRandom(100, 300) game draws are thrown away. +void stir_random(GameRandom& game, WatcomRandom& rand); + +// LeagueScreenShown(param_1, param_2): whether the screen is shown at all. param_1 1 = table, +// 2 = results; param_2 = the phase end minute (90 / 120 / 45 ...); league = descriptor +// +0xcc (CareerSession_BeginFriendlyOpponentTable_RuntimeField2). The desk buttons (block LeaguePresentationOptions, 9 bytes per league) switch it off. +bool league_screen_shown(const std::vector& buttons, int param_1, int param_2, int league); + +// The rest of AdvanceTurn after a matchday: for every competition bit of the day (bits +// 0-4 = leagues) the round counter LeagueRoundCounters advances, the table is recomputed and +// each club's rank is added to the position history (*LeagueRankHistory); human managers get their +// season position and strength history updated. This API accepts league bits only; +// finish_event dispatches bits 5+ separately through advance_cup. +void advance_league_rounds(ModernState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report, + const CompetitionWinnerHook& winner = {}); +// TicketPriceDraws: the random draws of a human manager's (disabled) ticket price drift. +void ticket_price_draws(const ModernState& g, int manager, WatcomRandom& rand); + +// Modern version of the function sportschau_presentation.hpp declares for Classic. +int sportschau_source_setting_index(const ModernState& state, const MatchGroup& group); + +} // namespace bmh::modern diff --git a/src/modern/game/matchday_setup.cpp b/src/modern/game/matchday_setup.cpp new file mode 100644 index 0000000..837936a --- /dev/null +++ b/src/modern/game/matchday_setup.cpp @@ -0,0 +1,1226 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/matchday_setup.hpp" +#include "game/trace.hpp" + +#include "modern/game/national.hpp" + +#include +#include +#include +#include +#include + +#include "modern/game/cup.hpp" +#include "game/lineup.hpp" +#include "game/match.hpp" +#include "modern/game/matchday.hpp" +#include "game/schedule.hpp" +#include "game/messages.hpp" +#include "game/table.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kManagerRecord = 0xB0C; +constexpr size_t kDescriptorSize = 0xD0; +// Competition class per descriptor type (MatchEngineRuntimeField9): which card counters apply. +constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255, + 4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0}; +// League groups per competition bit 0-4 (CalendarFirstLeague first league, CalendarLeagueCounts count; +// the arrays are indexed with the bit for bits 0-3 and with 4..7 for bit 4). +// (kGroupLeague / kGroupLeagues: schedule.hpp, the calendar groups of the loaded game) +// Crowd interest per descriptor type (MatchdaySetupRuntimeField). +constexpr uint8_t kTypeInterest[24] = {5, 5, 10, 15, 12, 10, 5, 10, 5, 10, 5, 31, 10, 10, 10, 0, 0, 1, 0, 0, 0, 12, 0, 0}; +// Number of clubs taking part in league play (CareerSession_DispatchLineup_RuntimeField). +// Squad slots checked by the driver (CareerRuntimeField). + +// The attendance tables MatchdaySetup_Attendance_ExecutableField .. MatchdaySetupRuntimeField2 as one block, because the original +// indexes them with league classes 0-7 although they only have four entries: classes 4-7 +// (the regional leagues) read the next table. Offsets relative to MatchdaySetup_Attendance_ExecutableField. The dword at +// MatchdaySetupRuntimeField6 is written at run time by the human home path (Attendance at layout field) and is +// only reached here as MatchdaySetup_Attendance_ExecutableField3[4], which is multiplied by 0 for the regional leagues. +constexpr uint8_t kAttendanceTables[0x6a] = { + 0xb8, 0x88, 0x00, 0x00, 0x98, 0x3a, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x70, 0x17, 0x00, 0x00, // MatchdaySetup_Attendance_ExecutableField capacity + 0x10, 0x27, 0x00, 0x00, 0x88, 0x13, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, // MatchdaySetup_Attendance_ExecutableField2 base + 0xf0, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x96, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, // MatchdaySetup_Attendance_ExecutableField3 per strength + 0x00, 0x00, 0x00, 0x00, 0x30, 0x75, 0x00, 0x00, 0x30, 0x75, 0x00, 0x00, 0xa8, 0x61, 0x00, 0x00, // MatchdaySetupRuntimeField6 stadium steps + 0x20, 0x4e, 0x00, 0x00, 0xd8, 0x59, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x98, 0x3a, 0x00, 0x00, + 0x20, 0x4e, 0x00, 0x00, 0xa8, 0x61, 0x00, 0x00, // (a3f0a) + 0x46, 0x30, 0x1d, 0x0e, // MatchdaySetup_Attendance_ExecutableField4 strength offset + 0xa6, 0x82, 0x50, 0x20, // MatchdaySetup_Attendance_ExecutableField5 interest divisor + 0x14, 0x12, 0x10, 0x0e, // MatchdaySetup_Attendance_ExecutableField6 ticket price + 0x0c, 0x0f, // MatchdaySetupRuntimeField9 + 0x6e, 0x3c, 0x1e, 0x0a, // MatchdaySetup_Attendance_ExecutableField7 +}; +int32_t table_u32(uint32_t address, int index) { + size_t at = address - ::bmh::layout::MatchdaySetup_Attendance_ExecutableField + size_t(index) * 4; + return int32_t(kAttendanceTables[at] | kAttendanceTables[at + 1] << 8 | kAttendanceTables[at + 2] << 16 | + uint32_t(kAttendanceTables[at + 3]) << 24); +} +int table_u8(uint32_t address, int index) { return kAttendanceTables[address - ::bmh::layout::MatchdaySetup_Attendance_ExecutableField + size_t(index)]; } + +void put32(Bytes& b, size_t o, uint32_t v) { + for (int i = 0; i < 4; i++) b.at(o + i) = uint8_t(v >> (8 * i)); +} + +uint32_t rd32(const Bytes& b, size_t o) { + return uint32_t(b.at(o) | b.at(o + 1) << 8 | b.at(o + 2) << 16) | uint32_t(b.at(o + 3)) << 24; +} +void wr32(Bytes& b, size_t o, uint32_t v) { put32(b, o, v); } +void wr16(Bytes& b, size_t o, uint16_t v) { b.at(o) = uint8_t(v), b.at(o + 1) = uint8_t(v >> 8); } + +// TeamLeague2: league of a club, 0 for the special ids above 0x164, 9 outside the leagues. +int league_of(int team) { + if (team > 0x164) return 0; + return team_league(team); +} + +// RestoreForfeitSquad, called once per side after FinishEvent detects a forfeited fixture. +void restore_forfeit_squad(ModernState& g, int team) { + const SquadRange range = squad_range(team); + for (size_t slot_index = range.first; slot_index < range.first + range.count; slot_index++) { + const uint16_t slot = g.squad_slots.at(slot_index); + const size_t player = slot & 0x0fff; + if (player == 0x0fff || player >= g.players.size() || player >= g.player_cards.size()) continue; + Player& p = g.players[player]; + if ((p.w35c >> 27) != 0) continue; + const uint16_t cards = g.player_cards[player]; + p.w368 = (p.w368 & 0xf8fc3fffu) | + (uint32_t(cards >> 9 & 7) << 24) | + (uint32_t(cards >> 5 & 0xf) << 14); + p.w364 &= 0xffe0ffffu; + p.w364 |= uint32_t(p.w364 >> 13 & 7) << 16; + } +} + +// BookMoney(manager, attendance, 0): income of the stadium's kiosks and restaurants: +// per facility 0-13 that exists, BalancePlanRuntimeField7[k] * attendance * level / 100 (level of +// facility 0 = its size step), then scaled by W(85, 115) %. +int32_t catering_income(const ModernState& g, int manager, int32_t spectators, WatcomRandom& rand) { + static const uint8_t kPerVisitor[14] = {0, 10, 10, 3, 5, 15, 3, 3, 3, 3, 2, 2, 2, 2}; // BalancePlanRuntimeField7 + const size_t rec = size_t(manager) * kManagerRecord; + uint32_t sum = 0; + for (int k = 0; k < 14; k++) { + const uint8_t v = g.manager_records.at(rec + size_t(k)); + if (v == 0) continue; + const uint32_t level = k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32 + sum += kPerVisitor[k] * uint32_t(spectators) * level / 100; + } + if (sum != 0) sum = uint32_t(rand.range(0x55, 0x73)) * sum / 100; + return int32_t(sum); +} + +} // namespace + +namespace { +uint8_t sportschau_capacity(const ModernState& g) { + const auto capacity = g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField) ? g.memory.u8(::bmh::layout::CareerSession_FormatError_RuntimeField) : 0; + if (capacity > 9) throw std::invalid_argument("Sportschau A8 exceeds the Original nine-match capacity"); + return capacity; +} +} + +void reset_sportschau_selection(ModernState& g) { + const auto capacity = sportschau_capacity(g); + std::fill_n(g.sportschau_priorities.begin(), capacity, uint8_t(0xff)); + g.sportschau_selection_available = true; +} + +bool consider_sportschau_fixture(ModernState& g, const MatchGroup& group, + int home, int away, WatcomRandom& rand) { + const int setting = modern::sportschau_source_setting_index(g, group); + if (setting < 0 || setting >= 20 || !g.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) || + g.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) != 0) return false; + const uint8_t capacity = sportschau_capacity(g); + int16_t priority = 0; + for (int team : {home, away}) { + if (g.memory.has(::bmh::layout::MatchdaySetup_ConsiderSportschauFixture_RuntimeField) && g.memory.u8(::bmh::layout::MatchdaySetup_ConsiderSportschauFixture_RuntimeField) == 0 && g.manager_of(team) >= 0) + priority = int16_t(priority - 300); + const auto average = team_average(g, team, 0x1ff, &rand); + priority = int16_t(priority + ((100 - int(uint16_t(average.value))) >> 1)); + const int position = std::max(0, int(int8_t(modern::table_position(g, team)))); + const int threshold = g.sportschau_club_threshold; + priority = int16_t(priority + position + (team >= threshold ? 50 : 0) + league_of(team) * 10); + } + if (priority <= 0) priority = 1; + g.sportschau_priorities[capacity] = uint8_t(priority); // low byte, not a clamp + g.sportschau_homes[capacity] = uint16_t(home); + for (int i = capacity; i > 0; --i) { + if (g.sportschau_priorities[size_t(i)] < g.sportschau_priorities[size_t(i - 1)]) { + std::swap(g.sportschau_priorities[size_t(i)], g.sportschau_priorities[size_t(i - 1)]); + std::swap(g.sportschau_homes[size_t(i)], g.sportschau_homes[size_t(i - 1)]); + } + } + return true; +} + +bool sportschau_selected(const ModernState& g, int home) { + const auto capacity = sportschau_capacity(g); + return std::find(g.sportschau_homes.begin(), g.sportschau_homes.begin() + capacity, + uint16_t(home)) != g.sportschau_homes.begin() + capacity; +} + +void match_weather(MatchGroup& grp, int m, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand) { + const int home = grp.fixtures.at(size_t(m) * 2), away = grp.fixtures.at(size_t(m) * 2 + 1); + const int region = team_region(home); + int8_t base = int8_t(month_temperature(ctx.month) + region_temperature(region)); + const uint8_t temperature = uint8_t(rand.range(0, 6) + base - 3); + grp.desc.at(0x30 + size_t(m)) = temperature; + int rain = rand.range(0, 5); + // the temperature is compared as an unsigned byte: only 0 and 1 degrees bring snow + if (temperature < 2 && rain > 3) rain += 2; + grp.desc.at(0x50 + size_t(m)) = uint8_t(rain); + if (int16_t(home) < no_team() && uint16_t(away) < no_team() && !(grp.desc.at(1) & 0x80)) { + // Range(1): a referee not yet chosen today + std::vector& refs = *ctx.referees; + int r; + do { + r = game.range(1, 0x31); + } while (refs.at(size_t(r)) & 0x80); + refs.at(size_t(r)) |= 0x80; + grp.desc.at(0x10 + size_t(m)) = uint8_t(r); + } +} + +void prepare_team(ModernState& g, int team, int cls, int index) { + uint16_t& flags = g.team_flags.at(size_t(team)); + flags = uint16_t((flags & 0xFF0F) | ((index % 2) << 4)); + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + uint16_t& slot = g.squad_slots.at(s); + slot &= 0xCFFF; + if ((slot & 0x0FFF) == 0x0FFF) break; + const int player = slot & 0x0FFF; + Player& p = g.players.at(size_t(player)); + if (p.w35c >> 27) continue; // not available (loaned out or similar) + uint16_t& cards = g.player_cards.at(size_t(player)); + // keep the league yellow cards of this season (bits 5-8 and 9-11) + cards = uint16_t((cards & 0xF01F) | ((p.w368 >> 14) & 0xF) << 5); + cards = uint16_t(cards | ((p.w368 >> 24) & 7) << 9); + uint8_t injury = 0; + if (cls != 0) { + // the card counters of this competition replace the league ones for the match + p.w368 &= 0xF8FC3FFFu; + const uint8_t k = uint8_t(cls - 1); + if (k <= 3) { + uint32_t v = k == 0 ? p.w364 >> 8 : k == 1 ? p.w364 >> 10 : k == 2 ? uint32_t(cards >> 14) : uint32_t(cards >> 12); + p.w368 |= (v & 3) << 14; + } + if (int8_t(cls) != -1 && ((p.w368 >> 14) & 3) > 1) injury = 1; // banned + } else { + injury = uint8_t((p.w364 >> 16) & 0xF); + } + p.w364 &= 0xFFFF0FFFu; + p.w364 |= ((p.w364 >> 16) & 7) << 13; + p.w364 &= 0xFFE0FFFFu; + if (injury) { + slot &= 0x0FFF; + p.w364 |= uint32_t(injury) << 16; + } + } +} + +// Postponed league matches (Postponed): 40 entries of 6 bytes - the day of the replay +// (u16, 0 = free entry), the league round (+2), the league (+3) and the match (+4). +constexpr uint32_t kPostponed = ::bmh::layout::Postponed; +constexpr int kPostponedEntries = 0x28; +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; // u16 per season day +// MatchdaySetupRuntimeField3 / MatchdaySetupRuntimeField4: first and last day of the winter break (static data, no +// replays are scheduled in between) +constexpr int kWinterBreakFirst = 0x96, kWinterBreakLast = 0xc8; +constexpr uint8_t kPostponedMark = 0xcd; // result byte of a postponed match + +uint16_t calendar_entry(const ModernState& g, int day) { return g.memory.u16(kCalendar + uint32_t(day) * 2); } + +// RescheduleLeagueMatch (with param_5 = -0x33): finds a replay day for match `m` of round `round` in +// `league`, starting five days after `day`. A day qualifies when it and both neighbours are +// free in the calendar (the day before may carry bit 4), or when it already is a replay day +// (0x4000); a coin toss of the game generator may still refuse it, as may eight replays or a +// team clash on that day. Records the replay in entry `slot`, marks the result byte and the +// calendar day. +bool schedule_replay(ModernState& g, int day, int league, int m, int slot, int round, GameRandom& game) { + for (int date = day + 5;; date++) { + if (date > 0x11e) return false; + if (date >= kWinterBreakFirst && date <= kWinterBreakLast) date = kWinterBreakLast + 1; + const bool free = (calendar_entry(g, date) == 0 && (calendar_entry(g, date - 1) & 0xffef) == 0 && + calendar_entry(g, date + 1) == 0) || + calendar_entry(g, date) == 0x4000; + if (!free) continue; + bool ok = true; + if (game.range(0, 1) == 0) { + int same_day = 0; + for (int e = 0; e < kPostponedEntries && ok; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != date) continue; + if (++same_day == 8) { + ok = false; + break; + } + // The original generates the other replay's fixtures with the parameters of + // `league`, whatever league that entry belongs to, and compares only the low + // bytes of the team ids. + const std::vector other = generate_fixtures(league_table_teams(league), g.memory.u8(at + 2) + 1, + league_matchdays(league) / 2, league_first_team(league)); + const std::vector own = + generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league)); + const Fixture& o = other.at(g.memory.u8(at + 4)); + const Fixture& f = own.at(size_t(m)); + const uint8_t oh = uint8_t(o.home), oa = uint8_t(o.away), fh = uint8_t(f.home), fa = uint8_t(f.away); + if (fh == oh || fa == oa || fa == oh || fh == oa) ok = false; + } + } else { + ok = false; + } + if (ok) { + const uint32_t at = kPostponed + uint32_t(slot) * 6; + g.memory.set16(at, uint16_t(date)); + g.memory.set8(at + 2, uint8_t(round)); + g.memory.set8(at + 3, uint8_t(league)); + g.memory.set8(at + 4, uint8_t(m)); + g.results.at(size_t(m) + size_t(round) * 10 + size_t(league) * 0x17C) = kPostponedMark; + g.memory.set8(kCalendar + uint32_t(date) * 2 + 1, g.memory.u8(kCalendar + uint32_t(date) * 2 + 1) | 0x40); + return true; + } + } +} + +// WinterPostponements: winter postponements of a league matchday (leagues 0-4, season days +// 0x6e..0xe6, unless MatchdaySetup_WinterPostponements_RuntimeField2 is set). The number of postponed matches peaks around day +// 0xaa and is capped by the option byte MatchdaySetup_WinterPostponements_RuntimeField. +void winter_postponements(ModernState& g, int day, int league, GameRandom& game, WatcomRandom& rand) { + if (g.memory.u8(::bmh::layout::MatchdaySetup_WinterPostponements_RuntimeField2) != 0 || league >= 5 || day <= 0x6d || day >= 0xe7) return; + const int16_t distance = int16_t(std::abs(day - 0xaa) / 10); + int16_t most = int16_t(9 - distance); + if (most != 0 && rand.range(0, 1) != 0) most = int16_t(8 - distance); + int16_t count = int16_t(rand.range(0, most)); + if (int16_t(g.memory.u8(::bmh::layout::MatchdaySetup_WinterPostponements_RuntimeField)) < count) count = int16_t(g.memory.u8(::bmh::layout::MatchdaySetup_WinterPostponements_RuntimeField)); + const int round = g.league_rounds.at(size_t(league)); + int16_t before; + do { + before = count; + if (count == 0) return; + for (int slot = 0; slot < kPostponedEntries; slot++) { + if (g.memory.u16(kPostponed + uint32_t(slot) * 6) != 0) continue; + const int m = rand.range(0, kLeagueSizes[league] / 2 - 1); + if ((g.results.at(size_t(m) + size_t(round) * 10 + size_t(league) * 0x17C) & 0xcf) == 0xcc && + schedule_replay(g, day, league, m, slot, round, game)) { + count--; + break; + } + } + } while (before != count); +} + +// ClubName3(team, buffer): the longest word of a club's name (separators MatchdaySetupRuntimeField5 +// " %.1-"; of words with the same length the last one), written to `out` at `at`; a word +// ending in "ER" loses the "ER" ("HER": only the "R"). +void longest_word(const ModernState& g, int team, std::vector& out, size_t at) { + static constexpr char kSeparators[] = {' ', '%', '.', '1', '-'}; + const std::string name = g.club_name(team); + int start = 0, longest = 0; + for (int i = 0; i <= int(name.size()); i++) { + const char c = i < int(name.size()) ? name[size_t(i)] : '\0'; + for (char sep : kSeparators) { + if (sep != c && c != '\0') continue; + if (longest <= i - start) { + longest = i - start; + for (int k = 0; k < longest; k++) out.at(at + size_t(k)) = uint8_t(name[size_t(start + k)]); + out.at(at + size_t(longest)) = 0; + } + start = i + 1; + } + } + if (longest >= 3 && out.at(at + size_t(longest) - 1) == 'R' && out.at(at + size_t(longest) - 2) == 'E') + out.at(at + size_t(longest + (out.at(at + size_t(longest) - 3) == 'H') - 2)) = 0; +} + +// AddCompetition(id): puts a competition on the list of running ones (ActiveSelectors, 8 bytes, +// 0x14 = free); false if it is there already. +bool add_competition(ModernState& g, int id) { + for (uint32_t i = 0; i < 8; i++) { + if (int8_t(g.memory.u8(::bmh::layout::ActiveSelectors + i)) == id) return false; + if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + g.memory.set8(::bmh::layout::ActiveSelectors + i, uint8_t(id)); + return true; + } + } + return true; +} + +// IndoorTournamentDraw (with Cup_AdvanceCup_RuntimeField4 = CupRuntimeField = 0): the draw of the indoor tournament +// after the first half of the season. Eight clubs: at random one of the regional leagues +// (teams 90-137), 5-7 of the first league and the rest of the second, none twice; the second +// club drawn names the tournament. A human manager's club gets a starting bonus of 100 000. +// The order is then shuffled (PrepareEvent) and the tournament's strength class computed +// (IndoorTournamentReset). +void indoor_tournament_reset(ModernState& g) { + StaticMemory& mem = g.memory; + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4) == 0) // the first tournament: Masters points and invitations + for (uint32_t i = 0; i < 0x50; i++) mem.set8(::bmh::layout::Cup_AdvanceCup_ExecutableField + i, 0), mem.set8(::bmh::layout::MatchdaySetup_IndoorTournamentDraw_RuntimeField + i, 0); + if (g.tournament_name.size() < 0x24) g.tournament_name.resize(0x24, 0); + const std::string in = message_text(g, ::bmh::layout::MatchdaySetup_IndoorTournamentReset_TextPointer); // "In " + for (size_t i = 0; i <= in.size() && i < 0x24; i++) g.tournament_name[i] = i < in.size() ? uint8_t(in[i]) : 0; + for (uint32_t i = 0; i < 0x20; i++) mem.set8(::bmh::layout::MatchdayGroupWorkspace + i, 0xcc); + for (int i = 0x19; i < 0x1e; i++) mem.set8(::bmh::layout::MatchdaySetup_IndoorTournamentReset_RuntimeField + uint32_t(i) * 0x28, 0); // played counters +} + +void indoor_tournament_draw(ModernState& g, GameRandom& game, WatcomRandom& rand) { + StaticMemory& mem = g.memory; + constexpr uint32_t kTeams = ::bmh::layout::Teams, kInvitations = ::bmh::layout::MatchdaySetup_IndoorTournamentDraw_RuntimeField; // u16 per club < 0x28 + const int held = mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4); // tournaments played so far (Cup_AdvanceCup_RuntimeField4) + modern::indoor_tournament_reset(g); + uint8_t attempts = 0; + const int guest = rand.range(0, 1); + if (guest != 0) mem.set16(kTeams, uint16_t(rand.range(90, 137))); + int count = guest != 0; + int n = rand.range(5, 7); + uint8_t lo = 0, hi = uint8_t(kLeagueSizes[0]); + uint32_t previous; + do { + for (int s = 0; s < n; s++) { + bool again; + uint16_t t; + do { + again = false; + attempts++; + t = uint16_t(rand.range(lo, hi - 1)); + if (int16_t(t) < 0x28 && int16_t(mem.u16(kInvitations + uint32_t(t) * 2)) > 1) { + again = true; + if (attempts > 0x14) attempts = 0xf, hi++; + } else { + if (count == 1) { + // the second club drawn hosts the tournament, not a host of before + longest_word(g, t, g.tournament_name, 3); + for (int k = 0; k < held; k++) + if (t == mem.u8(::bmh::layout::LiveMatchday_FormatError_RuntimeField14 + uint32_t(k))) again = true; + mem.set8(::bmh::layout::LiveMatchday_FormatError_RuntimeField14 + uint32_t(held), uint8_t(t)); + } + for (int k = 0; k < count; k++) + if (mem.u16(kTeams + uint32_t(k) * 2) == t) again = true; + } + } while (again); + if (count < 8) mem.set16(kTeams + uint32_t(count++) * 2, t); + } + n = 8 - count; + previous = hi; + lo = hi; + hi = uint8_t(hi + kLeagueSizes[1]); + } while (previous < uint32_t(kLeagueSizes[0] + kLeagueSizes[1])); + std::string title; + for (size_t i = 3; i < g.tournament_name.size() && g.tournament_name[i]; i++) title.push_back(char(g.tournament_name[i])); + for (uint32_t k = 0; k < 8; k++) { + const uint16_t t = mem.u16(kTeams + k * 2); + const int manager = g.manager_of(t); + if (manager >= 0) { + post_composed(g, manager, std::string(kIndoorInvitationText) + title); + modern::book_money(g, manager, -100000, true, true); + } + if (t < 0x28) mem.set16(kInvitations + uint32_t(t) * 2, uint16_t(mem.u16(kInvitations + uint32_t(t) * 2) + 1)); + } + for (uint32_t i = 0; i < 8; i++) { // PrepareEvent(8, teams) + const uint32_t j = uint32_t(game.range(0, 7)); + const uint16_t a = mem.u16(kTeams + i * 2); + mem.set16(kTeams + i * 2, mem.u16(kTeams + j * 2)); + mem.set16(kTeams + j * 2, a); + } + int sum = 0; // IndoorTournamentReset + for (uint32_t k = 0; k < 8; k++) { + const int t = mem.u16(kTeams + k * 2); + const int league = t > 0x164 ? 0 : team_league(t); // TeamLeague2 + if (league < 2) sum += (0x26 - modern::table_position(g, t)) - kLeagueSizes[0] * league; + else if (league < 5) sum += 1; + else sum += 0x19; + } + mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField3, uint8_t(int16_t(sum + 7) / 8)); +} + +uint32_t day_competitions(const ModernState& g, uint16_t entry) { + uint32_t v = entry & 0x7fff; + if (g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2) != 0) v = entry & 0x7fef; + // (German: the indoor option off removes the indoor days; the English CycleManagerOptions2 has no + // such test - its 0x4002 days are the League Cup) + if (!kEnglishCompetitions && g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField) != 0 && v == 0x4002) v = 0; + if ((v & 0x4001) == 0x4001) v = (v & 0xff0) | 0x8000; + if (v == 0x4002) v = 0x10000; + if (v == 0x4004) v = 0x40000; + if (v == 0x4006) v = (g.memory.u8(::bmh::layout::CompetitionSelection) & 2) ? 0x800000 : 0; + // the international tournament of the year (bits 9-12) turns with the season; the English + // CycleManagerOptions2 counts from 1995 and adds 3 ((season + 3) % 4) to stay in step + if (v & 0x1e00) v &= 1u << (0xc - (g.season + (kEnglishCompetitions ? 3 : 0)) % 4); + return v; +} + +void cycle_manager_options(ModernState& g) { + for (size_t k = 0; k < g.manager_teams.size(); k++) { + uint8_t option = g.manager_options.at(k * 5); + const uint8_t enabled = g.manager_records.at(k * kManagerRecord + 0x218 + (g.indoor ? 1 : 0)); + if (option != 0 && enabled != 0) + while (!((enabled >> (option - 1)) & 1)) { + option++; + if (option > 8) option = 1; + } + g.manager_options.at(k * 5) = option; + } +} + +// DayConflict(team, other, calendar entry, day): whether a friendly day concerns the team. +// A calendar entry other than 0 and 0x4001 without the top bit always does; otherwise the +// friendly list (FriendlyDays: 30 days, FriendlyTeams: the two teams of each) is searched +// for a friendly on `day` with the national team, `team` or `other`. +static bool national_friendly(const ModernState& g, int team, int other, int16_t entry, int day) { + if (entry != 0 && entry != 0x4001 && !(uint16_t(entry) & 0x8000)) return true; + const StaticMemory& mem = g.memory; + if (!mem.has(::bmh::layout::FriendlyDays) || !mem.has(::bmh::layout::FriendlyTeams)) return false; + for (int i = 0; i < 0x3c; i += 2) { + if (int16_t(mem.u16(::bmh::layout::FriendlyDays + uint32_t(i / 2) * 2)) != day) continue; + for (int k = 0; k < 2; k++) { + const int t = int16_t(mem.u16(::bmh::layout::FriendlyTeams + uint32_t(i + k) * 2)); + if (t == no_team() || t == team || t == other) return true; + } + } + return false; +} + +bool matchday_needs_manager_desks(const ModernState& g, uint16_t calendar_entry, + const std::vector& groups) { + if (g.manager_teams.empty()) return false; + const auto& mem = g.memory; + const bool opening = g.season_day() == 0; + const bool closing = mem.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && mem.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) != 0; + int request = mem.u8(::bmh::layout::MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField) + int(opening) + int(closing); + if (mem.u32(::bmh::layout::CompetitionSelection) == 2) request = 0; + if (modern::day_competitions(g, calendar_entry) == 0x8000 && + national_friendly(g, no_team(), 500, int16_t(calendar_entry), g.season_day())) + request = 4; + + // MatchdayNeedsManagerDesks assigns local_44 only to actual participants. League results + // must still be 0xcc; setup has already changed postponed 0xce to 0xcd. + // Cup descriptors instead obtain the context from their entry's +0x18. + for (const auto& group : groups) { + const uint32_t competition = rd32(group.desc, 0xcc); + for (size_t fixture = 0; fixture < size_t(group.matches()); ++fixture) { + if (competition < 0x14) { + const size_t result = size_t(competition) * 0x17c + + size_t(g.league_rounds.at(competition)) * 10 + fixture; + if (g.results.at(result) != 0xcc) continue; + } else if (int8_t(mem.u8(competition + 0x18) + 5) >= 0x1e) { + continue; + } + if (g.manager_of(group.fixtures.at(fixture * 2)) >= 0 || + g.manager_of(group.fixtures.at(fixture * 2 + 1)) >= 0) + request = 1; + } + } + return (mem.has(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) && mem.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) != 0) || + (request != 0 && (request == 4 || !groups.empty() || closing || opening)); +} + +std::vector setup_matchday(ModernState& g, uint32_t competitions, const MatchdayContext& ctx, + GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + std::vector groups; + // AdvanceTurn first: after the first half of the Bundesliga season (17 rounds) the + // indoor tournament (competition 0xb) is drawn once, unless switched off (CalendarState_FormatError_RuntimeField) + if (g.league_rounds.at(0) == 0x11 && g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField) == 0 && add_competition(g, 0xb)) { + g.memory.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, 0); // Cup_AdvanceCup_RuntimeField4: the first tournament of the season + turn_step = "setup: indoor tournament draw"; + modern::indoor_tournament_draw(g, game, rand); + } + // AdvanceTurn keeps the day's competition bits (DayCompetitions of the calendar entry) in + // SavedCompetition; the savegame carries the value of the last prepared matchday. + g.memory.set32(::bmh::layout::SavedCompetition, competitions); + // the Bundestrainer: on an international match day (competition bits 0x1e00) or a friendly + // day of the national team (local_28 == 4), not on season day 0 and not after the season + // end, he takes the national team over (SwapManagerSlots2) unless he already has; on any other + // day a take-over in effect ends (NationalCoachHandBack). (ActiveManager at this point: what the day + // step's manager loop left, the number of managers.) + if (!ctx.national_team_day) { + const bool national_day = + (competitions & 0x1e00) || + (competitions == 0x8000 && + national_friendly(g, no_team(), 500, int16_t(g.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(ctx.season_day) * 2)), ctx.season_day)); + if (national_day && !(g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && g.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) && ctx.season_day != 0) { + if (!modern::national_coach_active(g)) + modern::national_coach_take_over(g, int(g.manager_teams.size()), uint16_t(ctx.season_day)); + } else if (modern::national_coach_active(g)) { + modern::national_coach_hand_back(g); + } + } + g.indoor = false; + for (uint8_t& r : *ctx.referees) r &= 0x7F; // Range(0) + for (int bit = 0; bit < 0x13; bit++) { + if (!((competitions >> bit) & 1)) continue; + if (bit >= 5) { + turn_step = "setup: cup groups"; + modern::setup_cup_groups(g, bit - 5, groups, report); // SetupCupGroups(bit - 5) + continue; + } + const int from = bit, to = bit < 4 ? bit + 1 : 8; + for (int k = from; k < to; k++) { + // FixturesFromGenerateFixtures(k) + for (int league = kGroupLeague[k]; league < kGroupLeague[k] + kGroupLeagues[k]; league++) { + turn_step = "setup: winter postponements"; + winter_postponements(g, ctx.season_day, league, game, rand); + const int round = g.league_rounds.at(size_t(league)); + const int size = kLeagueSizes[league]; + MatchGroup grp; + grp.desc = modern::group_descriptor(g, groups.size()); + for (const Fixture& f : generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league))) { + grp.fixtures.push_back(f.home); + grp.fixtures.push_back(f.away); + } + const size_t at = size_t(league) * 0x17C + size_t(round) * 10; + for (int m = 0; m < size / 2; m++) { + uint8_t& r = g.results.at(at + size_t(m)); + if ((r & 0xCF) == 0xCE) r = 0xCD; // postponed -> to be replayed later + } + grp.desc.at(0) = 0; // league + grp.desc.at(1) = 2; + grp.desc.at(2) = uint8_t(size / 2); + put32(grp.desc, 0xcc, uint32_t(league)); + // MatchdayNeedsManagerDesks: a human manager's club notes its side (record +0x28a) + for (int i = 0; i < size; i++) + for (size_t mgr = 0; mgr < g.manager_teams.size(); mgr++) + if (g.manager_teams[mgr] == grp.fixtures[size_t(i)]) g.manager_records.at(mgr * kManagerRecord + 0x28a) = uint8_t(i % 2); + groups.push_back(grp); + } + // before the 17th Bundesliga matchday every manager is reminded that the balance + // sheets go to the DFB at the end of the first half of the season (MatchdaySetup_SetupMatchday_TextPointer) + if (k == 0 && g.league_rounds.at(0) == 0x10) post_text(g, -1, text_id(::bmh::layout::MatchdaySetup_SetupMatchday_TextPointer)); + } + } + turn_step = "setup: teams"; + for (MatchGroup& grp : groups) { + const int cls = kCompetitionClass[grp.desc.at(0)]; + for (int i = 0; i < grp.matches() * 2; i++) { + if (i < grp.matches()) modern::match_weather(grp, i, ctx, game, rand); + const int team = grp.fixtures.at(size_t(i)); + modern::prepare_team(g, team, cls, i); + try { + auto_lineup(g, team, 100); + } catch (const std::invalid_argument& e) { + report.fail(e.what()); + } + } + } + for (int team = 0; team < league_clubs(); team++) + if (g.team_flags.at(size_t(team)) & 1) auto_lineup(g, team, 100); + turn_step = "setup: options"; + modern::cycle_manager_options(g); + modern::store_group_descriptors(g, groups); + return groups; +} + +int match_mode_bits(const ModernState& g, const MatchGroup& grp, const MatchdayContext& ctx, MinuteReport& report) { + const int type = grp.desc.at(0); + uint8_t bits = kTypeInterest[type]; + if (type == 0) { + const int league = int(le32(grp.desc, 0xcc)); + const int matchdays = league_matchdays(league), rounds = g.league_rounds.at(size_t(league)); + // the last four rounds draw more spectators + if (rounds > matchdays - 4) bits = uint8_t(bits + uint8_t(0xF - uint8_t((matchdays - rounds) * 3))); + } else if (type != 9 && type != 0xb) { + // cups: more interest in the last round of a stage, even more in the final + const uint32_t e = le32(grp.desc, 0xcc); + if (g.memory.u8(e + 0x1d) + 1 >= g.memory.u8(e + 0x1b)) { + bits = uint8_t(bits + 5); + if (g.memory.u8(e + 0x16) == 0) bits = uint8_t(bits + 10); + } + } + int result = bits; + if (ctx.weekday == 4 && type == 10) result |= 0x20; + if (!(grp.desc.at(1) & 2)) result |= 0x80; + if (type == 1) result |= 0x100; + if (type > 1 && type < 5) result |= 0x200; + return result; +} + +int attendance(ModernState& g, int home, int away, int bits, int temperature, int rain, int competition_type, + GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + const int team[2] = {home, away}; + int strength[2] = {0, 0}, position[2] = {0, 0}, league[2] = {0, 0}; // local_6c[2..3], local_7c + int best_half_sum = 0; // CareerSession_FormatError_ExecutableField3 (home side) + for (int i = 1; i >= 0; i--) { + const TeamAverage avg = team_average(g, team[i], 0x1f7, &rand); + strength[i] = uint16_t(avg.value); + best_half_sum = avg.best_half_sum; + position[i] = modern::table_position(g, team[i]); + if (position[i] < 0) position[i] = rand.range(2, 5); + if (uint16_t(team[i]) >= 0x5a) { + league[i] = 0; + } else { + league[i] = league_of(team[i]); + if (league[i] > 2) league[i]--; + } + } + const int home_manager = g.manager_of(home), away_manager = g.manager_of(away); // local_20, local_14 + const size_t rec = size_t(home_manager) * 0xB0C; // EDI / puVar10: the home manager's record + auto r8 = [&](size_t off) { return int(g.manager_records.at(rec + off)); }; + auto r16 = [&](size_t off) { return int(g.manager_records.at(rec + off) | g.manager_records.at(rec + off + 1) << 8); }; + auto r32 = [&](size_t off) { return int32_t(rd32(g.manager_records, rec + off)); }; + auto w32 = [&](size_t off, int32_t v) { wr32(g.manager_records, rec + off, uint32_t(v)); }; + + int32_t n; // ESI: the attendance + int price; // local_38: ticket price + if ((home_manager < 0 || home != no_team()) && !(bits & 0x80)) { + const int lh = league[0], la = league[1]; + n = table_u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField2, lh); + int prestige = 0x32, performance = 0x226; // local_24, local_2c + if (home_manager < 0) { + price = table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField6, lh); + } else { + if (strength[0] < best_half_sum - 10) n += 2000; // a team with stars draws more + prestige = r8(0x211); + performance = r16(0x8aa); + price = r8(0x26e); + } + int sum = 0, sum_above = 0; // local_50, local_30 + for (int i = 0; i < 2; i++) { + sum += strength[i]; + int16_t above = int16_t(strength[i] - table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField4, league[i])); + if (above < 0) above = 0; + if (above > 30) above = 30; + sum_above += above; + } + const int32_t from_strength = sum_above * table_u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField3, lh); + int x = (40 - position[0] - position[1]) * 2; // local_5c + if (lh + la == 0 && rand.range(60, 66) < x) x = x * rand.range(110, 125) / 100; + prestige = uint8_t(prestige / (lh + 1)); + performance = uint16_t(performance / 5 / (lh + 1)); + x += (performance >> 2) + (prestige >> 2); + n = (x + 80) * (n + from_strength) / 100; + if (la < lh) + n += lh * -2000 + la * -500 + 10000; + else if (lh < la) + n += (4 - la) * -4000; + int capacity; // local_3c + if (home_manager < 0) { + const int a = table_u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField, lh); + capacity = rand.range(a - (a >> 2), a + (a >> 2)) / 500 * 500; + if ((bits & 0x180) == 0x180) capacity = 76000; + } else { + // the manager's stadium: facilities, size steps, roofs against the rain + int covered = 0; // local_64: covered share of the stands + const int facilities = modern::facility_rating(g, home_manager, &covered, &rand) - table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField7, lh); // local_44 + static const int32_t kStadiumSteps[10] = {0, 30000, 30000, 25000, 20000, 23000, 10000, 15000, 20000, 25000}; + for (int k = 0; k < 10; k++) { + const int v = r8(size_t(k)); + // MatchdaySetupRuntimeField6[0] is overwritten with the step of the stadium size + const int32_t step = k == 0 ? int32_t(v / 0x55 * 25000) : kStadiumSteps[k]; + if (step < n && (v == 0 || k == 0)) n -= n / rand.range(10, 20); + } + const int wet = int(uint32_t(100 - covered) * uint32_t(uint8_t(rain)) * 8) / 100; + n = (((n >> 1) + (100 - wet) * (n >> 1) / 100) * (int8_t(temperature) + 0x5a)) / 100 >> 1; + n += n * rand.range(facilities + 0x5a, facilities + 0x6e) / 100; + capacity = r8(0x5c) * 1000; + } + const int level_bonus = (9 - g.level) * 2; // Range3 returns 1 in this version + const int form = rand.range(level_bonus + 0x55, level_bonus + 0x5f); + int interest = bits & 0x1f; + if (interest == 0x1f) { + interest = -10; + bits = 0; + } + if (interest > 20) interest = 20; + int demand = sum * ((bits & 0x1f) + 100) / 100; + if (demand < 0) demand = 0; + if (demand > 180) demand = 180; + int price_index = price * 100 / table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField6, lh); + int demand_index = demand * 100 / table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField5, lh); + if (price_index < demand_index) price_index += price_index >> 3; + if (demand_index < 30) demand_index = 30; + if (demand_index > 180) demand_index = 180; + n = ((interest * 3 + 100) * (n * form / 100) / 100) * (demand_index + 100 - price_index) / 100; + int standing = 1, seated = 1; // local_4c, local_48: places of the open stands + if (home_manager >= 0) { + // stands that differ much from an eighth of the stadium put people off + int unevenness = 0; // local_60 + int unit = r8(0x5c) >> 3; + if (unit == 0) unit = 1; + for (int k = 0; k < 8; k++) { + const int places = r8(0x34 + size_t(k)) == 0 ? r8(0x4c + size_t(k)) : 0; + unevenness += std::abs(100 - places * 100 / unit); + if (r8(0x3c + size_t(k)) & 1) + seated += places; + else + standing += places; + } + unevenness >>= 3; + if (rand.range(0x8c, 0xb4) < unevenness) { + unevenness = unevenness < 0x96 ? 0x96 : unevenness > 0xfa ? 0xfa : unevenness; + unevenness -= 0x96; + n -= (unevenness >> 1) * n / 100; + } + } + if (bits & 0x20) n = rand.range(n - (n >> 2), n + (n >> 2)); + if (n < 100) n = rand.range(100, 500); + n = (n + 100) / 100 * 100; + if (n > capacity) n = capacity; + if (home_manager >= 0 && capacity * rand.range(0x4b, 100) / 100 < n && rand.range(0, r8(0x210) + 1) == 0) { + // a full house: few seats make riots likely (record +0x289 then costs the team at + // kick-off, see rate_side); the damage is paid by the club + const int share = seated * 100 / standing; + g.manager_records.at(rec + 0x289) = share < 0x1e; + if (share < game.range(0x50, 0x78) && r8(0x43) < 3 && rand.range(0, r8(0x43) << 2) == 0) { + const int32_t damage = rand.range(n / 0x1e, n / 10) * 100; + post_composed(g, home_manager, message_text(g, ::bmh::layout::MatchdaySetup_Attendance_TextPointer) + format_amount(g, damage) + message_text(g, ::bmh::layout::CareerSession_Int32T_TextPointer)); + modern::book_money(g, home_manager, damage, true, true); + } + } + } else { + n = (rand.range(3, 10) + (bits & 0x1f)) * 2500; + if ((bits & 0x40) && n > 74000) n = 74000; + price = 0x16; + } + int32_t income = price * n; // local_5c: ticket income + if (bits & 0x180) income >>= 1; + if (home_manager + away_manager != -2 && (bits & 0x100)) { + // cup matches with a human club: TV and advertising rights raise the (shared) gate + // by W(12, 15) / 10; both human managers get the message "... erhöhten sich Ihre + // Einnahmen auf (+ )." (MatchdaySetup_Attendance_TextPointer2, MatchdaySetupRuntimeField7 " (+ ", MatchdaySetupRuntimeField8 ").") + const int32_t raised = income * rand.range(12, 15) / 10; // MatchdaySetupRuntimeField9, MatchdaySetupRuntimeField10 + const std::string text = message_text(g, ::bmh::layout::MatchdaySetup_Attendance_TextPointer2) + format_amount(g, raised) + " (+ " + + format_amount(g, raised - income) + ")."; + int64_t mask = 0x80000000LL; + if (home_manager >= 0) mask |= 1LL << home_manager; + if (away_manager >= 0) mask |= 1LL << away_manager; + post_composed(g, mask, text); + income = raised; + } + int kind = ((bits & 0x200) ? 2 : 0) + ((bits & 0x100) ? 1 : 0); // 0 league, 1 cup, 2 other + if (kind > 2) { + report.fail("attendance: invalid competition bits"); + kind = 2; + } + if (home_manager >= 0 && r16(0x290) != no_team()) { + modern::book_money(g, home_manager, -income, true); + w32(0x868, r32(0x868) + income); + const int32_t catering = catering_income(g, home_manager, n, rand); // BookMoney + modern::book_money(g, home_manager, -catering, true); + w32(0x38c + 2 * 4, catering); // indexed by a stale loop counter (2) in the original + w32(0x86c, r32(0x86c) + catering); + if (kind != 0 || competition_type == 0 || competition_type == 0xe || competition_type == 0xa) { + g.manager_records.at(rec + 0x28c + size_t(kind))++; + w32(0x748 + size_t(kind) * 4, r32(0x748 + size_t(kind) * 4) + n); + w32(0x754 + size_t(kind) * 4, r32(0x754 + size_t(kind) * 4) + income); + if (n > r32(0x718 + size_t(kind) * 8)) { // record attendance + w32(0x718 + size_t(kind) * 8, n); + w32(0x71c + size_t(kind) * 8, int32_t(g.date)); + wr16(g.manager_records, rec + 0x8c0 + size_t(kind) * 2, g.club_ids.at(size_t(away))); + } + if (income > r32(0x730 + size_t(kind) * 8)) { // record income + w32(0x730 + size_t(kind) * 8, income); + w32(0x734 + size_t(kind) * 8, + int32_t(uint32_t(g.season_day()) + uint32_t(g.memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3)))); + wr16(g.manager_records, rec + 0x8c6 + size_t(kind) * 2, g.club_ids.at(size_t(away))); + } + if (kind == 0) { + // the last 19 league home matches: attendance (+0x340) and ticket price (+0x270) + auto& m = g.manager_records; + int k = int8_t(r8(0x283)); + if (k < 0x13) { + m.at(rec + 0x283) = uint8_t(k + 1); + } else { + std::copy(m.begin() + long(rec + 0x344), m.begin() + long(rec + 0x344 + 0x48), m.begin() + long(rec + 0x340)); + std::copy(m.begin() + long(rec + 0x271), m.begin() + long(rec + 0x271 + 0x12), m.begin() + long(rec + 0x270)); + // (only 0x12 bytes of the u32 list +0x38c are moved) + std::copy(m.begin() + long(rec + 0x390), m.begin() + long(rec + 0x390 + 0x12), m.begin() + long(rec + 0x38c)); + k = 0x12; + } + w32(0x340 + size_t(k) * 4, n); + m.at(rec + 0x270 + size_t(k)) = uint8_t(price); + // season ticket holders (+0x2ac) have paid already: 70 % of their tickets + // are taken back from the gate income + const int holders = std::min(r16(0x2ac), int(n)); + const int32_t refund = price * (holders * 0x46 / 100); + modern::book_money(g, home_manager, refund, true); + w32(0x754, r32(0x754) - refund); + w32(0x868, r32(0x868) - refund); + } + } + } + if (away_manager >= 0 && (bits & 0x180)) { + // a shared gate (cups, bits 7/8): the human away club gets the same half and counts + // the match in its attendance statistics (no catering, no records) + const size_t away_rec = size_t(away_manager) * 0xB0C; + auto& m = g.manager_records; + if ((m.at(away_rec + 0x290) | m.at(away_rec + 0x291) << 8) != no_team()) { + modern::book_money(g, away_manager, -income, true); + wr32(m, away_rec + 0x868, rd32(m, away_rec + 0x868) + uint32_t(income)); + m.at(away_rec + 0x28c + size_t(kind))++; + wr32(m, away_rec + 0x748 + size_t(kind) * 4, rd32(m, away_rec + 0x748 + size_t(kind) * 4) + uint32_t(n)); + wr32(m, away_rec + 0x754 + size_t(kind) * 4, rd32(m, away_rec + 0x754 + size_t(kind) * 4) + uint32_t(income)); + } + } + return n; +} + +namespace { + +// AutoLineup: a match with a human team (morale byte bit 7) is shown live, unless the +// option LiveDeskDisabled is set or 4 matches are already chosen. Returns true if chosen (the +// original also loads the club colours then, which is display only). +bool select_live_match(ModernState& g, int home, int away) { + if (!(g.team_morale.at(size_t(home)) & 0x80) && !(g.team_morale.at(size_t(away)) & 0x80)) return false; + for (int t : g.live_matches) + if (t == home) return false; + const bool no_live = g.memory.has(::bmh::layout::LiveDeskDisabled) && g.memory.u8(::bmh::layout::LiveDeskDisabled) != 0; + if (no_live || g.live_matches.size() >= 4) return false; + g.live_matches.push_back(home); + return true; +} + +// KickOff(own manager, own team, other manager, other team, 50, rate): man marking. +// The other team's midfielders and forwards in the line-up are ranked (forwards first, +// then strength, depth preference, shooting skill and experience); each of them is marked +// with a probability of 50 % (+30/20/10 % for the best three). The marker is drawn from the +// own defenders and midfielders not marking yet, ranked by strength, tackling skill and +// how close their board places are; each candidate in turn takes the job with `rate` %. +// Human managers record the pairs on their tactics boards (slot +0x44 = the player the +// slot marks, +0x46 = the player marking the slot); computer teams just draw. A human +// manager only takes part with option byte 3 (MatchdaySetupRuntimeField11) set; his rate comes from +// record +0x8ac / 16 + 40. +void man_marking(ModernState& g, int own_manager, int own, int other_manager, int other, int chance, int rate, + WatcomRandom& rand) { + const int kLeagueTeams = league_clubs(); // CareerSession_DispatchLineup_RuntimeField + if (g.indoor || own >= kLeagueTeams || other >= kLeagueTeams || (own_manager < 0 && other_manager < 0)) return; + if (other_manager >= 0) + for (size_t s = 0; s < 24; s++) { + const size_t at = size_t(other_manager) * 0x840 + s * 0x58 + 0x46; + g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F; + } + if (own_manager >= 0) { + if (!g.manager_option(own_manager, 3)) return; + for (size_t s = 0; s < 24; s++) { + const size_t at = size_t(own_manager) * 0x840 + s * 0x58 + 0x44; + g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F; + } + const size_t rec = size_t(own_manager) * 0xB0C + 0x8ac; + rate = uint8_t((int16_t(g.manager_records.at(rec) | g.manager_records.at(rec + 1) << 8) >> 4) + 0x28); + } + bool marking[24] = {}; // local_70: own slots already marking + const SquadRange own_range = squad_range(own), other_range = squad_range(other); + int16_t targets[24]; + uint32_t target_key[24]; + int n = 0; // local_38 + for (size_t s = 0; s < other_range.count; s++) { + const uint16_t slot = g.squad_slots.at(other_range.first + s); + if (!(slot & kSlotInLineup)) continue; + const Player& p = g.players.at(slot & 0x0FFF); + const int position = int(p.w364 & 3); + if (position < 2) continue; + targets[n] = int16_t(s); + target_key[n] = uint32_t(((position - 2) << 6) + int16_t(p.strength(false)) + int(p.w35c >> 21 & 7) * 8 + + int(p.w368 >> 18 & 0x3F) * 4 + int(p.w364 >> 2 & 0x3F) * 8); + n++; + } + if (n == 0) return; + quicksort_by_key(targets, target_key, n); + for (int k = 0; k < n; k++) { + const int bonus = k < 3 ? (3 - k) * 10 : 0; + if (!(100 - chance < rand.range(0, 100) + bonus)) continue; + const int target = targets[k]; // local_34 + int tx = 0, ty = 0; + g.formation_position(other, target, tx, ty); + int16_t candidates[24]; + uint32_t candidate_key[24]; + int m = 0; // local_20 + for (size_t s = 0; s < own_range.count; s++) { + const uint16_t slot = g.squad_slots.at(own_range.first + s); + if (marking[s] || !(slot & kSlotInLineup)) continue; + const Player& p = g.players.at(slot & 0x0FFF); + const int position = int(p.w364 & 3); + if (position != 1 && position != 2) continue; + int ox = 0, oy = 0; + g.formation_position(own, int(s), ox, oy); + candidates[m] = int16_t(s); + candidate_key[m] = uint32_t(int16_t(p.strength(false)) + int(p.w368 >> 8 & 3) * 0x10 + + int16_t((0x19 - std::abs(tx - ox)) + std::abs(ty - oy)) * 0x10); + m++; + } + if (m == 0) return; + quicksort_by_key(candidates, candidate_key, m); + for (int j = 0; j < m; j++) { + if (!(rand.range(0, 100) < rate)) continue; + const int marker = candidates[j]; + if (other_manager >= 0) { + const uint16_t id = g.squad_slots.at(own_range.first + size_t(marker)) & 0x0FFF; + const size_t at = size_t(other_manager) * 0x840 + size_t(target) * 0x58 + 0x46; + g.tactics.at(at) = uint8_t(id), g.tactics.at(at + 1) = uint8_t(id >> 8); + } + if (own_manager >= 0) { + const uint16_t id = g.squad_slots.at(other_range.first + size_t(target)) & 0x0FFF; + const size_t at = size_t(own_manager) * 0x840 + size_t(marker) * 0x58 + 0x44; + g.tactics.at(at) = uint8_t(id), g.tactics.at(at + 1) = uint8_t(id >> 8); + } + marking[marker] = true; + break; + } + } +} + +} // namespace + +void kick_off(ModernState& g, std::vector& groups, const MatchdayContext& ctx, WatcomRandom& rand, + GameRandom& game, MinuteReport& report, bool select_sportschau, uint16_t club_threshold) { + // LiveSceneVisible = 1 - CareerSession_DispatchLiveTactic_RuntimeField3, set by the caller of DayCompetitions2 right after the + // matchday setup; MatchdaySetupRuntimeField12 = 0 (no live match chosen yet). + g.live_scene = uint8_t(1 - (g.memory.has(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) ? g.memory.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) : 0)) != 0; + g.live_matches.clear(); + g.sportschau_selection_available = false; + g.sportschau_club_threshold = club_threshold; + if (select_sportschau) reset_sportschau_selection(g); + for (size_t s = 0; s < transfer_list_slot() && s < g.squad_slots.size(); s++) { + const uint16_t slot = g.squad_slots[s]; + if ((slot & 0x0FFF) != 0x0FFF) g.players.at(slot & 0x0FFF).w364 &= ~0x1000u; // not played yet + } + // tactics board byte 0x10: 0 starts, 0x7f on the bench, 0x7e not in the squad + for (size_t k = 0; k < g.manager_teams.size(); k++) { + const SquadRange range = squad_range(g.manager_teams[k]); + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t slot = g.squad_slots.at(s); + if ((slot & 0x0FFF) == 0x0FFF) break; + g.tactics.at(k * 0x840 + (s - range.first) * 0x58 + 0x10) = slot & 0x8000 ? 0 : slot & 0x4000 ? 0x7f : 0x7e; + } + } + for (MatchGroup& grp : groups) { + const int n = grp.matches(); + const int league = int(le32(grp.desc, 0xcc)); + put32(grp.desc, 0xb8, 0); + for (size_t i = 0xbc; i < 0xcc; i++) grp.desc.at(i) = 0; // bookings, sendings-off, crowd, goals (Assign) + grp.records.assign(size_t(n) * 18, 0); + grp.end_minute.assign(size_t(n), 0); + grp.spectators.assign(size_t(n), 0); + uint32_t void_mask = 0; + if (grp.desc.at(0) != 0) { + // cups: no league result bytes; the results of this leg start at 0:0 + grp.results.clear(); + grp.cup_results.assign(size_t(n), 0); + } else { + grp.results.assign(size_t(n), 0); + const size_t at = size_t(league) * 0x17C + size_t(g.league_rounds.at(size_t(league))) * 10; + for (int m = 0; m < n; m++) { + uint8_t& r = g.results.at(at + size_t(m)); + if (r == 0xCC) + r = 0; // 0:0 before kick-off + else + void_mask |= 1u << m; + grp.results[size_t(m)] = r; + } + } + put32(grp.desc, 0xb8, void_mask); + grp.kickoff_void_mask = void_mask; + for (int m = 0; m < n; m++) { + if (void_mask & (1u << m)) continue; + const int home = grp.fixtures.at(size_t(m) * 2), away = grp.fixtures.at(size_t(m) * 2 + 1); + const bool live = select_live_match(g, home, away); + if (!live && select_sportschau) consider_sportschau_fixture(g, grp, home, away, rand); + int forfeit_side = -1; + for (int side = 0; side < 2; side++) { + // the original swaps home and away after each pass + const int t = side ? away : home, opponent = side ? home : away; + const int own_manager = g.manager_of(t), other_manager = g.manager_of(opponent); + if ((own_manager >= 0 || other_manager >= 0) && (other_manager < 0 || g.manager_option(other_manager, 3))) { + const int rate = rand.range(0x46, 0x50); + man_marking(g, own_manager, t, other_manager, opponent, 0x32, rate, rand); + } + const TeamAverage fit = team_average(g, t, 0x1f1, &rand); + if ((t < league_clubs() || t == no_team()) && (fit.players & 0xFF) < 8) { + // FinishEvent sets this fixture's local void bit and BuildSideRecords writes + // the awarded 0:2/2:0 score before continuing to the next fixture. + forfeit_side = side; + const int manager = g.manager_of(t); + if (manager >= 0) modern::book_money(g, manager, 200000, true, true); // BookMoney2 + if (g.memory.has(::bmh::layout::MatchdaySetup_KickOff_RuntimeField + uint32_t(t) * 2)) + g.memory.set8(::bmh::layout::MatchdaySetup_KickOff_RuntimeField + uint32_t(t) * 2, + uint8_t(g.memory.u8(::bmh::layout::MatchdaySetup_KickOff_RuntimeField + uint32_t(t) * 2) + 1)); + } + } + if (forfeit_side >= 0) { + restore_forfeit_squad(g, home); + restore_forfeit_squad(g, away); + void_mask |= 1u << m; + grp.kickoff_void_mask |= 1u << m; + put32(grp.desc, 0xb8, void_mask); + const int home_goals = forfeit_side == 0 ? 0 : 2; + const int away_goals = forfeit_side == 0 ? 2 : 0; + if (grp.desc.at(0) == 0) { + const size_t at = size_t(league) * 0x17C + + size_t(g.league_rounds.at(size_t(league))) * 10 + size_t(m); + const uint8_t score = uint8_t((home_goals << 4) | away_goals); + g.results.at(at) = score; + grp.results.at(size_t(m)) = score; + } else { + grp.cup_results.at(size_t(m)) = uint16_t((home_goals << 5) | away_goals); + } + continue; + } + const int bits = modern::match_mode_bits(g, grp, ctx, report); + int spectators; + if (g.indoor) + spectators = 10000; + else + spectators = modern::attendance(g, home, away, int16_t(bits), int8_t(grp.desc.at(0x30 + size_t(m))), + grp.desc.at(0x50 + size_t(m)), grp.desc.at(0), game, rand, report); + put32(grp.desc, 0xc4, le32(grp.desc, 0xc4) + uint32_t(spectators)); + grp.spectators[size_t(m)] = uint32_t(spectators); + MatchSetup setup; + setup.home = home; + setup.away = away; + setup.match_index = m; + setup.climate_effect = (grp.desc.at(1) & 2) != 0; + setup.temperature = int8_t(grp.desc.at(0x30 + size_t(m))); + setup.spectators = spectators; + setup.month = ctx.month; + const std::array sides = build_side_records(g, setup, rand, &game); + for (int s = 0; s < 2; s++) + for (int b = 0; b < 9; b++) grp.records[size_t(m) * 18 + size_t(s) * 9 + size_t(b)] = sides[size_t(s)].b[size_t(b)]; + } + } + modern::store_group_descriptors(g, groups); +} + +} // namespace bmh::modern + +namespace bmh::modern { + +std::vector shuffle_manager_order(ModernState& g, GameRandom& game) { + constexpr uint32_t kOrder = ::bmh::layout::NextDeskManager; // u16 per manager + const int n = int(g.manager_teams.size()); + std::vector order(static_cast(n)); + for (int i = 0; i < n; i++) order[size_t(i)] = g.memory.has(kOrder) ? g.memory.u16(kOrder + uint32_t(i) * 2) : i; + for (int i = 0; i < n; i++) std::swap(order[size_t(i)], order[size_t(game.range(0, n - 1))]); + if (g.memory.has(kOrder)) + for (int i = 0; i < n; i++) g.memory.set16(kOrder + uint32_t(i) * 2, uint16_t(order[size_t(i)])); + return order; +} + +} // namespace bmh::modern + +namespace bmh::modern { + +Bytes group_descriptor(const ModernState& g, size_t index) { + constexpr uint32_t kGroups = ::bmh::layout::MatchdayGroupDescriptors; + Bytes d(kDescriptorSize, 0); + const uint32_t at = kGroups + uint32_t(index) * kDescriptorSize; + if (g.memory.has(at)) + for (size_t i = 0; i < kDescriptorSize; i++) d[i] = g.memory.u8(at + uint32_t(i)); + return d; +} + +void store_group_descriptors(ModernState& g, const std::vector& groups, bool with_log) { + constexpr uint32_t kGroups = ::bmh::layout::MatchdayGroupDescriptors; + for (size_t gi = 0; gi < groups.size() && gi < 6; gi++) { + const uint32_t at = kGroups + uint32_t(gi) * kDescriptorSize; + if (!g.memory.has(at)) continue; + const Bytes& d = groups[gi].desc; + auto copy = [&](size_t from, size_t to) { + for (size_t i = from; i < to; i++) g.memory.set8(at + uint32_t(i), d.at(i)); + }; + copy(0, 4); // type, flags, matches + copy(0x10, 0x70); // referees, temperatures, rain + copy(0xb8, 0xcc); // void mask, attendance + copy(0x94, 0x96); // event log entries + // cup groups keep their fixtures in the descriptor (SetupCupGroups) + if (d.at(0) != 0 && !(d.at(1) & 4)) copy(0x88, 0x88 + size_t(d.at(2)) * 4); + if (with_log) g.memory.set16(at + 0x94, uint16_t(groups[gi].log.size())); + // league number, or the guest pointer to the cup table entry + const uint32_t v = le32(d, 0xcc); + g.memory.set32(at + 0xcc, d.at(0) == 0 ? v : v + kGuestDataBase); + } +} + +} // namespace bmh::modern + +namespace bmh::modern { + +namespace { + +// MatchScore (read): the current score of match m as the original reads it, including the +// "not played" markers (0xCC -> 12:12, 0xCCCC -> 6:12). +void raw_score(const ModernState& g, const MatchGroup& grp, int m, int& home, int& away) { + if (grp.desc.at(0) == 0) { + const int league = int(le32(grp.desc, 0xcc)); + const uint8_t r = g.results.at(size_t(league) * 0x17C + size_t(g.league_rounds.at(size_t(league))) * 10 + size_t(m)); + home = r >> 4, away = r & 0xF; + } else { + const uint16_t r = grp.cup_results.at(size_t(m)); + home = (r >> 5) & 0x1F, away = r & 0x1F; + } +} + +} // namespace + +void build_pools_coupon(ModernState& g, const std::vector& groups, WatcomRandom* rand) { + g.pools_open = true; // PoolsOpenFlag = 0xcc + int n = 0; + for (const MatchGroup& grp : groups) { + for (int m = 0; m < grp.matches() && n != 0x16; m++) { + int home = 0, away = 0; + raw_score(g, grp, m, home, away); + if (!((home == 0xc || home == 6) && away == 0xc)) continue; + const int a = uint16_t(team_average(g, grp.fixtures.at(size_t(m) * 2), 0x1ff, rand).value); + const int b = uint16_t(team_average(g, grp.fixtures.at(size_t(m) * 2 + 1), 0x1ff, rand).value); + if (std::abs(a - b) >= 0x12) continue; + for (int s = 0; s < 2; s++) g.memory.set16(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + uint32_t(n++) * 2, uint16_t(grp.fixtures.at(size_t(m) * 2 + size_t(s)))); + } + if (n == 0x16) break; + } + g.memory.set8(::bmh::layout::CareerSession_DispatchToto_RuntimeField, uint8_t(n >> 1)); // CareerSession_DispatchToto_RuntimeField: matches on the coupon +} + +void evaluate_pools_coupon(ModernState& g, const std::vector& groups) { + if (!g.pools_open) return; // (PoolsOpenFlag != 0xcc: evaluated already) + g.pools_open = false; + int k = 0; + for (const MatchGroup& grp : groups) { + for (int m = 0; m < grp.matches() && k < 0xb; m++) { + if (grp.fixtures.at(size_t(m) * 2) != int(g.memory.u16(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + uint32_t(k) * 4))) continue; + int home = 0, away = 0; + modern::match_score(grp, m, home, away); + g.memory.set8(::bmh::layout::MatchdaySetup_EvaluatePoolsCoupon_RuntimeField + uint32_t(k), uint8_t(away < home ? 1 : home == away ? 0 : 2)); + k++; + } + if (k >= 0xb) break; + } + g.memory.set8(::bmh::layout::CareerSession_DispatchToto_RuntimeField, uint8_t(k)); // CareerSession_DispatchToto_RuntimeField: matches evaluated +} + +void settle_pools_coupon(ModernState& g, const std::vector& groups) { + StaticMemory& mem = g.memory; + if (!mem.has(::bmh::layout::Coupon) || !mem.has(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField)) return; + // the coupon's matches among today's (in the order of the coupon, home team at +0) + int k = 0; + for (const MatchGroup& grp : groups) { + for (int m = 0; m < grp.matches() && k < 0xb; m++) + if (grp.fixtures.at(size_t(m) * 2) == int(mem.u16(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + uint32_t(k) * 4))) k++; + if (k >= 0xb) break; + } + if (mem.has(::bmh::layout::CareerSession_DispatchToto_RuntimeField)) mem.set8(::bmh::layout::CareerSession_DispatchToto_RuntimeField, uint8_t(k)); + if (k <= 10) return; + static constexpr uint8_t kQuota[12] = {11, 10, 0, 20, 11, 10, 0, 1, 0, 10, 20, 50}; // MatchdaySetupRuntimeField13 + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const uint32_t at = ::bmh::layout::Coupon + uint32_t(m) * 0x14; + if (mem.u8(at + 3) & 0x80) mem.set32(at, 0); + const uint32_t stake = mem.u32(at); + if ((stake & 0x7fffffff) == 0) continue; + if (!modern::book_money(g, int(m), int32_t(stake), false, true)) { + post_composed(g, int(m), message_text(g, ::bmh::layout::MatchdaySetup_SettlePoolsCoupon_TextPointer)); + } else { + int hits = 0; + for (uint32_t i = 0; i < 0xb; i++) + if (mem.u8(at + 8 + i) == mem.u8(::bmh::layout::MatchdaySetup_EvaluatePoolsCoupon_RuntimeField + i)) hits++; + uint32_t win = 0; + if (hits > 8) win = stake * kQuota[hits]; + mem.set32(at + 4, win); + mem.set8(at + 0x13, uint8_t(hits)); + modern::book_money(g, int(m), -int32_t(win), true, true); + } + mem.set32(at, 0); // (also clears the "settled" bit 7 of byte 3 just set) + } +} + +} // namespace bmh::modern diff --git a/src/modern/game/matchday_setup.hpp b/src/modern/game/matchday_setup.hpp new file mode 100644 index 0000000..7a0bd58 --- /dev/null +++ b/src/modern/game/matchday_setup.hpp @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +#include "game/matchday_setup.hpp" +// Before the first minute of a matchday (BMH.exe V2.24 + supported rule profile patch). +// +// When "Weiter" reaches a day with a calendar event, AdvanceTurn prepares the matchday: +// 1. DayCompetitions2 builds one match group per league playing today (FixturesFromGenerateFixtures): +// fixtures of the next round, the result bytes of that round, and per match the +// weather and the referee (MatchWeather). Every team is then prepared for the match +// (PrepareTeam: cards of this competition, injuries, line-up flags) and gets an +// automatic line-up (Int2 mode 100). CycleManagerOptions advances the human +// managers' option byte 0 to the next enabled setting. +// 2. CurrentMatchday = WatcomRandom(0, 10000); PrepareEvent shuffles the order in which +// the human managers see their pre-match desks (one game draw per manager). +// 3. The matchday driver FinishEvent (called through the supported rule profile wrapper +// MatchdaySetupOperation) starts: "played" flags are cleared, the human tactics boards note who +// starts, every group's unplayed result bytes are set to 0:0 (anything else voids +// the match), and per match the attendance (Attendance) and the side records +// (BuildSideRecords3 + BuildSideRecords2) are computed. +// After that the minute loop (match_engine.hpp) runs. +// +// Ported for league matchdays of computer teams. Cups, indoor tournaments, the winter +// break postponements, human teams in a match (pre-match desk, own stadium, income) and +// Teams with fewer than 8 fit players receive the original 0:2 forfeit award. + +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// Globals of the original that the preparation reads but that are not part of ModernState. + +// The 0xD0-byte descriptor of match group `index` as it is left in memory (block MatchdayGroupDescriptors) from +// the previous matchday: the preparation only overwrites what it needs, so for example +// the referee bytes of matches without referee keep old values. +Bytes group_descriptor(const ModernState& g, size_t index); +// Writes the descriptors back (the per-match bytes, void mask, attendance, league/cup). +void store_group_descriptors(ModernState& g, const std::vector& groups, bool with_log = false); + +// MatchWeather: temperature (descriptor +0x30), rain (+0x50) and referee (+0x10) of +// match m of a group. +void match_weather(MatchGroup& grp, int m, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand); + +// PrepareTeam: prepares the squad of `team` before a match of a competition of class +// `cls` (MatchEngineRuntimeField9[type]: 0 league, 1-4 cups with their own card counters, 0xFF none). +// `index` is the team's position in the flat fixture list (home 0, away 1, ...). +void prepare_team(ModernState& g, int team, int cls, int index); + +// DayCompetitions2(..., 1): builds the match groups of the competitions in `competitions` +// (SavedCompetition) and prepares all teams. Returns the groups in the order of the original. +// DayCompetitions: the competitions of a day from its calendar entry (CompetitionCalendar): the low +// 15 bits, with special entries mapped (0x4001 group -> 0x8000, 0x4002 -> layout field indoor +// tournament, 0x4004 -> layout field, 0x4006 -> national-only flag or nothing) and the four league +// groups 0x1e00 rotating with the season. +uint32_t day_competitions(const ModernState& g, uint16_t entry); + +// IndoorTournamentDraw: the draw of an indoor tournament (eight clubs, the host names it). +void indoor_tournament_draw(ModernState& g, GameRandom& game, WatcomRandom& rand); +// The part of IndoorTournamentDraw that also runs before the Masters (CupRuntimeField != 0, no draw): +// before the first tournament the Masters points (Cup_AdvanceCup_ExecutableField) and invitations +// (MatchdaySetup_IndoorTournamentDraw_RuntimeField) are cleared; the name becomes "In ", the results of block MatchdayGroupWorkspace 0xCC and +// the played counters of the cup entries 25-29 0. +void indoor_tournament_reset(ModernState& g); + +std::vector setup_matchday(ModernState& g, uint32_t competitions, const MatchdayContext& ctx, + GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// MatchdayNeedsManagerDesks / AdvanceTurn: after preparation and manager-order shuffling, +// F6 (MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField == 0) admits the whole manager desk loop only if a manager plays. +// Postponed/already played league fixtures do not count. Opening/closing season +// desks, national friendlies and the Source auto-continue latch retain their gates. +// Read-only; callers still simulate an event whose desks are skipped. +bool matchday_needs_manager_desks(const ModernState&, uint16_t calendar_entry, + const std::vector&); + +// CycleManagerOptions: option byte 0 of every human manager moves on to the next setting that +// is enabled in the manager record (+0x218, a bit mask of settings 1-8). +void cycle_manager_options(ModernState& g); + +// MatchModeBits plus the flags added by BuildSideRecords: the "mode bits" passed to the +// attendance. Bits 0-4 a crowd interest value (per competition type, rising towards the +// end of the league season), 0x20 random spread, 0x80 no league match, 0x100 cup of +// class 1, 0x200 other cups. +int match_mode_bits(const ModernState& g, const MatchGroup& grp, const MatchdayContext& ctx, MinuteReport& report); + +// Attendance: attendance of a match. For a human home club also the gate and kiosk +// income, the attendance statistics of its record and a possible riot (message, damage). +// competition_type = byte 0 of the group descriptor (MatchdaySetupRuntimeField14). Bits 0x180 +// select cup gate sharing, including the away human manager's income/statistics. +int attendance(ModernState& g, int home, int away, int bits, int temperature, int rain, int competition_type, + GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// PrepareEvent(ManagerCount, NextDeskManager): shuffles the order of the human managers' pre-match +// desks in place - the order of the matchday before is shuffled again, not 0, 1, ... - and +// returns it (manager indices). One game draw per manager: entry i swaps with entry G(0, n - 1). +std::vector shuffle_manager_order(ModernState& g, GameRandom& game); + +// The start of FinishEvent up to the first minute: flags, void masks, attendance and side +// records for every match of every group, including the live match choice (AutoLineup) and +// the man marking of human managers (KickOff). Human teams draw from `game` in their +// ratings (team_rating). +void kick_off(ModernState& g, std::vector& groups, const MatchdayContext& ctx, WatcomRandom& rand, + GameRandom& game, MinuteReport& report, bool select_sportschau = false, + uint16_t club_threshold = 90); + +} // namespace bmh::modern + +namespace bmh::modern { + +// CurrentMatchday = WatcomRandom(0, 10000), drawn by AdvanceTurn after the preparation (kept +// in the savegame). +inline void draw_matchday_number(ModernState& g, WatcomRandom& rand) { + const int v = rand.range(0, 10000); + if (g.memory.has(::bmh::layout::CurrentMatchday)) g.memory.set32(::bmh::layout::CurrentMatchday, uint32_t(v)); +} + +} // namespace bmh::modern + +namespace bmh::modern { + +// BuildPoolsCoupon, at a human manager's pre-match desk: the pools coupon (block DeskActions_SubmitPoolsCoupon_RuntimeField) - up +// to 11 of today's matches between clubs of similar strength (team_average 0x1ff within +// 17); CareerSession_DispatchToto_RuntimeField = their number. +// Teams without a squad (national teams) draw their average from `rand` (TeamRating). +void build_pools_coupon(ModernState& g, const std::vector& groups, WatcomRandom* rand = nullptr); + +// EvaluatePoolsCoupon(0) at full time of that matchday: the results of the coupon's matches, +// MatchdaySetup_EvaluatePoolsCoupon_RuntimeField[i] = 1 home win, 0 draw, 2 away win. +void evaluate_pools_coupon(ModernState& g, const std::vector& groups); + +// EvaluatePoolsCoupon(1) at the end of the matchday: with 11 matches on the coupon every human +// manager's tip (Coupon + manager * 0x14: stake u32, tips +8..+0x12) is settled - the +// stake is booked (BookMoney2, may fail: "Ihr Tototipp wurde nicht berücksichtigt ..." +// MatchdaySetup_SettlePoolsCoupon_TextPointer), the hits counted (+0x13), from 9 on the stake times the quota +// (MatchdaySetupRuntimeField13: 10, 20, 50) is won (+4) and booked; the stake is cleared. The coupon's +// matches are counted again in the groups of the matchday (CareerSession_DispatchToto_RuntimeField; the outcomes stay +// those read after the second half, PoolsOpenFlag / MatchdaySetup_EvaluatePoolsCoupon_RuntimeField). The toto screen +// it shows (LeagueTableRangeDialog) draws nothing. +void settle_pools_coupon(ModernState& g, const std::vector& groups); + +// Modern version of the function sportschau_presentation.hpp declares for Classic. +bool sportschau_selected(const ModernState& g, int home); + +} // namespace bmh::modern diff --git a/src/modern/game/modern_state.cpp b/src/modern/game/modern_state.cpp new file mode 100644 index 0000000..d68dcb0 --- /dev/null +++ b/src/modern/game/modern_state.cpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/game/modern_state.hpp" + +#include "modern/game/matchday.hpp" +#include "modern/game/prediction.hpp" + +namespace bmh::modern { + +namespace { + +// The shared match core passes the GameState base; Modern games always hold a ModernState. +void statistic(GameState& g, int competition_type, int player, int manager, int slot, int kind, int minute) { + player_statistic(static_cast(g), competition_type, player, manager, slot, kind, minute); +} + +int prediction(GameState& g, int team, int mode, std::array& buf, int* size_word) { + return table_prediction(static_cast(g), team, mode, buf, size_word); +} + +} // namespace + +const SeasonHooks& season_hooks() { + static const SeasonHooks hooks{&statistic, &prediction}; + return hooks; +} + +} // namespace bmh::modern diff --git a/src/modern/game/modern_state.hpp b/src/modern/game/modern_state.hpp new file mode 100644 index 0000000..6a5e65d --- /dev/null +++ b/src/modern/game/modern_state.hpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The game state of the Modern season core. +// +// Modern started as a fork of the Classic season core (docs/new_engine). Its season +// functions take ModernState instead of GameState: the shared parts (formats, match +// core, line-ups, ratings) keep working on the GameState base, and overload resolution +// always prefers the Modern season function over a Classic one of the same name. +// Modern-only data (world layout, UTF-8 names, ...) is added here, never to GameState. + +#include +#include + +#include "game/state.hpp" +#include "game/world_layout.hpp" + +namespace bmh::modern { + +// Dimensions of the running world (WorldLayout). Modern code uses these accessors where +// the Classic sources have the fixed numbers (138 league clubs, 90 German clubs, 168, the +// pool slots 0xb70/0xb9c/0xbec/0xc00, 3150 slots); no_team() replaces kNoTeam (0x165). +inline int league_clubs() { return world_layout().league_teams; } +inline int german_clubs() { return world_layout().german_teams; } +inline int first_foreign_cup() { return world_layout().first_foreign_cup(); } +inline size_t transfer_list_slot() { return world_layout().transfer_list; } +inline size_t free_agent_slot() { return world_layout().free_agents; } +inline size_t foreign_offer_slot() { return world_layout().foreign_offers; } +inline size_t pool_end_slot() { return world_layout().pool_end; } +inline size_t total_squad_slots() { return world_layout().total_slots; } + +// The callbacks the shared match core uses for season functions (SeasonHooks). +const SeasonHooks& season_hooks(); + +struct ModernState : GameState { + ModernState() { season_hooks = &modern::season_hooks(); } + // Takes over a state built by shared code (save loading, career setup). + ModernState(GameState&& g) : GameState(std::move(g)) { season_hooks = &modern::season_hooks(); } + ModernState(const GameState& g) : GameState(g) { season_hooks = &modern::season_hooks(); } +}; + +} // namespace bmh::modern diff --git a/src/modern/game/month.cpp b/src/modern/game/month.cpp new file mode 100644 index 0000000..44b01f5 --- /dev/null +++ b/src/modern/game/month.cpp @@ -0,0 +1,990 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/environment.hpp" +#include "modern/game/month.hpp" +#include "game/trace.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "game/lineup.hpp" +#include "modern/game/matchday.hpp" +#include "game/messages.hpp" +#include "modern/game/prediction.hpp" +#include "game/schedule.hpp" +#include "modern/game/season.hpp" +#include "modern/game/weekly.hpp" +#include "game/human_buyer_sale.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecord = 0xB0C; // manager record +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; +constexpr uint32_t kListEntry = 0x58; + +// MonthRuntimeField2: development steps by strength / 10; the ten bytes after it (PlayerCard_PlayerCardMarketValue_RuntimeField) +// are the extra value above 500 points. +constexpr uint8_t kDevelopment[20] = {6, 6, 6, 5, 5, 5, 4, 4, 3, 1, 10, 15, 20, 30, 40, 45, 55, 75, 85, 95}; +// BalancePlanRuntimeField5: value of the facilities (maintenance per month), u16 per facility. +constexpr uint16_t kFacilityValue[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600, + 2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000}; +// BalancePlanRuntimeField6: monthly income of facilities 0-5 per level. +constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000}; +// MonthRuntimeField3: share of the new list entries per kind (free agents, big clubs, foreign +// agents, small clubs), percent. +constexpr int16_t kListShare[4] = {47, 35, 10, 8}; +// MonthRuntimeField4 / MonthRuntimeField5: players a club wants per position (big / small squads). +constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4}; + +uint32_t rd32(const std::vector& v, size_t o) { + return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16) | uint32_t(v.at(o + 3)) << 24; +} +void wr32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i)); +} +void add32(std::vector& v, size_t o, int32_t x) { wr32(v, o, rd32(v, o) + uint32_t(x)); } + +// BoughtEntry: index + 1 of a player in the table of players bought for later / on loan +// (Career_RemoveJoinLoans_RuntimeField), 0 if none. +int bought_entry(const ModernState& g, int player) { + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xFFF) == player) return k + 1; + } + return 0; +} + +// PlayerOnTransferListFirstPoolSlots: index + 1 of the list entry of the player in an absolute squad slot (the +// first 44 pool slots), 0 if he is not on the list. +int list_index(const ModernState& g, int slot) { + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + for (int s = int(transfer_list_slot()); s < int(transfer_list_slot()) + 0x2c; s++) + if ((g.squad_slots[size_t(s)] & 0xFFF) == player) return s - int(transfer_list_slot()) + 1; + return 0; +} + +// FirstFreeSlotSquad(start, count): first empty squad slot from `start`, -1 if none. +int free_slot(const ModernState& g, int start, int count) { + for (int s = start; s < start + count && s < int(g.squad_slots.size()); s++) + if (g.squad_slots[size_t(s)] == 0xFFF) return s; + return -1; +} + +// ListPlayer: puts the player in an absolute squad slot on the transfer list: the first +// free list slot, asking price and demand percentages, 5-8 weeks, the market value; human +// managers with a matching search profile are told. +bool list_player(ModernState& g, int slot, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + if (bought_entry(g, player) != 0) { + report.fail("transfer list: the player is bought for later (internal error 0x38)"); + return false; + } + if (list_index(g, slot) != 0) { + report.fail("transfer list: the player is listed already (ListPlayer message box)"); + return false; + } + // (the original passes 0xb70 + 0x28 as the count: the search runs on past the list) + const int free = free_slot(g, int(transfer_list_slot()), int(transfer_list_slot()) + 0x28); + if (free == -1) return false; // message box MonthRuntimeField6 + if (free >= int(transfer_list_slot()) + 0x2c) { + report.fail("transfer list: the free slot lies beyond the list (the original overwrites memory)"); + return false; + } + g.squad_slots[size_t(free)] = uint16_t(player); + const uint32_t e = kTransferList + uint32_t(free - int(transfer_list_slot())) * kListEntry; + if (slot < int(transfer_list_slot())) { + const int seller = modern::slot_team(slot); + uint16_t field = uint16_t(seller); + mem.set16(e + 8, field); + if (g.manager_of(seller) >= 0) mem.set8(e + 9, uint8_t(mem.u8(e + 9) | 0x80)); + mem.set8(e + 0x54, uint8_t(rand.range(0x4b, 0x7a))); + mem.set8(e + 0x55, uint8_t(rand.range(0x5c, 100))); + if (seller >= german_clubs()) mem.set8(e + 0x54, uint8_t(mem.u8(e + 0x54) + rand.range(5, 0xf))); + } else { + mem.set16(e + 8, 0xFFF); + mem.set8(e + 0x54, uint8_t(rand.range(0x46, 0x69))); + mem.set8(e + 0x55, uint8_t(rand.range(0x3c, 0x60))); + } + mem.set8(e + 0x56, uint8_t(rand.range(5, 8))); + uint32_t fee = 0, salary = 0; + modern::market_value(g, slot, 0, mem.u8(e + 0x54), fee, salary, 1, 0, rand); + mem.set32(e + 0x2c, fee); + mem.set32(e + 0x30, salary); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF); + for (size_t m = 0; m < g.manager_teams.size(); m++) modern::search_profile_news(g, int(m), e, g.squad_slots[size_t(free)]); + return true; +} + +// PickFreeAgent(from, to): a random free agent in the pool slots from..to-1 who is not on +// the list and not bought for later. +int pick_free_agent(const ModernState& g, int from, int to, WatcomRandom& rand, MinuteReport& report) { + std::vector slots; + for (int s = from; s < to; s++) { + const int p = g.squad_slots.at(size_t(s)) & 0xFFF; + if (p != 0xFFF && list_index(g, s) == 0 && bought_entry(g, p) == 0) slots.push_back(s); + } + if (slots.empty()) { + report.fail("transfer list: no free agent (internal error 0x26)"); + return -1; + } + return slots[size_t(rand.range(0, int(slots.size()) - 1))]; +} + +// InPseudoSquad: the player of a slot also plays in the squad of the pseudo club 0x165. +bool in_pseudo_squad(const ModernState& g, int slot) { + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const SquadRange r = squad_range(no_team()); + for (size_t s = r.first; s < r.first + r.count; s++) + if ((g.squad_slots[s] & 0xFFF) == player) return true; + return false; +} + +// Int5(first, last): a computer club (every second one, starting alternately at the +// first or second, MonthRuntimeField7) with too many goalkeepers or too many players in a line +// puts one of them on the list. With no club found in first..last the search is repeated +// over the big clubs. +void list_club_player(ModernState& g, int first, int last, WatcomRandom& rand, MinuteReport& report) { + const int8_t* wanted = first < german_clubs() ? kWantedBig : kWantedSmall; // Attempt + for (;;) { + std::vector teams(static_cast(league_clubs())); + std::vector keys(static_cast(league_clubs())); + int n = 0; // local_14 + g.list_toggle = g.list_toggle + 1 == 2 ? 0 : g.list_toggle + 1; + int best_line = 0; // local_1c, keeps its value between the clubs + for (int team = first + g.list_toggle; team < last; team += 2) { + if (g.manager_of(team) >= 0) continue; + const SquadRange range = squad_range(team); + int8_t count[4] = {0, 0, 0, 0}; // local_50 + const int players = int16_t(modern::squad_count(g, team, 3)); + for (int s = 0; s < players; s++) { + const int p = g.squad_slots.at(range.first + size_t(s)) & 0xFFF; + if (p != 0xFFF) count[g.players.at(size_t(p)).w364 & 3]++; + } + int key_base = 0, line = 0; + bool add = false; + if (rand.range(0, 1) + 2 < count[0]) { + // three or four goalkeepers + line = 0; + key_base = count[0] + 100; + add = true; + } else if (players > 0xd) { + const int flags = (g.team_flags.at(size_t(team)) >> 0xc) & 3; + if (rand.range(0, flags * 2 + 2) != 0) { + int8_t most = 0; // local_28 + for (int k = 1; k < 4; k++) { + const int8_t over = int8_t(count[k] - wanted[k]); + if (most < over) most = over, best_line = k; + } + int chosen = best_line; + if (most == 0) chosen = rand.range(1, 3); + key_base = most * 8; + const int8_t room = int8_t(range.count - ((team < german_clubs() ? 1 : 0) + 2)); + if (room < players) key_base += (players - room) * 4; + line = chosen; + add = true; + } + } + if (add) { + const int a = rand.range(0, 5), b = rand.range(0, 5); + keys[n] = uint32_t((key_base + a - b) * 4 + int8_t(line)); + teams[n] = int16_t(team); + n++; + } + } + int pick = league_clubs(); // sVar11 + int slot = -1; // unaff_EDI: the slot tried last + if (n != 0) { + quicksort_by_key(teams.data(), keys.data(), n); + for (pick = 0; pick < n; pick++) { + const int team = teams[pick]; + const SquadRange range = squad_range(team); + const int players = int16_t(modern::squad_count(g, team, 2)); + const int line = int(keys[pick] & 3); + int tries = 0; + bool again; + do { + slot = int(range.first) + rand.range(0, players - 1); + const int p = g.squad_slots.at(size_t(slot)) & 0xFFF; + const bool taken = bought_entry(g, p) != 0 || list_index(g, slot) != 0; + tries++; + again = int(g.players.at(size_t(p)).w364 & 3) != line || in_pseudo_squad(g, slot) || taken; + } while (tries < 0x23 && again); + if (tries < 0x23) break; + } + // (when no club had a fitting player the slot tried last is listed all the same) + } + if (pick < league_clubs()) { + list_player(g, slot, rand, report); + return; + } + if (first == 0) { + report.fail("transfer list: no club to take a player from (internal error 0x28)"); + return; + } + first = 0; + last = german_clubs(); + } +} + +// CareerFirstSteps: new players on the transfer list. The number depends on how full the list +// is (at most 37 entries); free agents of the pool are preferred while there are many. +void new_list_entries(ModernState& g, WatcomRandom& rand, MinuteReport& report) { + uint8_t count[5] = {0, 0, 0, 0, 0}; // local_18: listed, free agents, foreign, listed of both + for (int s = int(transfer_list_slot()); s < int(pool_end_slot()); s++) { + if (g.squad_slots.at(size_t(s)) == 0xFFF) continue; + if (!(s < int(transfer_list_slot()) + 0x28 || int(transfer_list_slot()) + 0x2c <= s)) continue; + const int cls = s < int(free_agent_slot()) ? 0 : s < int(foreign_offer_slot()) ? 1 : 2; + count[cls]++; + if (cls != 0 && list_index(g, s) != 0) count[cls + 2]++; + } + uint8_t add[4] = {0, 0, 0, 0}; // local_10 + const int r = rand.range(2, 0x16); + uint8_t n = uint8_t(r); + if (count[0] + int8_t(r) >= 0x26) { + n = uint8_t(0x25 - count[0]); + if (int8_t(n) <= 0) return; + } + count[1] = uint8_t(count[1] - count[3]); + count[2] = uint8_t(count[2] - count[4]); + for (int16_t u = count[1]; n != 0 && u > 0x36; u--) n--, add[0]++; + for (int16_t u = count[2]; n != 0 && u > 0xe; u--) n--, add[2]++; + for (int k = 0; k < 4; k++) add[k] = uint8_t(add[k] + int8_t(kListShare[k] * int8_t(n) / 100)); + if (count[1] < add[0]) { + add[1] = uint8_t(add[1] + ((add[0] - count[1]) >> 1)); + add[0] = count[1]; + } + if (count[2] < add[2]) { + add[3] = uint8_t(add[3] + ((add[2] - count[2]) >> 1)); + add[2] = count[2]; + } + int8_t total = 0; + for (int k = 0; k < 4; k++) total = int8_t(total + add[k]); + if (total < 4) add[1] = uint8_t(add[1] + rand.range(2, 4)); + if (add[3] == 0 && add[1] != 0 && rand.range(0, 10) == 5) add[3]++, add[1]--; + // (MonthRuntimeField8, a debug switch for club players only, is 0) + for (int k = 0; k < 4 && !report.unsupported; k++) { + uint8_t left = add[k]; + if (left == 0) continue; + switch (k) { + case 0: + case 2: + while (left != 0 && !report.unsupported) { + const int slot = k == 0 ? pick_free_agent(g, int(free_agent_slot()), int(foreign_offer_slot()), rand, report) + : pick_free_agent(g, int(foreign_offer_slot()), int(pool_end_slot()), rand, report); + if (slot < 0) return; + if (list_player(g, slot, rand, report)) left--; + } + break; + case 1: + while (left-- != 0 && !report.unsupported) list_club_player(g, 0, german_clubs(), rand, report); + break; + case 3: + while (left-- != 0 && !report.unsupported) list_club_player(g, german_clubs(), league_clubs(), rand, report); + break; + } + } +} + +// Loaned players whose time is up go back to their clubs (part of DayStepRest2). +void return_loans(ModernState& g, WatcomRandom& rand, GameRandom* game, MinuteReport& report) { + StaticMemory& mem = g.memory; + for (int s = 0; s < int(transfer_list_slot()) && !report.unsupported; s++) { + const int player = g.squad_slots.at(size_t(s)) & 0xFFF; + if (player == 0xFFF) continue; + const int k = bought_entry(g, player) - 1; + if (k < 0) continue; + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + const int owner = int(e >> 12 & 0x3FF), club = int(e >> 22 & 0x3FF); // local_30, local_28 + const int owner_manager = g.manager_of(owner); + const int borrower_manager = g.manager_of(club); + // Human owners have a saved tactics-board row in ClubInfo_FormatError_RuntimeField and a matching + // player ID/manager in Career_CareerManagersEnd_RuntimeField/ClubInfo_FormatError_RuntimeField2 (Fail). Restore it on expiry; + // AI owners have no snapshot. Stage the complete return so malformed state + // or a failed lineup cannot lose the loan ledger first. + if (owner_manager >= 0 || borrower_manager >= 0) { + const uint8_t remaining = mem.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k)); + if (remaining != 1) { + // Source decrements an unsigned byte and returns only when the + // decremented byte is zero (DayStepRest2). A malformed/stale zero + // therefore wraps to 0xff instead of expiring immediately. + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), uint8_t(remaining - 1)); + continue; + } + if ((owner_manager >= 4) || (owner_manager >= 0 && + (!mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || + !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b) || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager))))) { + report.fail("month change: human-owner loan record is incomplete"); + return; + } + int snapshot_slot = -1; + if (owner_manager >= 0) { + for (int i = 0; i < 12; ++i) { + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2) == uint16_t(player) && + mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(i)) == uint8_t(owner_manager)) { + snapshot_slot = i; + break; + } + } + } + const SquadRange owner_range = squad_range(owner); + const int owner_slot = free_slot(g, int(owner_range.first), int(owner_range.count)); + const SquadRange borrower_range = squad_range(club); + bool borrower_has_player = false; + for (size_t i = 0; i < borrower_range.count; ++i) + if ((g.squad_slots.at(borrower_range.first + i) & 0x0fff) == player) borrower_has_player = true; + if ((owner_manager >= 0 && snapshot_slot < 0) || owner_slot < 0 || !borrower_has_player || + (owner_manager >= 0 && size_t(owner_manager) * kBoard + + size_t(owner_range.count) * kBoardSlot > g.tactics.size())) { + report.fail("month change: human-owner loan cannot be restored safely"); + return; + } + if (borrower_manager >= 0 && !g.loan_return_screen) { + report.fail("month change: expiring human-borrower loan needs its Source return dialog owner"); + return; + } + ModernState staged = g; + try { + staged.memory.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), 0); + staged.memory.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4, 0); + staged.squad_slots.at(size_t(owner_slot)) = uint16_t(player); + if (!modern::remove_from_seller(staged, club, player, report)) return; + if (owner_manager >= 0) { + const size_t board = size_t(owner_manager) * kBoard + + size_t(owner_slot - int(owner_range.first)) * kBoardSlot; + const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(snapshot_slot) * uint32_t(kBoardSlot); + for (size_t b = 0; b < kBoardSlot; ++b) + staged.tactics.at(board + b) = staged.memory.u8(snapshot + uint32_t(b)); + staged.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(snapshot_slot) * 2, 0x0fff); + const uint8_t count = staged.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager)); + if (count == 0) { + report.fail("month change: human-owner loan count is inconsistent"); + return; + } + staged.memory.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager), uint8_t(count - 1)); + } + // DayStepRest2 posts the return notice to whichever owner/borrower + // managers exist. + const std::string notice = message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer) + staged.player_name(player) + + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer2) + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer3) + staged.club_name(club) + + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer4) + staged.club_name(owner) + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer5); + if (borrower_manager >= 0) { + const int keep = staged.loan_return_screen(staged, borrower_manager, + notice + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer6)); + if (keep < 0) { + report.fail("month change: human-borrower loan return dialog stopped"); + return; + } + if (keep != 0) { + // DayStepRest2 makes the borrower the active manager before + // RowWhose/Range2. The two W(90,100) draws occur even + // when all four special offer slots are occupied. + staged.memory.set8(::bmh::layout::ActiveManager, uint8_t(borrower_manager)); + int offer = 0; + while (offer < 4 && staged.memory.u32(::bmh::layout::OfferSlots + uint32_t(offer) * 4) != 0xffffffffu) + ++offer; + if (offer < 4 && (!game || !staged.loan_return_offer_screen)) { + report.fail("month change: OpenTransferEditor return-offer editor has no typed runtime owner"); + return; + } + WatcomRandom offer_rand = rand; + std::optional offer_game; + if (game) offer_game = *game; + const int percent = offer_rand.range(90, 100); + const int demand = offer_rand.range(90, 100); + if (offer < 4) { + const uint32_t entry = kTransferList + uint32_t(40 + offer) * kListEntry; + uint16_t team_word = uint16_t(owner); + if (owner_manager >= 0) team_word |= 0x8000; + staged.memory.set16(entry + 8, team_word); + for (int bid = 0; bid < 4; ++bid) + staged.memory.set16(entry + uint32_t(bid) * 2, 0xffff); + staged.memory.set8(entry + 0x54, uint8_t(percent)); + staged.memory.set8(entry + 0x55, uint8_t(demand)); + uint32_t fee = 0, salary = 0; + modern::market_value(staged, owner_slot, 0, uint8_t(percent), fee, salary, 1, 0, offer_rand); + staged.memory.set32(entry + 0x2c, fee); + staged.memory.set32(entry + 0x30, salary); + const int source_slot = int(transfer_list_slot()) + 40 + offer; + staged.squad_slots.at(size_t(source_slot)) = uint16_t(player); + staged.memory.set32(::bmh::layout::OfferSlots + uint32_t(offer) * 4, + uint32_t(player) * 0x400 + uint32_t(borrower_manager)); + // A modal may replace staged (and its hook) while paused. + // Own the active callable until the synchronous invocation returns. + const auto present_return_offer = staged.loan_return_offer_screen; + const int submitted = present_return_offer(staged, *offer_game, offer_rand, + borrower_manager, source_slot, 40 + offer, HumanBuyerSaleHooks{}); + if (submitted < 0) { + report.fail("month change: OpenTransferEditor return-offer editor stopped"); + return; + } + // The original month caller performs this cleanup only + // after OpenTransferEditor has returned from the actual editor. + staged.squad_slots.at(size_t(int(transfer_list_slot()) + 40 + offer)) = 0x0fff; + staged.memory.set32(::bmh::layout::OfferSlots + uint32_t(offer) * 4, 0xffffffffu); + } + rand = offer_rand; + if (game && offer_game) *game = *offer_game; + } + } + std::string return_notice = notice; + if (borrower_manager >= 0) { + const SquadRange returned_borrower_range = squad_range(club); + for (size_t i = 0; i < returned_borrower_range.count; ++i) { + if ((staged.squad_slots.at(returned_borrower_range.first + i) & 0x0fff) == player) { + return_notice += message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer7) + staged.club_name(club) + + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer8); + break; + } + } + } + uint32_t managers = 0x80000000u; + if (borrower_manager >= 0) managers = 1u << borrower_manager; + if (owner_manager >= 0) managers |= 1u << owner_manager; + post_composed(staged, int64_t(managers), return_notice); + auto_lineup(staged, owner, owner_manager >= 0 ? 0xe4 : 100); + auto_lineup(staged, club, borrower_manager >= 0 ? 0xe4 : 100); + } catch (const std::exception&) { + report.fail("month change: human-owner loan cannot be restored safely"); + return; + } + g = std::move(staged); + continue; + } + const uint8_t months = uint8_t(mem.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k)) - 1); + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), months); + if (months != 0) continue; + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4, 0); + const SquadRange range = squad_range(owner); + const int slot = free_slot(g, int(range.first), int(range.count)); + if (slot == -1) { + report.fail("month change: no room for a returning player (internal error 0x2e)"); + return; + } + g.squad_slots[size_t(slot)] = uint16_t(player); + if (!modern::remove_from_seller(g, club, player, report)) return; + modern::lineup_after_transfer(g, owner); + modern::lineup_after_transfer(g, club); + } +} + +// OriginalFinancePreview(1): the month's expenses of a human manager: facility maintenance +// (BMHExeXa), record +0x854/+0x858, the wages of the squad (MonthlyPay with flags +// 14), all six monthly environment budgets and the debt +// service (+0x179 x 1000); each booked in the statistics. +int32_t monthly_expenses(ModernState& g, int m) { + std::vector& r = g.manager_records; + const size_t rec = size_t(m) * kRecord; + int32_t sum = 0; + for (int i = 0; i < 0xe; i++) sum += kFacilityValue[i]; + for (int i = 0xe; i < 0x16; i++) sum += (r.at(rec + 0x2e + size_t(i)) & 7) * kFacilityValue[i]; + add32(r, rec + 0x87c, sum); + for (int k = 1; k < 3; k++) { + const int32_t v = int32_t(rd32(r, rec + 0x850 + size_t(k) * 4)); + add32(r, rec + 0x890 + size_t(k) * 4, v); + sum += v; + } + // MonthlyPay(manager, 14): salaries (+0x50) and bonus bases (+0x4e) of the board + int32_t wages = 0; + uint32_t bonus = 0; + for (size_t s = 0; s < 24; s++) { + const size_t slot = size_t(m) * kBoard + s * kBoardSlot; + if (g.tactics.at(slot + 0x3d) == 0xFF) continue; + bonus = uint32_t(g.tactics.at(slot + 0x4e) | (g.tactics.at(slot + 0x4f) & 0x7F) << 8); + const int32_t salary = int32_t(rd32(g.tactics, slot + 0x50)); + add32(r, rec + 0x338, salary); + add32(r, rec + 0x33c, int32_t(bonus)); + wages += salary + int32_t(bonus); + } + sum += wages; + for (int k = 0; k < 6; k++) { + const int32_t v = modern::environment_monthly_cost(g, m, k); + if (k >= 3 && k <= 5) add32(r, rec + 0x878 + size_t(k) * 4, v); + else add32(r, rec + 0x880, v); + sum += v; + } + const int debt = r.at(rec + 0x179); + if (debt != 0) { + add32(r, rec + 0x8a0, debt * 1000); + sum += debt * 1000; + } + return sum < 0 ? 0 : sum; +} + +// FinanceTotalsFromGame3(1): the month's income: facilities (FacilityIncome) and the 16 advertising +// contracts (record +0xa34), booked in the statistics. +int32_t monthly_income(ModernState& g, int m) { + std::vector& r = g.manager_records; + const size_t rec = size_t(m) * kRecord; + int32_t sum = 0; + for (int k = 0; k < 6; k++) { + const uint8_t v = r.at(rec + size_t(k)); + if (v == 0) continue; + const int level = k == 0 ? ((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32 + sum += level * kFacilityIncome[k]; + } + add32(r, rec + 0x86c, sum); + for (int k = 0; k < 16; k++) { + const int32_t v = int32_t(rd32(r, rec + 0xa34 + size_t(k) * 0xc)); + add32(r, rec + (k < 14 ? 0x860 : k == 14 ? 0x85c : 0x864), v); + sum += v; + } + return sum; +} + +// The monthly bookkeeping of the players on a human manager's tactics board. +void board_month(ModernState& g, int m, WatcomRandom& rand, MinuteReport& report, GameRandom* game) { + std::vector& r = g.manager_records; + const size_t rec = size_t(m) * kRecord; + const SquadRange range = squad_range(g.manager_teams.at(size_t(m))); + auto board = [&](int s) { return size_t(m) * kBoard + size_t(s) * kBoardSlot; }; + // the value history has 12 months; when it is full it moves on by one + int month = r.at(rec + 0x286); // local_24 + if (month < 0xc) { + r.at(rec + 0x286) = uint8_t(month + 1); + } else { + for (int s = 0; s < 24; s++) { + if (g.squad_slots.at(range.first + size_t(s)) == 0xFFF) continue; + for (int k = 0; k < 3; k++) { + const size_t at = board(s) + 0x19 + size_t(k) * 0xc; + std::copy(g.tactics.begin() + long(at + 1), g.tactics.begin() + long(at + 0xc), g.tactics.begin() + long(at)); + } + } + month = 0xb; + } + for (int s = 0; s < 24; s++) { + // (a player who leaves closes the gap: the same row is looked at again, or after the + // contracts screen all rows from the first one - those done are marked 0x80) + next_player: + const size_t b = board(s); + const int player = g.squad_slots.at(range.first + size_t(s)) & 0xFFF; + if (player == 0xFFF || (g.tactics.at(b + 0xb) & 0x80)) continue; + g.tactics.at(b + 0xb) |= 0x80; + if (rand.range(0, 0xb) == 0) { + const uint32_t limit = uint32_t(rand.range(0x11, 0x17)); + if (limit < (g.players.at(size_t(player)).w364 >> 21 & 0x1F) && !(g.tactics.at(b + 0xb) & 0x20)) { + // he wants to end his career at the end of his contract + g.tactics.at(b + 0xb) |= 0x20; + post_composed(g, m, g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer)); + } + } + g.tactics.at(b + 0x11)++; + if (rand.range(0, 6) == 0) { + // the mood (+0x0d) drifts back towards 100 + const int d = std::abs(100 - g.tactics.at(b + 0xd)); + if (int16_t(d) != 0) { + int16_t step = int16_t(d) < 0xb ? 1 : 10; + if (g.tactics.at(b + 0xd) > 100) step = int16_t(-step); + g.tactics.at(b + 0xd) = uint8_t(std::clamp(step + g.tactics.at(b + 0xd), 0, 0xff)); + } + } + if (g.tactics.at(b + 0x43) != 0) { + g.tactics.at(b + 0x43)--; + if ((g.tactics.at(b + 0x43) & 0x3f) == 0) g.tactics.at(b + 0x43) = 0; + } + if (g.tactics.at(b + 0xc) != 0xFF) g.tactics.at(b + 0xc)--; // contract months (BalancePlan_BalanceFromGame_RuntimeField is 0) + if (g.tactics.at(b + 0xc) <= 1) { + if (g.tactics.at(b + 0xc) != 0) { + // "'s Vertrag läuft in einem Monat ab. ..." (string at ContractExpiryWarningText) + post_composed(g, m, g.player_name(player) + + kContractEndsSoonText); + } else if (!(g.tactics.at(b + 0xb) & 0x20)) { + // the contract has ended: "... Vertrag ist ausgelaufen" (Month_BoardMonth_TextPointer4) and the + // contracts screen; without a renewal the message is posted and he goes + const std::string text = g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer4); + const int renewed = g.contract_screen ? g.contract_screen(g, m, s) : -2; + if (renewed == -2) { + report.fail("month change: a contract ends (the contracts screen InstallDefaultHooks)"); + return; + } + if (renewed < 0) return; + if (renewed == 0) { + post_composed(g, m, text); + if (!game) { + report.fail("month change: a player goes (MonthChange) without the game generator"); + return; + } + if (!modern::release_player(g, int(range.first) + s, *game, rand, report)) return; + s = 0; + goto next_player; + } + } else { + // he ends his career (flag 0x20, see above): Month_BoardMonth_TextPointer2, then his club gets + // a compensation, Month_BoardMonth_TextPointer3 + the amount (AddToSquad with W(15, 30) + // percent, 1 year, rounded down to 10000) + post_composed(g, m, g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer2)); + const int percent = rand.range(0xf, 0x1e); + uint32_t fee = 0, salary = 0; + modern::market_value(g, int(range.first) + s, 0, percent, fee, salary, 1, 0, rand); + fee = fee / 10000 * 10000; + post_composed(g, m, message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer3) + format_amount(g, int32_t(fee)) + "."); + add32(r, rec + 0x314, int32_t(fee)); // MonthRuntimeField9: the balance, not booked + if (!game) { + report.fail("month change: a player retires (MonthChange) without the game generator"); + return; + } + if (!modern::release_player(g, int(range.first) + s, *game, rand, report)) return; + goto next_player; + } + } + // the value history of the month + uint32_t fee = 0, salary = 0; + modern::market_value(g, int(range.first) + s, 0, 100, fee, salary, 0, 0, rand); + const size_t h = b + size_t(month); + g.tactics.at(h + 0x19) = uint8_t(std::min(fee / 8000, 0xff)); + const uint32_t w = g.players.at(size_t(player)).w35c; + g.tactics.at(h + 0x25) = uint8_t((((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) * 3 >> 1) * 0xff) / 300); + g.tactics.at(h + 0x31) = uint8_t(std::min(((w & 0x7F) * 0x8c) / 0x5a, 0xff)); + } + for (int s = 0; s < 24; s++) g.tactics.at(board(s) + 0xb) &= 0x7F; +} + +// MonthChange2: share prices grow by 2.5 %, dividends, loans between the managers. +void shares_and_loans(ModernState& g) { + StaticMemory& mem = g.memory; + std::vector& r = g.manager_records; + static const int kShareFactor[6] = {15, 18, 21, 24, 27, 30}; // MonthRuntimeField10 + const int managers = int(g.manager_teams.size()); + for (int k = 0; k < 6; k++) { + const uint32_t at = ::bmh::layout::FundBlock + uint32_t(k) * 0x1c; + uint32_t price = mem.u32(at); + price += ((price / 10000) * 0x19 / 10) * 10; + mem.set32(at, price); + // (a bug of the original: only the last manager's dividend is kept and it is booked + // for the manager after the last one) + int32_t dividend = 0; + for (int m = 0; m < managers; m++) + dividend = int32_t(mem.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c) * + ((price * uint32_t(kShareFactor[k])) / 10000)); + modern::book_money(g, managers, -dividend, true); + add32(r, size_t(managers) * kRecord + 0x870, dividend); + } + for (int m = 0; m < managers; m++) + for (int l = 0; l <= managers; l++) { + const uint32_t e = ::bmh::layout::Loans + uint32_t(l) * 0x18 + uint32_t(m) * 0x78; + const int32_t rate = int32_t(mem.u32(e + 8)); + if (rate == 0) continue; + modern::book_money(g, m, rate, true); + add32(r, size_t(m) * kRecord + 0x89c, rate); + if (l != 0) { + add32(r, size_t(l - 1) * kRecord + 0x870, rate); + modern::book_money(g, l - 1, -rate, true); + } + mem.set32(e + 0x14, mem.u32(e + 0x14) + uint32_t(rate)); + mem.set32(e + 0x10, mem.u32(e + 0x10) + 1); + if (int32_t(mem.u32(e + 0xc)) <= int32_t(mem.u32(e + 0x10))) + for (uint32_t i = 0; i < 0x18; i++) mem.set8(e + i, 0); + } +} + +} // namespace + +bool list_transfer_player(ModernState& g, int slot, WatcomRandom& rand, MinuteReport& report) { + return list_player(g, slot, rand, report); +} + +void new_transfer_list_entries(ModernState& g, WatcomRandom& rand, MinuteReport& report) { new_list_entries(g, rand, report); } + +void market_value(const ModernState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years, + int extra, WatcomRandom& rand) { + if (years > 4) years = 4; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const Player& p = g.players.at(size_t(player)); + int age = int((p.w364 >> 21) & 0x1F) + 1; // local_24 + if (age > 0x14) age = 0x14; + const int position = int(p.w364 & 3); + uint16_t value[2] = {uint16_t((p.w35c >> 7) & 0x7F), uint16_t((p.w35c >> 14) & 0x7F)}; // technique, condition + uint8_t growth = 100; // local_14 + if (age > 10) growth = uint8_t(age * -10 - 0x38); + for (int k = 0; k < 2; k++) + for (int s = 0; s < years - 1; s++) + value[k] = uint16_t((uint32_t(growth) * kDevelopment[int16_t(value[k]) / 10]) / 100 + value[k]); + const int ad = std::abs(0xb - age) & 0xFF; + int points = ((int16_t(value[0]) + int16_t(value[1])) * 5) / 2 + 0x96 - ad * 2; // local_2c + points = std::clamp(points, 0xc, 0x26c); + if (points > 500) points += points < 600 ? kDevelopment[10 + (points - 500) / 10] : 100; + points = (((points >> 2) + 1) * points * ((points >> 3) + 100)) / 10; + int16_t factor = int16_t(((p.w364 >> 26) & 0x3F) >> 2); // experience + if (position == 0) { + factor = int16_t(factor + 0x6e); + } else { + const int16_t skill = int16_t((int((p.w364 >> 10) & 0x3F) * 3 + int((p.w368 >> 7) & 0x3F)) >> 1); + const int t = (position * skill) / 3; + factor = int16_t(factor + 100 + (int16_t(t) >> 1)); + } + fee = uint32_t((percent * ((factor * points) / 100)) / 100); + if (fee < 50000) fee = uint32_t(rand.range(50000, 80000)); + salary = fee / 0x28; + // (local_24 holds 11 - age by now, the variable of the age difference above: younger + // players ask for more per extra year, older ones for less) + salary = ((uint32_t(extra * (0xb - age) + 100) * salary) / 10000) * 100; + if (loan == 1) fee >>= 2; + // BMH_MARKET_TRACE=1: the factors of one valuation (diagnosis of #40; no state, no draws) + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[market_value player %d (%s) pos %d age_raw %d TE %d KO %d -> points %d factor %d percent %d years %d extra %d: fee %u salary %u]\n", + player, g.player_name(player).c_str(), position, age, int((p.w35c >> 7) & 0x7F), int((p.w35c >> 14) & 0x7F), + points, int(factor), percent, years, extra, fee, salary); +} + +std::array contract_demands(ModernState& g, int manager, int row, bool from_desk, WatcomRandom& rand) { + const SquadRange range = squad_range(g.manager_teams.at(size_t(manager))); + const int slot = int(range.first) + row; + const size_t b = size_t(manager) * kBoard + size_t(row) * kBoardSlot; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const int age = int((g.players.at(size_t(player)).w364 >> 21) & 0x1F) + 1; // local_24 + // Difficulty (Range3 always returns 1, so the level is used) + const int percent = g.level + 100; + std::array demand{}; + for (int k = 0; k < 4; k++) { + // per year beyond the current contract the salary changes by 11 - age percent + const int extra = int8_t(uint8_t(k - (g.tactics.at(b + 0xc) + 6) / 0xc + 1)); + uint32_t fee = 0, salary = 0; + modern::market_value(g, slot, 0, percent, fee, salary, k + 1, extra, rand); + salary = (g.tactics.at(b + 0xd) * salary) / 100; // his mood + const bool refuses = age + k >= 0x24 || (g.tactics.at(b + 0xb) & 0x60); + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[contract_demands player %d years %d: mood +0x0d %d, flags +0x0b %02x, refuses %d -> %u]\n", + player, k + 1, int(g.tactics.at(b + 0xd)), int(g.tactics.at(b + 0xb)), int(refuses), salary); + demand[size_t(k)] = refuses && from_desk ? 0xFFFFFFFFu : salary; + } + return demand; +} + +bool contract_offer(ModernState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request, + bool screen_row, WatcomRandom& rand, const std::array* proposed_bonuses) { + const int team = g.manager_teams.at(size_t(manager)); + const SquadRange range = squad_range(team); + const int slot = int(range.first) + row; + const size_t b = size_t(manager) * kBoard + size_t(row) * kBoardSlot; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const size_t bonus_at = b + 0x12; + std::array current_bonuses{}; + for (size_t i = 0; i < current_bonuses.size(); ++i) { + current_bonuses[i] = g.tactics.at(bonus_at + i); + if (proposed_bonuses && (*proposed_bonuses)[i] > (i < 3 ? 20 : 200)) return false; + } + // the longer he is at the club (+0x11, months), the less he insists + int loyalty = g.tactics.at(b + 0x11) / rand.range(8, 0xc); // local_3c + if (int16_t(loyalty) > 6) loyalty = 6; + // the offer counts with 80 % of the bonus he can expect (ContractOffer with the fitness + // correction on a copy of his board row whose salary is the offer: its +0x50 is the + // offer variable local_f0 that follows the copy on the stack) + std::array buf; + const int predicted = modern::table_prediction(g, team, 4, buf); + const int rank = predicted == 0 ? 0xB : predicted + 1; + uint8_t saved[4]; + std::copy(g.tactics.begin() + long(b + 0x50), g.tactics.begin() + long(b + 0x54), saved); + for (int i = 0; i < 4; i++) g.tactics.at(b + 0x50 + size_t(i)) = uint8_t(offer >> (8 * i)); + if (proposed_bonuses) + std::copy(proposed_bonuses->begin(), proposed_bonuses->end(), g.tactics.begin() + long(bonus_at)); + const uint32_t bonus = modern::expected_bonus(g, manager, rank, row, player, true); + std::copy(saved, saved + 4, g.tactics.begin() + long(b + 0x50)); + if (proposed_bonuses) + std::copy(current_bonuses.begin(), current_bonuses.end(), g.tactics.begin() + long(bonus_at)); + const uint32_t worth = offer + (bonus * 0x50) / 100; // uVar12 + if (std::getenv("BMH_TRACE")) + std::printf(" [offer %u: loyalty %d, rank %d, bonus %u, worth %u, demand %u]\n", offer, loyalty, rank, bonus, worth, + demand); + // what he wants: W(80, 100) - 2 x loyalty percent of his demand (a request of his own: + // the whole demand) + const uint32_t wanted = (request ? 100u : uint32_t(rand.range(0x50, 100) - 2 * int16_t(loyalty))) * demand; + if (std::getenv("BMH_TRACE")) std::printf(" [wanted %u / 100]\n", wanted); + if ((offer * 100u) / demand < 0x3d || worth < wanted / 100) { + // "Der Spieler lehnt ab" (CareerSession_Reject_TextPointer6, a message box): he is offended (+0x4f bit 7) + // and in a worse mood + g.tactics.at(b + 0x4f) |= 0x80; + if (g.tactics.at(b + 0xd) < 0xfb) g.tactics.at(b + 0xd) = uint8_t(g.tactics.at(b + 0xd) + 5); + if (screen_row) g.tactics.at(b + 0xb) |= 0x40; // he will not talk again + return false; + } + // accepted (CareerSession_Reject_TextPointer5): the new salary and term; his mood is what the offer is worth + // against his market salary for that term + for (int i = 0; i < 4; i++) g.tactics.at(b + 0x50 + size_t(i)) = uint8_t(offer >> (8 * i)); + g.tactics.at(b + 0xc) = uint8_t((column + 1) * 0xc); + uint32_t fee = 0, salary = 0; + modern::market_value(g, slot, 0, 100, fee, salary, column, 0, rand); + g.tactics.at(b + 0xd) = uint8_t(std::clamp((worth * 100) / salary, 100, 0xff)); + if (proposed_bonuses) + std::copy(proposed_bonuses->begin(), proposed_bonuses->end(), g.tactics.begin() + long(bonus_at)); + return true; +} + +bool contract_bonuses(ModernState& g, int manager, int row, const std::array& rates) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return false; + const int team = g.manager_teams[size_t(manager)]; + if (team == no_team()) return false; + const SquadRange range = squad_range(team); + if (row < -1 || (row >= 0 && size_t(row) >= range.count) || range.first + range.count > g.squad_slots.size()) + return false; + for (size_t i = 0; i < rates.size(); ++i) + if (rates[i] > (i < 3 ? 20 : 200)) return false; + const size_t board = size_t(manager) * 0x840; + if (board + size_t(range.count) * 0x58 > g.tactics.size()) return false; + bool changed = false; + const size_t first_row = row < 0 ? 0 : size_t(row); + const size_t end_row = row < 0 ? range.count : size_t(row) + 1; + // The original checks the whole selected scope before committing any of it. + for (size_t r = first_row; r < end_row; ++r) { + const int player = g.squad_slots.at(range.first + r) & 0x0fff; + if (player == 0x0fff) continue; + if (size_t(player) >= g.players.size()) return false; + const size_t b = board + r * 0x58; + for (size_t i = 0; i < rates.size(); ++i) { + const uint8_t old = g.tactics.at(b + 0x12 + i); + changed |= rates[i] > old; + } + } + for (size_t i = 0; i < rates.size(); ++i) { + bool found = false; + uint8_t minimum = 0xff; + for (size_t r = first_row; r < end_row; ++r) { + if ((g.squad_slots.at(range.first + r) & 0x0fff) == 0x0fff) continue; + found = true; + minimum = std::min(minimum, g.tactics.at(board + r * 0x58 + 0x12 + i)); + } + if (found && rates[i] < minimum) return false; + } + if (!changed) return false; + for (size_t r = first_row; r < end_row; ++r) { + const int player = g.squad_slots.at(range.first + r) & 0x0fff; + if (player == 0x0fff) continue; + const size_t b = board + r * 0x58; + for (size_t i = 0; i < rates.size(); ++i) + if (rates[i] > g.tactics.at(b + 0x12 + i)) g.tactics.at(b + 0x12 + i) = rates[i]; + } + return true; +} + +ContractInsuranceResult contract_insurance(ModernState& g, int manager, int row, int insurance_type, + uint8_t months) { + ContractInsuranceResult out; + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || insurance_type < 0 || insurance_type >= 4 || + months < 1 || months > 60) return out; + const int team = g.manager_teams[size_t(manager)]; + if (team == no_team()) return out; + const SquadRange range = squad_range(team); + if (row < 0 || size_t(row) >= range.count || range.first + size_t(row) >= g.squad_slots.size()) return out; + const int player = g.squad_slots.at(range.first + size_t(row)) & 0x0fff; + if (player == 0x0fff || size_t(player) >= g.players.size()) return out; + const size_t b = size_t(manager) * 0x840 + size_t(row) * 0x58; + if (b + 0x54 > g.tactics.size() || (g.tactics.at(b + 0x0b) & 0x60) != 0 || + g.tactics.at(b + 0x43) != 0 || (g.players[size_t(player)].w35c >> 27) != 0) return out; + const uint32_t salary = uint32_t(g.tactics.at(b + 0x50)) | + (uint32_t(g.tactics.at(b + 0x51)) << 8) | (uint32_t(g.tactics.at(b + 0x52)) << 16) | + (uint32_t(g.tactics.at(b + 0x53)) << 24); + const uint32_t fee = (((uint32_t(insurance_type * 10 + 10) * salary) / 1000) * 10); + const uint16_t old_fee = uint16_t(g.tactics.at(b + 0x4e) | (uint16_t(g.tactics.at(b + 0x4f)) << 8)); + g.tactics.at(b + 0x43) = uint8_t(months | uint8_t(insurance_type << 6)); + // The original clears the old amount but preserves the high flag before adding the + // term's monthly premium into the 16-bit field. + const uint16_t base = uint16_t(old_fee & 0x8000); + const uint16_t stored = uint16_t(base + uint16_t(fee)); + g.tactics.at(b + 0x4e) = uint8_t(stored); + g.tactics.at(b + 0x4f) = uint8_t(stored >> 8); + out.accepted = true; + out.monthly_fee = uint16_t(fee); + return out; +} + +void search_profile_news(ModernState& g, int manager, uint32_t list, int player) { + const StaticMemory& mem = g.memory; + const size_t rec = size_t(manager) * kRecord; + auto b = [&](size_t off) { return int(g.manager_records.at(rec + off)); }; + const int team = g.manager_teams.at(size_t(manager)); + player &= 0xFFF; + if (team == no_team() || (mem.u16(list + 8) & 0x7FFF) == team || (b(0x1f6) & 0x40)) return; + const uint32_t w364 = g.players.at(size_t(player)).w364, w35c = g.players.at(size_t(player)).w35c; + // position wanted (or none selected) and age within the range + if (b(0x1f6 + (w364 & 3)) == 0 && b(0x1f9) + b(0x1f8) + b(0x1f7) + b(0x1f6) != 0) return; + const int age = int((w364 >> 21) & 0x1F); + if (age < b(0x1fa) || age > b(0x1fb)) return; + // strength by the selected attributes (condition, technique, form; none = all three) + int8_t selected = int8_t(b(0x200) + b(0x1fe) + b(0x1ff)); + if (selected == 0) selected = 3; + int sum = 0, n = 0, form = 0; + if (b(0x1fe) != 0 || selected == 3) sum = int((w35c >> 14) & 0x7F), n = 1; + if (b(0x1ff) != 0 || selected == 3) sum = int16_t(sum) + int((w35c >> 7) & 0x7F), n++; + if (b(0x200) != 0 || selected == 3) form = int(w35c & 0x7F); + int16_t strength; + if (n == 0) { + strength = int16_t((form - 0x23) * 3 + 10); + } else { + strength = int16_t(uint32_t(sum) / uint32_t(n)); + if (form != 0) strength = int16_t(uint32_t(strength * int16_t((int16_t(form) >> 3) + 0x5e)) / 100); + } + if (strength < b(0x1fc) || strength > b(0x1fd)) return; + // left / right foot and wing preferences (w35c bits 21-23 and 24-26) + const int lane = int((w35c >> 21) & 7), foot = int((w35c >> 24) & 7); + bool low_foot = b(0x201) || b(0x203), high_foot = b(0x202) || b(0x204); + if (low_foot && high_foot) low_foot = high_foot = false; + bool low_lane = b(0x201) || b(0x202), high_lane = b(0x203) || b(0x204); + if (low_lane && high_lane) low_lane = high_lane = false; + if ((low_lane && lane >= 3) || (high_lane && lane <= 4) || (low_foot && foot >= 3) || (high_foot && foot <= 4)) return; + // the price class (asking price 70..130 %) against the classes wanted + int8_t price_class = int8_t((mem.u8(list + 0x54) - 0x46) / 0x14); + price_class = std::clamp(price_class, 0, 2); + const int8_t classes = int8_t(b(0x207) + b(0x205) + b(0x206)); + int highest = 2; + while (highest >= 0 && b(0x205 + size_t(highest)) == 0) highest--; + if (classes == 0 || price_class <= highest) + post_composed(g, manager, message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer2)); +} + +void month_change(ModernState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game) { + StaticMemory& mem = g.memory; + std::vector& r = g.manager_records; + const int managers = int(g.manager_teams.size()); + // 1. advertising contracts + turn_step = "month_change: advertising"; + if (mem.u8(::bmh::layout::GameMode) != 1 && mem.u8(::bmh::layout::CareerDuration) != 1) + for (int m = 0; m < managers; m++) + for (int k = 0; k < 0x12; k++) { + const size_t c = size_t(m) * kRecord + 0xa34 + size_t(k) * 0xc; + if (r.at(c + 5) == 0 && (r.at(c + 6) & 0x80)) { + wr32(r, c, 0); + r.at(c + 6) = 0; + } + if (r.at(c + 5) != 0 && --r.at(c + 5) == 0) { + if ((r.at(c + 6) & 0x7F) == 0) wr32(r, c, 0); + else turn_step = "month_change: advertising text", post_text(g, m, text_id(::bmh::layout::Month_MonthChange_TextPointer)); // the contract can be renewed + } + } + // 2. new players on the transfer list + turn_step = "month_change: new list entries"; + new_list_entries(g, rand, report); + if (report.unsupported) return; + // 3. loans + turn_step = "month_change: loans"; + return_loans(g, rand, game, report); + if (report.unsupported) return; + // 4. the human managers + turn_step = "month_change: managers"; + for (int m = 0; m < managers && !report.unsupported; m++) { + const size_t rec = size_t(m) * kRecord; + for (int k = 0; k < 3; k++) + modern::rate_manager(g, m, uint8_t(int8_t(int32_t(mem.u32(::bmh::layout::Month_MonthChange_RuntimeField + uint32_t(k) * 4 + uint32_t(m) * 0x24)) / 0x96)), + k + 1); + const int32_t expenses = monthly_expenses(g, m); + const int32_t income = monthly_income(g, m); + modern::book_money(g, m, expenses - income, true); + for (int k = 0; k < 2; k++) + modern::rate_manager(g, m, uint8_t(int8_t(((rd32(r, rec + 0x854 + size_t(k) * 4) / 5000) * 200) / 7)), k + 4); + board_month(g, m, rand, report, game); + } + if (report.unsupported) return; + // 5. shares and loans + turn_step = "month_change: shares"; + shares_and_loans(g); +} + +} // namespace bmh::modern diff --git a/src/modern/game/month.hpp b/src/modern/game/month.hpp new file mode 100644 index 0000000..21c8809 --- /dev/null +++ b/src/modern/game/month.hpp @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/month.hpp" +// The month change (DayStepRest2), run by the day step (DayStepRest) of the first day of +// a month in the full game (CompetitionSelection bit 0), after the training / weekly processing: +// +// 1. advertising contracts of the human managers count down (record +0xa34, 18 x 0xC) +// 2. new players on the transfer list (CareerFirstSteps): free agents of the pool and players +// the computer clubs want to sell +// 3. loaned players whose time is up return to their clubs (table Career_RemoveJoinLoans_RuntimeField) +// 4. per human manager: the monthly ratings (ManagerMatchRecord2), expenses minus income, and the +// monthly bookkeeping of every squad player on the tactics board (contract months, +// mood, value history, retirement wishes) +// 5. share prices grow, dividends and loans between managers are booked (MonthChange2) +// +// Monthly bookkeeping uses Watcom draws; player moves also require the game RNG. +// Human decisions use caller-supplied contract/loan presenters. Missing context +// and invalid state report through MinuteReport, rather than guessing a decision. + +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// `game` is needed when a player leaves at the end of his contract (MonthChange). +void month_change(ModernState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr); + +// CareerFirstSteps: new players on the transfer list (part of the month change; also at the +// start of a season). +void new_transfer_list_entries(ModernState& g, WatcomRandom& rand, MinuteReport& report); + +// AddToSquad(slot, loan, percent, &fee, &salary, years, extra): market value (fee) and +// salary of the player in an absolute squad slot, from strength, age, position and +// experience; `percent` scales the fee, `years` - 1 steps of expected development raise +// it, `extra` * (11 - age) percent change the salary. A fee below 50000 is replaced by W(50000, +// 80000); a loan (1) costs a quarter. +void market_value(const ModernState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years, + int extra, WatcomRandom& rand); + +// ContractBonuses, the salary page of the contract talks (contracts screen InstallDefaultHooks): the +// four demands for 1-4 years when the talks open, AddToSquad with the level + 100 percent +// and the salary rise for the years beyond the current contract, times the player's mood +// (+0xd) / 100. Opened from the desk (`from_desk`, param_5 0x80) a player of 36 or more +// at the end of the term, or one flagged 0x20 / 0x40, wants no contract (no-contract sentinel). +std::array contract_demands(ModernState& g, int manager, int row, bool from_desk, WatcomRandom& rand); + +// ContractBonuses "OK" with an offer for `column` + 1 years against that column's demand: W(8, 12) +// (loyalty from the months at the club, +0x11) and - unless the player asked himself +// (`request`, param_5 0x40) - W(80, 100). The offer plus 80 % of the expected bonus +// (ContractOffer) must reach that percentage of the demand, and the offer itself 61 %. +// Accepted: salary, term and mood (+0x50, +0xc, +0xd) change, AddToSquad for the term. +// Rejected: the player is offended (+0x4f bit 7, mood + 5); for the row whose contract +// ended (`screen_row`) he will not talk again (+0xb bit 6). Returns whether he accepted. +bool contract_offer(ModernState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request, + bool screen_row, WatcomRandom& rand, + const std::array* proposed_bonuses = nullptr); + +// ContractBonuses "Prämien" page. `row == -1` edits the squad's shared proposal; each +// stored row is raised to the requested value. A bonus-only submission is accepted only +// when it does not lower any player's current rate, and must change at least one rate. +bool contract_bonuses(ModernState& g, int manager, int row, const std::array& rates); + + +// ContractBonuses insurance button: one-time per player, duration 1..60 months, and insurance +// category bound to the selected 1..4 year term. This action consumes no RNG. +ContractInsuranceResult contract_insurance(ModernState& g, int manager, int row, int insurance_type, + uint8_t months); + +// SearchProfileNews(manager, list entry, player, 1): tells a human manager about a new player on +// the transfer list that matches his search profile (record +0x1f6 .. +0x207). +void search_profile_news(ModernState& g, int manager, uint32_t list, int player); + +// Put an existing squad slot on the shared transfer list (human desk action). +bool list_transfer_player(ModernState& g, int slot, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh::modern diff --git a/src/modern/game/national.cpp b/src/modern/game/national.cpp new file mode 100644 index 0000000..783be3f --- /dev/null +++ b/src/modern/game/national.cpp @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/national.hpp" + +#include +#include + +#include "game/lineup.hpp" +#include "game/match_engine.hpp" +#include "modern/game/month.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kManagerRecord = 0xb0c; +constexpr size_t kBoard = 0x840; // one manager's tactics board (24 x 0x58) +constexpr size_t kBoardSlot = 0x58; +constexpr uint32_t kDesktops = ::bmh::layout::Desktops; // desktop layouts, 0x360 per manager slot +constexpr size_t kDesktop = 0x360; +constexpr uint8_t kNominated[4] = {3, 5, 7, 5}; // NationalRuntimeField: keepers, defence, midfield, attack + +// the manager's team (record +0x290) as the port caches it +void refresh_manager_teams(ModernState& g) { + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const size_t at = m * kManagerRecord + 0x290; + g.manager_teams[m] = int16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); + } +} + +// a byte of the original's static data, created on first use (not every one is saved) +uint8_t& static_byte(ModernState& g, uint32_t address) { + if (!g.memory.has(address)) g.memory.add_block(address, 1); + return g.memory.at(address); +} + +} // namespace + +void swap_manager_slots(ModernState& g, int a, int b) { + if (a == b) return; + std::swap_ranges(g.manager_records.begin() + long(size_t(a) * kManagerRecord), + g.manager_records.begin() + long(size_t(a + 1) * kManagerRecord), + g.manager_records.begin() + long(size_t(b) * kManagerRecord)); + std::swap_ranges(g.tactics.begin() + long(size_t(a) * kBoard), g.tactics.begin() + long(size_t(a + 1) * kBoard), + g.tactics.begin() + long(size_t(b) * kBoard)); + if (g.memory.has(kDesktops)) + for (size_t i = 0; i < kDesktop; i++) { + const uint32_t pa = kDesktops + uint32_t(size_t(a) * kDesktop + i); + const uint32_t pb = kDesktops + uint32_t(size_t(b) * kDesktop + i); + const uint8_t t = g.memory.u8(pa); + g.memory.set8(pa, g.memory.u8(pb)); + g.memory.set8(pb, t); + } + refresh_manager_teams(g); +} + +int add_to_squad(ModernState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand) { + // FirstFreeSlotSquad(start, 0x18): the first free slot of the squad + int slot = -1; + for (int s = squad_start; s < squad_start + 24; s++) + if (g.squad_slots.at(size_t(s)) == kEmptySlot) { + slot = s; + break; + } + if (slot < 0) return -1; // (the original shows the message PendingOffer_FormatError_ExecutableField) + g.squad_slots.at(size_t(slot)) = g.squad_slots.at(size_t(from_slot)); + modern::new_board_entry(g, manager, slot - squad_start, slot, rand); + return slot; +} + +void new_board_entry(ModernState& g, int manager, int index, int slot, WatcomRandom& rand) { + uint8_t* e = &g.tactics.at(size_t(manager) * kBoard + size_t(index) * kBoardSlot); + std::memset(e + 7, 0, 3); + std::memset(e + 0x19, 0, 0x24); + e[10] = 2; + for (int k = 0; k < 4; k++) e[2 + k] = index < 2 ? 1 : uint8_t(rand.range(2, 0x27)); + e[0x3f] = 0xff; + e[0x46] = 0xff, e[0x47] = 0x0f; // u16 0xfff + e[0x44] = 0xff, e[0x45] = 0x0f; + e[0] = 10; + e[1] = 4; + e[0xe] = 0x59; + e[0xf] = uint8_t(rand.range(0x28, 0x3c)); + e[0x11] = 0; + e[0x43] = 0; + e[0x4e] = 0, e[0x4f] = 0; + e[0x3d] = index < 11 ? 0 : index <= 0x10 ? 1 : 2; + e[0xc] = 0x18; + // AddToSquad(slot, 0, W(95, 105), &fee, &salary (+0x50), 2 years, no extra) + const int percent = rand.range(0x5f, 0x69); + uint32_t fee = 0, salary = 0; + modern::market_value(g, slot, 0, percent, fee, salary, 2, 0, rand); + for (int k = 0; k < 4; k++) e[0x50 + k] = uint8_t(salary >> (8 * k)); + std::memset(e + 0x12, 0, 7); +} + +bool national_team_day(ModernState& g, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + const SquadRange national = squad_range(no_team()); + // NationalSquadEmptied: the national squad is emptied + for (size_t s = national.first; s < national.first + national.count; s++) g.squad_slots.at(s) = kEmptySlot; + + // SwapManagerSlots2 (called whether or not a take-over is already in effect): a manager flagged + // as Bundestrainer takes the national team over in slot 0. ActiveManager is what the day + // step's manager loop (DayStepRest) leaves: the number of managers. + (void)mem; + (void)report; + modern::national_coach_take_over(g, int(g.manager_teams.size()), uint16_t(g.date - g.season_start)); + const uint8_t coach = static_byte(g, ::bmh::layout::CoachActive); // CoachActive + if (coach == 0) modern::swap_manager_slots(g, 4, 0); // slot 0 becomes the spare slot 4 + + // the strongest available German players per position (NationalRuntimeField of each), kept in + // ascending order: a stronger one pushes the weakest out + int16_t best[4][7] = {}, slots[4][7] = {}; + for (size_t s = 0; s < transfer_list_slot(); s++) { + const int id = g.squad_slots.at(s) & 0xfff; + if (id == 0xfff) continue; + const Player& p = g.players.at(size_t(id)); + const bool fit = (p.w35c >> 27) == 0 || ((p.w364 >> 16) & 0x1f) == 0; + if (!fit || modern::nationality(g, id) != 0) continue; + const int pos = int(p.w364 & 3); + int16_t strength = int16_t(p.strength(false)); // Strength(w35c, 0) + if (pos > 1) strength = int16_t(strength + ((p.w364 >> 2) & 0x3f) + (((p.w368 >> 18) & 0x3f) >> 1)); + if (s > 0x86f) strength = int16_t((strength * 0xb) / 10); // (the clubs from slot 0x870 on) + int i = 0; + // NationalTeamDay caps the insertion index at the positional quota. Guard + // before indexing: the full seven-player row has no C++ eighth element. + while (i < kNominated[pos] && strength > best[pos][i]) i++; + if (i == 0) continue; + const int j = i - 1; + // Int16T: entries 1..j move down one place, the new one takes place j + for (int k = 0; k < j; k++) best[pos][k] = best[pos][k + 1], slots[pos][k] = slots[pos][k + 1]; + best[pos][j] = strength; + slots[pos][j] = int16_t(s); + } + // PendingOfferAnswer for each, weakest first, into the board of slot 0 + for (int pos = 0; pos < 4; pos++) + for (int k = 0; k < kNominated[pos]; k++) modern::add_to_squad(g, 0, slots[pos][k], int(national.first), rand); + // Int2(0x165, 0xe4) with manager 0's option byte (ManagerAutomation) at 1 + const uint8_t option = g.manager_options.at(0); + g.manager_options.at(0) = 1; + try { + auto_lineup(g, no_team(), 0xe4); + } catch (const std::exception& ex) { + report.fail(std::string("national team line-up: ") + ex.what()); + } + if (coach == 0) modern::swap_manager_slots(g, 4, 0); + g.manager_options.at(0) = option; + return coach != 0; // (with a Bundestrainer his desk follows: AdvanceTurn's local_28 = 4) +} + + +// --------------------------------------------------------------------------------------- +// The Bundestrainer (national coach). A manager flagged in his record (+0x21c), every +// manager in the world game without leagues (CompetitionSelection == 2) and the only manager of a +// one-manager game coaches the national team on international days: SwapManagerSlots2 moves his +// slot 0 to the spare slot 4 and puts the national team's record (kept in slot 4 between the +// international periods) into slot 0; NationalCoachHandBack swaps them back. CoachActive tells +// whether the swap is in effect, OriginalManagerCount keeps the number of managers meanwhile. + +namespace { + +void set_manager_count(ModernState& g, int managers) { + static_byte(g, ::bmh::layout::ManagerCount) = uint8_t(managers); // ManagerCount + g.manager_teams.assign(size_t(managers), 0); // (the typed copy, one entry per manager) +} + +} // namespace + +void national_coach_take_over(ModernState& g, int active_manager, uint16_t source_season_day) { + StaticMemory& mem = g.memory; + int managers = int(g.manager_teams.size()); + static_byte(g, ::bmh::layout::OriginalManagerCount) = uint8_t(managers); // OriginalManagerCount = ManagerCount + static_byte(g, ::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3) = uint8_t(active_manager); // ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager + // DaysIntoSeason == 1 (the first day after the saved season origin): the national team's + // mood byte loses its top bit before coach eligibility is checked. + const bool first_day = source_season_day == 1; + if (first_day) g.team_morale.at(no_team()) &= 0x7f; + const bool world_only = mem.u32(::bmh::layout::CompetitionSelection) == 2; + // (the loop bound is ManagerCount itself, which a take-over sets to 1) + for (int m = 0; m < managers; m++) { + uint8_t* rec = &g.manager_records.at(size_t(m) * kManagerRecord); + if (rec[0x21c] == 0 && !world_only && managers != 1) continue; + // the national team's record (slot 4) gets the coach's portrait (+0x221) and name + // (+0xa8, StrcpySoHallReplacesItsCurrentTournament = strcpy) + uint8_t* spare = &g.manager_records.at(4 * kManagerRecord); + spare[0x221] = rec[0x221]; + for (size_t i = 0;; i++) { + spare[0xa8 + i] = rec[0xa8 + i]; + if (rec[0xa8 + i] == 0) break; + } + managers = 1; + set_manager_count(g, 1); + modern::swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0) + uint8_t* coach = &g.manager_records.at(0); + coach[0x290] = uint8_t(no_team() & 0xff), coach[0x291] = uint8_t(no_team() >> 8); // CupDraw_FormatError_RuntimeField2 = 0x165 + coach[0x218] = g.manager_records.at(4 * kManagerRecord + 0x218); // NationalRuntimeField2 = NationalRuntimeField3 + g.manager_teams.at(0) = no_team(); + auto_lineup(g, no_team(), 0xe4); // Int2(0x165, 0xe4) + static_byte(g, ::bmh::layout::CoachActive) = 1; + if (first_day) g.team_morale.at(no_team()) |= 0x80; + } +} + +void national_coach_hand_back(ModernState& g) { + if (static_byte(g, ::bmh::layout::CoachActive) == 0) return; + const int managers = static_byte(g, ::bmh::layout::OriginalManagerCount); + set_manager_count(g, managers); // ManagerCount = OriginalManagerCount + modern::swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0) (refreshes the typed teams) + static_byte(g, ::bmh::layout::CoachActive) = 0; +} + +bool national_coach_active(const ModernState& g) { return !g.manager_teams.empty() && g.manager_teams[0] == no_team(); } + +void national_coach_after_load(ModernState& g) { + // NationalCoachAfterLoad's end, loading as well as saving: the take-over is done again + if (g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0) + modern::national_coach_take_over(g, g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0, + uint16_t(g.date - g.season_start)); +} + +ModernState national_coach_save_form(const ModernState& g) { + // NationalCoachAfterLoad's start: the slots swapped back, CoachActive kept at 1 + ModernState s = g; + if (s.memory.has(::bmh::layout::CoachActive) && s.memory.u8(::bmh::layout::CoachActive) != 0) { + modern::national_coach_hand_back(s); + s.memory.set8(::bmh::layout::CoachActive, 1); + } + return s; +} + +} // namespace bmh::modern diff --git a/src/modern/game/national.hpp b/src/modern/game/national.hpp new file mode 100644 index 0000000..0bfd0d3 --- /dev/null +++ b/src/modern/game/national.hpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/national.hpp" +// The national team (BMH.exe V2.24 + supported rule profile patch), team id 0x165 (no_team()), squad slots +// 0xc00-0xc17 (LargeSquadClubCount). +// +// With the world game on (CompetitionSelection bit 1) the calendar holds national team days (entry +// 0x4006, DayCompetitions -> national-only flag). On such a day AdvanceTurn calls NationalTeamDay, which +// nominates the squad: the manager slots are swapped so that slot 0 is a spare one +// (SwapManagerSlots(4, 0); a Bundestrainer instead takes slot 0 over with the national team, +// SwapManagerSlots2), the 3 goalkeepers, 5 defenders, 7 midfielders and 5 forwards +// (NationalRuntimeField) of the highest strength among the available German players of all clubs +// join the national squad with a fresh tactics board entry (PendingOfferAnswer), the national team +// gets its line-up (Int2(0x165, 0xe4)) and the slots are swapped back. Without a +// Bundestrainer the day then prepares an empty matchday (no desk, no match). + +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + + +// SwapManagerSlots(a, b): manager slots a and b change places - the manager records (0xb0c +// bytes), the tactics boards (0x840) and the desktop layouts (block Desktops, 0x360). +void swap_manager_slots(ModernState& g, int a, int b); + +// PendingOfferAnswer(manager, from_slot, -1, squad_start): the player of the absolute squad slot +// `from_slot` gets the first free slot of the squad starting at `squad_start` (24 slots; +// the slot value is copied with its flags) and a fresh entry on the tactics board of +// manager slot `manager`: neutral settings, familiarity W(40, 60), the four attribute +// bytes W(2, 39) each (1 for the first two places) and the salary of a 2-year contract +// at W(95, 105) percent (AddToSquad). Returns the new absolute slot, -1 if the squad is full. +int add_to_squad(ModernState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand); +// The board part of PendingOfferAnswer (also called with a given place `index`): the entry of +// the player in absolute squad slot `slot` on the tactics board of `manager`. +void new_board_entry(ModernState& g, int manager, int index, int slot, WatcomRandom& rand); + +// NationalTeamDay: the national team day (see above). Returns whether a Bundestrainer manages +// the national team (CoachActive) - then his desk follows (AdvanceTurn: local_28 = 4). +bool national_team_day(ModernState& g, WatcomRandom& rand, MinuteReport& report); + +// The Bundestrainer (national coach), see national.cpp. SwapManagerSlots2: notes the number of +// managers (OriginalManagerCount) and `active_manager` (ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager); a manager +// flagged in his record (+0x21c), every manager in the world game without leagues +// (CompetitionSelection == 2) and the only manager of a one-manager game takes the national team over: +// the national team's record (slot 4) gets his name and portrait, the number of managers +// becomes 1, slots 4 and 0 change places, slot 0 manages team 0x165 and copies +0x218 from +// slot 4, the national team gets its line-up (Int2(0x165, 0xe4)) and +// CoachActive = 1. +// `source_season_day` is the 16-bit value visible in DaysIntoSeason at this exact Source call +// site. It is not always `g.season_day()`: DailyInterest advances the counter before +// quiet-day rest but after rest on the completed-event path. +void national_coach_take_over(ModernState& g, int active_manager, uint16_t source_season_day); +// NationalCoachHandBack: with CoachActive set the slots change places again, the number of managers +// is restored from OriginalManagerCount and CoachActive cleared. +void national_coach_hand_back(ModernState& g); +// CupDraw_FormatError_RuntimeField2 == 0x165: slot 0 manages the national team. +bool national_coach_active(const ModernState& g); +// NationalCoachAfterLoad (saving and loading): the savegame holds the slots swapped back with +// CoachActive still 1; afterwards (and so after loading) SwapManagerSlots2 takes over again. +void national_coach_after_load(ModernState& g); +// The state as NationalCoachAfterLoad writes it (for the savegame writer and comparisons). +ModernState national_coach_save_form(const ModernState& g); + +} // namespace bmh::modern diff --git a/src/modern/game/other_games.cpp b/src/modern/game/other_games.cpp new file mode 100644 index 0000000..fe7085e --- /dev/null +++ b/src/modern/game/other_games.cpp @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/other_games.hpp" + +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "modern/game/cup.hpp" +#include "game/schedule.hpp" + +namespace bmh::modern { +namespace { + +constexpr uint32_t kActiveSelectors = ::bmh::layout::ActiveSelectors; +constexpr uint32_t kSelectorCount = 8; +constexpr size_t kTextCompetitionNames = (::bmh::layout::CupDraw_FormatError_ExecutableField6 - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextCompetitionButtonNames = (::bmh::layout::OtherGames_Layout_ExecutableField - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextRoundHeadings = (::bmh::layout::CupDraw_FormatError_ExecutableField4 - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextGroupRound = (::bmh::layout::Calendar_Information_TextPointer2 - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextGroupCaption = (::bmh::layout::CupDraw_FormatError_ExecutableField5 - ::bmh::layout::TextPointerTable) / 4; + +[[noreturn]] void invalid(const char* why) { throw FormatError(std::string("other games: ") + why); } + +std::string text(const TextDb& texts, size_t index) { + if (index >= texts.strings.size()) invalid("missing Source TEXTD entry"); + return texts.strings[index]; +} + +bool in_descriptor_table(int entry) { return entry >= 0 && entry < kCupEntries; } + +// Bounded port of FindCup's literal scan cursor. On a matching descriptor, its +0x17 link +// wins, else +0x16; a zero link falls back to entry0 in Source. The scan cursor itself advances +// only on a nonmatch and returns the just-followed pointer immediately when the cursor is0. +// Malformed/no-match paths fail closed instead of returning Source's invalid one-past-table ptr. +int resolve_linked_entry(const StaticMemory& memory, int competition, int ordinal) { + if (ordinal < 0 || ordinal >= kCupEntries) invalid("linked occurrence outside Source bounds"); + int cursor = 0, current = 0, remaining = ordinal; + std::vector seen(size_t(kCupEntries) * kCupEntries * kCupEntries, 0); + for (size_t step = 0; step < seen.size(); ++step) { + if (!in_descriptor_table(cursor) || !in_descriptor_table(current)) + invalid("Source linked resolver left descriptor table"); + const size_t key = (size_t(cursor) * kCupEntries + size_t(current)) * kCupEntries + size_t(remaining); + if (seen[key]) invalid("cycle in Source linked resolver"); + seen[key] = 1; + const uint32_t address = modern::cup_entry_address(current); + if (!memory.has(address + 0x19)) invalid("truncated Source descriptor ID"); + if (int16_t(memory.u16(address + 0x18)) == competition) { + if (remaining == 0) return current; + const int parallel = int8_t(memory.u8(address + 0x17)); + const int next = int8_t(memory.u8(address + 0x16)); + if (parallel != 0) current = parallel; + else if (next != 0) current = next; + else invalid("Source linked occurrence reaches its no-link fallback"); + if (!in_descriptor_table(current)) invalid("invalid Source linked descriptor link"); + --remaining; + if (cursor == 0) return current; + } else { + ++cursor; + if (cursor >= kCupEntries) invalid("Source linked resolver cursor wrapped without a match"); + current = cursor; + } + } + invalid("Source linked resolver exceeded bounded traversal"); +} + +std::vector source_linked_pages(const StaticMemory& memory, int selected) { + std::vector pages; + int first = selected; + std::array seen{}; + while (in_descriptor_table(first)) { + if (seen[size_t(first)]) invalid("cycle while locating first Source group selector"); + seen[size_t(first)] = true; + const uint8_t group = memory.u8(modern::cup_entry_address(first) + 0x1e); + if ((group >> 4) == 0) break; + if (first == 0) invalid("Source group selector would walk before descriptor table"); + --first; // InDescriptorTable moves one adjacent descriptor left until group index0. + } + while (true) { + if (!in_descriptor_table(first) || seen[size_t(first)]) { + // The first adjacent scan above marks visited entries; reset its cycle guard before + // following signed previous-stage links. + if (!in_descriptor_table(first)) invalid("invalid Source first group descriptor"); + } + seen[size_t(first)] = true; + const int previous = int8_t(memory.u8(modern::cup_entry_address(first) + 0x15)); + if (previous == -1) break; + if (!in_descriptor_table(previous) || seen[size_t(previous)]) invalid("invalid Source previous-stage link"); + first = previous; + } + // InDescriptorTable suppresses the linked-page selector before enumerating groups when the first + // stage has no +0x16 continuation. + if (memory.u8(modern::cup_entry_address(first) + 0x16) == 0) return pages; + int stage = first; + std::array stage_seen{}; + while (in_descriptor_table(stage)) { + if (stage_seen[size_t(stage)]) invalid("cycle in Source linked-stage selector"); + stage_seen[size_t(stage)] = true; + int group_entry = stage; + const uint8_t count = memory.u8(modern::cup_entry_address(stage) + 0x1e) & 0x0f; + for (int group = 0; group < count; ++group) { + if (!in_descriptor_table(group_entry)) invalid("parallel group left descriptor table"); + const uint32_t address = modern::cup_entry_address(group_entry); + pages.push_back({int(pages.size()), group_entry, int16_t(memory.u16(address + 0x18)), + int(memory.u8(address + 0x1e) >> 4), int(count)}); + const bool has_adjacent = memory.u8(address + 0x17) != 0; + if (group + 1 < count && !has_adjacent) + invalid("parallel group count lacks adjacent Source entry"); + // Source checks +0x17 after every emitted sibling, including the final one; when + // present it advances to the adjacent descriptor before reading its +0x16 stage. + if (has_adjacent) ++group_entry; + } + const int next = int8_t(memory.u8(modern::cup_entry_address(group_entry) + 0x16)); + if (next == 0) break; + if (!in_descriptor_table(next)) invalid("invalid Source next-stage selector link"); + stage = next; + } + return pages; +} + +void validate_team(const ModernState& game, uint16_t team) { + // CupGroupOverviewEffects indexes ClubIdentities directly; this screen has no empty-club fallback. + if (team == 0x0fff) invalid("Source row references the empty-club sentinel"); + if (team >= game.club_ids.size()) invalid("club id outside loaded name table"); +} + +OtherGamesRow make_row(const ModernState& game, int home, int away, uint16_t result, int match) { + if (home < 0 || home > 0xffff || away < 0 || away > 0xffff) invalid("invalid team id"); + const uint16_t h = uint16_t(home), a = uint16_t(away); + validate_team(game, h); + validate_team(game, a); + OtherGamesRow row; + row.home_team = home; + row.away_team = away; + row.home_name = game.club_name(home); + row.away_name = game.club_name(away); + row.source_result = result; + row.played = result != 0xcccc; + if (row.played) { + row.home_goals = (result >> 5) & 0x1f; + row.away_goals = result & 0x1f; + } + row.source_match = match; + return row; +} + +OtherGamesClubMetadata source_metadata(const ModernState& game, int team) { + OtherGamesClubMetadata out; + bool manager_owned = game.manager_of(team) >= 0; + constexpr size_t kNationalOriginalClub = 4 * 0xb0c + 0x290; + if (!manager_owned && !game.manager_teams.empty() && game.manager_teams[0] == no_team() && + game.manager_records.size() >= kNationalOriginalClub + 2) { + const int original_club = int(uint16_t(game.manager_records[kNationalOriginalClub] | + uint16_t(game.manager_records[kNationalOriginalClub + 1]) << 8)); + manager_owned = original_club == team; + } + if (team >= first_foreign_cup() && !manager_owned) { + const size_t at = size_t(team - first_foreign_cup()); + if (at >= game.foreign_strength.size()) invalid("missing Source foreign-strength byte"); + out.foreign_strength = game.foreign_strength[at]; + return out; + } + if (team >= first_foreign_cup() && team != no_team()) + invalid("manager-controlled foreign-club row needs live TeamRating W-generator context"); + constexpr std::array kFlags{0x0f1, 0x0f2, 0x0f4, 0x0f8, 0x0ff}; + for (size_t i = 0; i < kFlags.size(); ++i) + out.averages[i] = team_average(game, team, kFlags[i]).value; + out.has_squad_values = true; + return out; +} + +void attach_source_values(const ModernState& game, OtherGamesRow& row) { + row.home_metadata = source_metadata(game, row.home_team); + row.away_metadata = source_metadata(game, row.away_team); +} + +void add_second_leg_and_winner(OtherGamesRow& row, uint16_t second, bool present, + bool visible, uint8_t flags) { + row.source_second_leg = second; + row.second_leg_array_present = present; + row.second_leg_visible = visible; + if (present) { + // The second fixture is reversed relative to the primary row: its low field belongs + // to the first displayed club and its high field to the second displayed club. + row.second_leg_home_goals = second & 0x1f; + row.second_leg_away_goals = (second >> 5) & 0x1f; + } + if (row.source_result == 0xcccc) return; + int home = row.home_goals; + int away = row.away_goals; + // CupTie reads the second result whenever the descriptor has an array pointer, + // independently of whether its separate detail line is visible or contains 0xcccc. + const uint16_t winner_second = present ? second : 0; + const int home_total = home + (winner_second & 0x1f); + const int away_total = away + ((winner_second >> 5) & 0x1f); + home = home_total; + away = away_total; + if ((flags & 0x10) && home == away && (row.source_result >> 11) == 0) { + home += winner_second & 0x1f; + away += row.away_goals; + } + row.source_winner = home > away ? 0 : away > home ? 1 : 2; +} + +} // namespace + +OtherGamesProjection other_games_from_game(const ModernState& game, const TextDb& texts, + int competition, int linked_page, int requested_round, + OtherGamesDisplayMode display_mode, int participant_offset, + bool source_new_selection) { + const StaticMemory& memory = game.memory; + if (competition < 0 || competition >= 0x14) invalid("unsupported competition selector"); + if (linked_page < 0 || linked_page >= kCupEntries) invalid("invalid linked-page index"); + if (!memory.has(kActiveSelectors) || !memory.has(kActiveSelectors + kSelectorCount - 1)) + invalid("missing live active-competition selector list"); + + OtherGamesProjection out; + for (uint32_t i = 0; i < kSelectorCount; ++i) { + const uint8_t id = memory.u8(kActiveSelectors + i); + if (id == 0x14) { + out.selectors.push_back({int(i), -1, {}, false}); + continue; + } + if (id > 0x14 || !in_descriptor_table(modern::find_cup(memory, id))) + invalid("active selector has no supported competition descriptor"); + out.selectors.push_back({int(i), int(id), text(texts, kTextCompetitionButtonNames + id), true}); + } + int entry = resolve_linked_entry(memory, competition, linked_page); + if (source_new_selection) { + std::array advanced{}; + while (in_descriptor_table(entry)) { + if (advanced[size_t(entry)]) invalid("cycle while advancing completed Source stages"); + advanced[size_t(entry)] = true; + const uint32_t at = modern::cup_entry_address(entry); + const uint8_t next = memory.u8(at + 0x16); + if (next == 0) break; + const int count = memory.u8(at + 0x1b); + if (modern::cup_round(memory, entry) < count) break; + if (!in_descriptor_table(next)) invalid("completed stage points outside descriptor table"); + entry = next; + } + } + const uint32_t address = modern::cup_entry_address(entry); + const uint8_t flags = memory.u8(address + 0x14); + const int team_count = memory.u8(address + 0x1a); + const int rounds = memory.u8(address + 0x1b); + const int live_round = modern::cup_round(memory, entry); + if (team_count < 0 || team_count > 0x40 || rounds <= 0 || rounds > 0x40) + invalid("descriptor dimensions outside Source bounds"); + const int round = requested_round < 0 ? std::min(live_round, rounds - 1) : requested_round; + if (round < 0 || round >= rounds) invalid("requested round outside descriptor"); + + out.competition = competition; + out.descriptor_competition = int16_t(memory.u16(address + 0x18)); + out.linked_page = linked_page; + out.entry_index = entry; + out.entry_address = address; + out.flags = flags; + out.knockout = (flags & 4) != 0; + out.two_legs = (flags & 1) != 0; + out.current_round = live_round; + out.round = round; + out.rounds = rounds; + out.group_index = memory.u8(address + 0x1e) >> 4; + out.group_count = memory.u8(address + 0x1e) & 0xf; + out.title = text(texts, kTextCompetitionNames + size_t(competition)); + out.linked_pages = source_linked_pages(memory, entry); + + int round_text = ((flags & 4) ? round : 0) + 1 + memory.u8(address + 0x1c); + if (memory.u8(address + 0x1c) == 1 && round == 0) --round_text; + if (round_text < 0 || round_text >= 32) invalid("Source round-heading index outside table"); + out.round_heading = text(texts, kTextRoundHeadings + size_t(round_text)); + if (kTextRoundHeadings + size_t(round_text) == kTextGroupRound && out.round_heading.size() > 0x10) + out.round_heading[0x10] = char('1' + linked_page); + if (kTextRoundHeadings + size_t(round_text) == kTextGroupCaption && out.round_heading.size() > 0x19) + out.round_heading[0x19] = char('0' + (linked_page == 0 ? 1 : linked_page)); + + // Source +0x1a is participants in this round. The detail/compact toggle is gated on this + // value, and detail mode's ordinary window is 16 participant slots (eight matches). + out.source_participant_count = team_count >> (round & 31); + out.display_mode_toggle_available = out.source_participant_count > 0x10; + if (display_mode != OtherGamesDisplayMode::compact && display_mode != OtherGamesDisplayMode::detail) + invalid("unknown Source display mode"); + const OtherGamesDisplayMode effective_mode = out.source_participant_count <= 0x10 + ? OtherGamesDisplayMode::detail : display_mode; + out.display_mode = effective_mode; + if (participant_offset < 0 || participant_offset > 0x7f || participant_offset % 0x10 != 0) + invalid("participant window offset is not a Source 16-slot boundary"); + // Compact draws the whole round, but the caller separately retains local14. + // Detail redraw only ORs CareerSession_DispatchOtherGames_RuntimeField's high bit; it never resets a retained cursor, + // even when a Source ID-versus-slot selection quirk leaves it past this list. + if (effective_mode == OtherGamesDisplayMode::compact) participant_offset = 0; + out.participant_offset = participant_offset; + out.round_arrows_visible = effective_mode == OtherGamesDisplayMode::detail && rounds > 1; + + // CupGroupOverviewEffects selects the second-leg result array only for descriptors with the exact + // two-leg/knockout flags and when the displayed round has reached that leg. + const uint8_t played = memory.u8(address + 0x1d); + const bool second_leg = out.knockout && (played % 2 != 0 || round < played / 2) && (flags & 5) == 5; + + // CupGroupOverviewEffects gates the fixture panel if this knockout round is in the future, or any + // descriptor in its +0x15 predecessor chain has not completed all its source rounds. + int predecessor = int8_t(memory.u8(address + 0x15)); + std::array seen_predecessors{}; + while (predecessor != -1) { + if (!in_descriptor_table(predecessor) || seen_predecessors[size_t(predecessor)]) + invalid("invalid/cyclic predecessor descriptor chain"); + seen_predecessors[size_t(predecessor)] = true; + const uint32_t pred = modern::cup_entry_address(predecessor); + if (modern::cup_round(memory, predecessor) < memory.u8(pred + 0x1b)) out.unfinished_predecessor = true; + predecessor = int8_t(memory.u8(pred + 0x15)); + } + out.fixtures_available = !out.unfinished_predecessor && (!out.knockout || round <= live_round); + out.display_mode_toggle_available = out.fixtures_available && out.source_participant_count > 0x10; + + if (out.descriptor_competition == 12) out.scheduled_day_mode = true; + // Source paints TEXTD1186 and returns before touching team/result/schedule arrays for a + // blocked future or unfinished stage. Preserve that boundary for incomplete live records. + if (!out.fixtures_available) return out; + + const uint32_t team_list = memory.pointer(address); + const uint32_t first_results = memory.pointer(address + 0x0c); + const uint32_t second_results = memory.pointer(address + 0x10); + if (team_count != 0 && team_list == 0) invalid("missing Source team list"); + if (team_count != 0 && first_results == 0) invalid("missing Source result list"); + if (out.knockout && second_leg && second_results == 0) invalid("missing Source second-leg results"); + + int participant_base = 0; + std::vector group_fixtures; + if (out.knockout) { + participant_base = uint8_t(modern::cup_round_offset(memory, entry, round)); + } else { + const int table_teams = modern::cup_group_schedule_teams(memory, address); + if (table_teams <= 0) invalid("unsupported Source group-round schedule table"); + const int rounds_per_leg = rounds / ((flags & 1) + 1); + if (rounds_per_leg <= 0) invalid("invalid group schedule leg count"); + group_fixtures = generate_fixtures(table_teams, round + 1, rounds_per_leg, 0); + } + + int row_participants = out.knockout ? out.source_participant_count : team_count; + int visible_participants = row_participants; + if (out.knockout && effective_mode == OtherGamesDisplayMode::detail) + visible_participants = std::min(visible_participants, 0x10); + const int begin = participant_offset; + const int end = out.knockout ? std::min(row_participants, begin + visible_participants) : row_participants; + if (out.scheduled_day_mode && !memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField3)) invalid("missing live Source date for scheduled competition"); + for (int p = out.knockout ? begin : 0; p + 1 < end; p += 2) { + int home = -1, away = -1, match = p / 2; + size_t result_slot = 0; + if (out.knockout) { + const int slot = participant_base + p; + if (!memory.has(team_list + uint32_t(slot) * 2 + 1)) invalid("truncated Source knockout team list"); + home = memory.u16(team_list + uint32_t(slot) * 2); + away = memory.u16(team_list + uint32_t(slot + 1) * 2); + result_slot = size_t(slot / 2); + } else { + const int fixture = p / 2; + if (size_t(fixture) >= group_fixtures.size()) invalid("group fixture count does not match descriptor"); + const Fixture& f = group_fixtures[size_t(fixture)]; + if (!memory.has(team_list + uint32_t(f.home) * 2 + 1) || + !memory.has(team_list + uint32_t(f.away) * 2 + 1)) invalid("truncated Source group team list"); + home = memory.u16(team_list + uint32_t(f.home) * 2); + away = memory.u16(team_list + uint32_t(f.away) * 2); + result_slot = size_t(round) * size_t(team_count / 2) + size_t(fixture); + } + const uint32_t result_address = first_results + uint32_t(result_slot * 2); + if (!memory.has(result_address + 1)) invalid("truncated Source result list"); + const uint16_t result = memory.u16(result_address); + OtherGamesRow row = make_row(game, home, away, result, match); + if (out.scheduled_day_mode) { + row.kind = OtherGamesRowKind::scheduled_competition; + row.played = false; + row.home_goals = row.away_goals = 0; + row.scheduled_source_day = uint32_t(memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3)) + + uint32_t(int32_t(int16_t(result))); + } else if (out.knockout) { + uint16_t second = 0xcccc; + const bool second_present = second_results != 0; + if (second_results != 0) { + const uint32_t second_address = second_results + uint32_t(result_slot * 2); + if (!memory.has(second_address + 1)) invalid("truncated Source second-leg result list"); + second = memory.u16(second_address); + } + add_second_leg_and_winner(row, second, second_present, second_leg, flags); + } + attach_source_values(game, row); + out.rows.push_back(std::move(row)); + } + if (!out.knockout && team_count > 2) out.group_tables.push_back(modern::cup_group_table(memory, address)); + return out; +} + +} // namespace bmh::modern diff --git a/src/modern/game/other_games.hpp b/src/modern/game/other_games.hpp new file mode 100644 index 0000000..ab1b6ca --- /dev/null +++ b/src/modern/game/other_games.hpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/other_games.hpp" + +#include +#include +#include +#include + +#include "formats/textd.hpp" +#include "modern/game/modern_state.hpp" +#include "game/table.hpp" + +namespace bmh::modern { + +// Source local20==0 (`compact`) draws the complete round in dense six-pixel rows; +// local20==1 (`detail`) draws a 16-participant window in the taller 16-pixel layout. + + +// One Source row in the ordinary CupGroupOverviewEffects desk view. Names and text are kept in +// Original encoding so the presentation layer can pass them through the existing FNT3 path. + + + + +// Const projection of the ordinary menu-5 call to CupGroupOverviewEffects. This API intentionally models +// only the visible values: Original entry separately updates serialized CareerSession_FormatError_RuntimeField3/selector-12 state, +// while complete/compact and page navigation persist the active manager's CareerSession_DispatchOtherGames_RuntimeField byte. It is +// therefore not evidence that the entire Original menu interaction is Native-neutral. +// `linked_page` follows the descriptor's Source +0x17 parallel-group link, then +0x16 next-stage +// link. `round == -1` selects CupRound's live round; otherwise it is range-checked. +// `participant_offset` is Source's low-seven-bit display cursor (multiples of 16). The +// displayed-round group row list remains complete; the mode/offset applies to knockout rows. +OtherGamesProjection other_games_from_game(const ModernState& game, const TextDb& texts, + int competition = 0, int linked_page = 0, + int round = -1, + OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail, + int participant_offset = 0, + bool source_new_selection = true); + +} // namespace bmh::modern diff --git a/src/modern/game/poach.cpp b/src/modern/game/poach.cpp new file mode 100644 index 0000000..afbbd5d --- /dev/null +++ b/src/modern/game/poach.cpp @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/poach.hpp" + +#include + +#include "game/messages.hpp" +#include "modern/game/month.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kAttempts = 0x8b6; // five player ids, 0xffff free +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 rows of 0x58 bytes +constexpr uint32_t kListRow = 0x58; +constexpr uint32_t kOfferSlots = ::bmh::layout::OfferSlots; // OfferSlots: 4 words, -1 free +// Attempt: how many players of each position a club wants (MonthRuntimeField4 / MonthRuntimeField5) +constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4}; + +uint16_t attempt(const ModernState& g, int m, int i) { + const size_t at = size_t(m) * kRecordSize + kAttempts + size_t(i) * 2; + return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); +} + +// PoachAttemptsLeft(player, club): the asking percentage of the club for the player, or -1 with +// the reason in `messages`. A club of a human manager asks 100 %. +int club_asking_percent(const ModernState& g, int player, int club, std::vector& messages, WatcomRandom& rand) { + if (g.manager_of(club) >= 0) return 100; + const Player& p = g.players.at(size_t(player)); + const int position = int(p.w364 & 3); + const int strength = p.strength(true); // Strength(w35c, 1) + const int8_t* wanted = club < german_clubs() ? kWantedBig : kWantedSmall; + // SquadCount(club, 0): the fit players + if (modern::squad_count(g, club, 0) < (club < german_clubs() ? 3 : 0) + 0xe) { + messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer) + g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer2)); + return -1; + } + int sum[4], count[4]; + for (int k = 0; k < 4; k++) { + // QuoteNationalFriendlyMatch with 0x607 + the position bit: sum of the fit players and their number + const TeamAverage a = team_average(g, club, uint16_t((1 << (k + 4)) + 0x607)); + sum[k] = int16_t(a.value); + count[k] = int8_t(a.players); + } + const int short_of = int16_t(wanted[position] - count[position]); // local_24 + if (short_of >= 3 || (short_of == 0 && position == 0)) { + // the club needs him (a club always keeps its second goalkeeper) + messages.push_back(g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer3)); + return -1; + } + int percent = short_of < 0 ? short_of * 0x18 + 0x8c : short_of * 16 + 0x82; // local_34 + if (percent < 0x5a) percent = 0x5a; + int averages = 0; + for (int k = 0; k < 4; k++) averages = int16_t(averages + sum[k] / count[k]); + const int team = averages / 4; + int relative = team != 0 ? int16_t(strength * 100 / team) : 100; // local_30 + if (relative < 0x65) { + percent -= std::clamp(100 - relative, 0, 0x14); // ClampInteger + } else { + const int over = int16_t(relative - 100) >> 1; + percent = int16_t(percent + int16_t(over * over)); + } + if (short_of != 0 && percent >= 0x100) { + messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer4)); // FINANCIAL FAIRPLAY + return -1; + } + if (percent > 0xbe) percent = 0xbe; + return uint8_t(rand.range(0xc, 0x14) + percent); +} + +} // namespace + +int poach_attempts_left(const ModernState& g, int manager) { + int left = 0; + for (int i = 0; i < 5; i++) + if (attempt(g, manager, i) == 0xffff) left++; + return left; +} + +PoachStart start_poach(ModernState& g, int manager, int squad_slot, WatcomRandom& rand) { + PoachStart out; + out.manager = manager; + out.squad_slot = squad_slot; + const size_t rec = size_t(manager) * kRecordSize; + if (attempt(g, manager, 4) != 0xffff) { + out.status = PoachStatus::attempts_used; + out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer2)); + return out; + } + if (g.manager_records.at(rec + 0x220) >> 5 == 1) { // PushBack + out.status = PoachStatus::transfer_ban; + out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer)); + return out; + } + if (squad_slot < 0 || size_t(squad_slot) >= transfer_list_slot() || g.squad_slots.at(size_t(squad_slot)) == 0xfff) return out; + out.player = g.squad_slots.at(size_t(squad_slot)) & 0xfff; + out.club = modern::slot_team(squad_slot); // SlotTeam + if (out.club < 0 || out.club == g.manager_teams.at(size_t(manager))) return out; + // BoughtEntry: a player on loan (table Career_RemoveJoinLoans_RuntimeField) + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xfff) == out.player) { + out.status = PoachStatus::on_loan; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer)); + return out; + } + } + for (int i = 0; i < 5; i++) + if (attempt(g, manager, i) == out.player) { + out.status = PoachStatus::tried_before; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer2)); + return out; + } + // PlayerOnTransferListFirstPoolSlots: the player is on the transfer list (first 44 pool slots) + for (size_t s = transfer_list_slot(); s < transfer_list_slot() + 0x2c; s++) + if ((g.squad_slots.at(s) & 0xfff) == out.player) { + out.status = PoachStatus::on_transfer_list; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer3)); + return out; + } + const int percent = club_asking_percent(g, out.player, out.club, out.messages, rand); + if (percent < 0) { + out.status = PoachStatus::club_refuses; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer5)); + return out; + } + out.asking_percent = percent; + // RowWhose: a special row whose OfferSlots word is free + int k = 0; + while (k < 4 && g.memory.u32(kOfferSlots + uint32_t(k) * 4) != 0xffffffffu) k++; + if (k == 4) { + out.status = PoachStatus::market_busy; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer4)); + modern::finish_poach(g, out); + return out; + } + out.offer_row = k; + const int demand = rand.range(0x50, 100); + // Range2(slot, 0, percent, demand, 0, k): the row like a market row of the club. + // (Its salary floor for a club of a human manager searches the buyer's own squad for + // the player and so never applies; the 0x8000 flag of the club word is kept.) + const uint32_t row = kTransferList + uint32_t(0x28 + k) * kListRow; + uint16_t club_word = uint16_t(out.club); + if (g.manager_of(out.club) >= 0) club_word |= 0x8000; + g.memory.set16(row + 8, club_word); + for (int b = 0; b < 4; b++) g.memory.set16(row + uint32_t(b) * 2, 0xffff); + g.memory.set8(row + 0x54, uint8_t(percent)); + g.memory.set8(row + 0x55, uint8_t(demand)); + uint32_t fee = 0, salary = 0; + modern::market_value(g, squad_slot, 0, uint8_t(percent), fee, salary, 1, 0, rand); + g.memory.set32(row + 0x2c, fee); + g.memory.set32(row + 0x30, salary); + g.squad_slots.at(transfer_list_slot() + 0x28 + size_t(k)) = uint16_t(out.player); + out.status = PoachStatus::ready; + return out; +} + +void finish_poach(ModernState& g, const PoachStart& poach) { + if (poach.offer_row >= 0) { + g.squad_slots.at(transfer_list_slot() + 0x28 + size_t(poach.offer_row)) = 0xfff; + g.memory.set32(kOfferSlots + uint32_t(poach.offer_row) * 4, 0xffffffffu); + } + for (int i = 0; i < 5; i++) + if (attempt(g, poach.manager, i) == 0xffff) { + const size_t at = size_t(poach.manager) * kRecordSize + kAttempts + size_t(i) * 2; + g.manager_records.at(at) = uint8_t(poach.player); + g.manager_records.at(at + 1) = uint8_t(poach.player >> 8); + break; + } +} + +} // namespace bmh::modern diff --git a/src/modern/game/poach.hpp b/src/modern/game/poach.hpp new file mode 100644 index 0000000..d887d4d --- /dev/null +++ b/src/modern/game/poach.hpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/poach.hpp" +// Poaching ("Abwerben", transfer screen menu 17, H2 p. 70; BMH.exe V2.24 + supported rule profile patch): +// the manager picks a player of another club in the league tables and makes him an offer +// that is decided at once. Button 4 of the transfer screen Reset: +// +// - at most five attempts per season: the players tried are kept in manager record +// +0x8b6 (5 words, 0xffff free; cleared at the season start, season.cpp) - CareerSession_DispatchPoachUi_TextPointer2 +// - not with a transfer ban (record +0x220 >> 5 == 1, PushBack, CareerSession_DispatchPoachUi_TextPointer) +// - not for a player on loan (BoughtEntry, Poach_StartPoach_TextPointer), not twice for the same player +// (Poach_StartPoach_TextPointer2), not for a player on the transfer list (PlayerOnTransferListFirstPoolSlots, Poach_StartPoach_TextPointer3) +// - the club must let him go (PoachAttemptsLeft): its squad must be big enough, the position +// must not be short (and a club keeps its second goalkeeper); the asking percentage +// follows how much the club needs him and how good he is compared with the team +// - the offer uses one of the special list rows 40..43 (RowWhose: a row whose +// OfferSlots word is free, else "Transfermarkt überlastet"), prepared like a market +// row by Range2: asking percentage, demand W(80, 100), market value and salary. +// +// The offer itself is the ordinary offer editor (desk_actions.hpp, OpenTransferEditor) on that +// row with `poach` set; its submit (SubmitTransferBidSourceHumanBuyer) decides at once. finish_poach frees the +// row again and counts the attempt, as the original does when the editor returns. + +#include +#include + +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + + + +// Attempts left this season (record +0x8b6). +int poach_attempts_left(const ModernState& g, int manager); + +// Button 4 after the player was picked (FriendlyMatchScreen returned `squad_slot`): the checks, +// PoachAttemptsLeft, RowWhose and Range2. Draws W(12, 20) (asking percentage), W(80, +// 100) (demand) and what the market value draws. `market_busy` counts the attempt itself. +PoachStart start_poach(ModernState& g, int manager, int squad_slot, WatcomRandom& rand); + +// When the offer editor has returned: the pool slot of the row is emptied, its OfferSlots +// word freed and the attempt recorded in +0x8b6. +void finish_poach(ModernState& g, const PoachStart& poach); + +} // namespace bmh::modern diff --git a/src/modern/game/prediction.cpp b/src/modern/game/prediction.cpp new file mode 100644 index 0000000..c48c2bf --- /dev/null +++ b/src/modern/game/prediction.cpp @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/prediction.hpp" + +#include +#include + +#include "modern/game/matchday.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecord = 0xB0C; // manager record +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; // one slot of the board + +// Static league tables of V2.24 (not part of the savegame): +// (European places per league, CareerSession_InstallLeagueSizes_RuntimeField, are kLeagueEurope of the loaded game; league 0 uses 4) +// (the relegation places per league, CareerSession_InstallLeagueSizes_RuntimeField2, are kLeagueRelegation of the loaded game) + +// Text of a pointer variable of the text table TextPointerTable. +} // namespace + +int table_prediction(ModernState& g, int team, int mode, std::array& buf, int* size_word) { + buf.fill(1); + int league = team_league(team); // local_30 + if (league >= kLeagueCount) return 0; // reads CareerRuntimeField6[0] = 0 as the round count + const int rounds = int8_t(g.league_rounds.at(size_t(league))); // local_1c + const int matchdays = league_matchdays(league); // LeagueMatchdayCounts + if (rounds < 2 || matchdays <= rounds) return 0; + const int manager = g.manager_of(team); // local_18, 0xFF = none + // (Fill would refresh the desk warning flags PredictionRuntimeField.. here; they are + // run-time only and not needed by the game logic.) + const size_t rec = size_t(manager) * kRecord; + const int size = kLeagueSizes[league]; // local_2c + if (size_word) *size_word = size; // (stored as a word, see the header) + if (team >= league_clubs()) return 9; + const int pos = team - league_first_team(league); // local_24 + const int target[3] = {0, league == 0 ? 4 : kLeagueEurope[league], size - kLeagueRelegation[league]}; + + int from = 0; // local_10 + if (mode > 3) { + from = rounds - 5 * (mode >> 2); + if (from < 0) from = 0; + } + auto per_game = [&](const LeagueTable& t, int club) { + const int games = t.games(club); + return games ? t.points[club] * 500 / games : 0; // the original divides by zero here + }; + int own_rate = 1500; // local_34: three points per remaining game + if (mode != 1) own_rate = per_game(compute_league_table(g, league, from, rounds, 3, 0), pos); + const LeagueTable full = compute_league_table(g, league, 0, rounds, 7, 0); + int points[20] = {}, remaining[20] = {}; // acStack_60, acStack_4c + for (int c = 0; c < size; c++) { + points[c] = full.points[c]; + remaining[c] = int8_t(matchdays - full.games(c)); + } + // The scratch table the rates of the other clubs are read from: the recent form table + // for mode >= 4, otherwise still the full table. + const LeagueTable rates = mode > 3 ? compute_league_table(g, league, from, rounds, 3, 0) : full; + uint16_t own = uint16_t(points[pos] * 500 + remaining[pos] * own_rate); // local_28 (low word) + + int ahead = size; // local_20: ranks that are out of reach + if (mode == 1) { + ahead = 0; + for (int c = 0; c < size; c++) ahead += int(own) < points[c] * 500; + } + for (int r = 0; r < ahead; r++) buf.at(size_t(r)) = 0; + + int league_index = league; // local_30 is changed by the league name of message 1 + if (mode == 1) { + for (int k = 0; k < 3; k++) { + if (buf.at(size_t(target[k])) != 0) continue; + if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> k & 1)) continue; + // the goal can no longer be reached + if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << k); + std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer2); + if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer3); + if (k == 1) { + std::string tail; + if (league_index == 0) { + tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer4); + } else if (league_index == 2 || league_index == 3) { + tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer5); + } else { + msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer6); + if (league_index > 2) league_index--; + msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer + uint32_t(league_index) * 4); // league name + tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer7); + } + msg += tail; + } + if (k == 2) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer8); + if (manager >= 0) post_composed(g, manager, msg); + } + own = uint16_t(points[pos] * 500); + } + + int behind = 0; // local_14: clubs that can no longer catch up + for (int c = 0; c < size; c++) { + if (c == pos) continue; + int rate; + if (mode == 1) rate = 1500; + else if (mode == 2) rate = 0; + else rate = int16_t(per_game(rates, c)); + if (uint16_t(points[c] * 500 + remaining[c] * rate) < own) behind++; + } + int r = 0; + for (; r < behind; r++) buf.at(size_t(size - r - 1)) = 0xFF; + if (mode != 1) { + if (r == size) r++; // cannot happen: the club itself is never counted + buf.at(size_t(size - r - 1)) = 1; + } + if (mode == 1) { + for (int k = 0; k < 3; k++) { + if (buf.at(size_t(target[k])) != 0xFF) continue; + if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> (k + 3) & 1)) continue; + // the goal is secured (or relegation avoided / certain) + if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << (k + 3)); + std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer9); + if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer10); + else if (k == 1) + msg += message_text(g, league_index == 0 ? ::bmh::layout::Prediction_TablePrediction_TextPointer11 : (league_index == 2 || league_index == 3) ? ::bmh::layout::Prediction_TablePrediction_TextPointer12 : ::bmh::layout::Prediction_TablePrediction_TextPointer13); + else msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer14); + msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer15); + // without a manager the original posts to "manager" 0xFE; not needed here + if (manager >= 0) post_composed(g, manager, msg); + } + } + int first = 0; + while (first < 24 && buf[size_t(first)] == 0) first++; + return (first + 1) & 0xFF; +} + +static uint32_t season_bonus_impl(ModernState& g, int manager, int team, int board_slot, int rank, bool pay) { + const int league = team_league(team); + uint32_t amount = 0; + if (league == 0 && rank == 0) amount = modern::pay_bonus(g, manager, board_slot, 3, pay); + if (amount == 0 && rank < 5) amount = modern::pay_bonus(g, manager, board_slot, 4, pay); + if (amount == 0 && rank < 10) amount = modern::pay_bonus(g, manager, board_slot, 5, pay); + if (amount == 0 && league < kLeagueCount && rank < kLeagueSizes[league] - kLeagueRelegation[league]) + amount = modern::pay_bonus(g, manager, board_slot, 6, pay); + return amount; +} + +uint32_t season_bonus(ModernState& g, int manager, int board_slot, int rank, bool pay) { + return season_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),board_slot,rank,pay); +} + +static uint32_t expected_bonus_impl(ModernState& g, int manager, int team, int rank, int board_slot, int player, bool fitness) { + static const uint8_t kPerSeason[3] = {0, 34, 25}; // PredictionRuntimeField2: -, points, appearances + static const uint8_t kGoals[4] = {0, 2, 4, 8}; // PredictionRuntimeField3: goals by position + const int position = int(g.players.at(size_t(player)).w364 & 3); + if (rank == 0xFF) { + std::array buf; + const int r = modern::table_prediction(g, team, 4, buf); + rank = r == 0 ? 0xB : r + 1; + } + const size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot; + const uint32_t base = uint32_t(g.tactics.at(slot + 0x50) | g.tactics.at(slot + 0x51) << 8 | + g.tactics.at(slot + 0x52) << 16) | uint32_t(g.tactics.at(slot + 0x53)) << 24; + uint32_t sum = 0; + for (int k = 0; k < 3; k++) { + uint32_t times = k == 0 ? kGoals[position] : kPerSeason[k]; + if (fitness && k != 1) { + // the fitness correction: a player weaker than the team average (QuoteNationalFriendlyMatch + // flags 499) earns goal and appearance bonuses less often - PredictionRuntimeField4 per gap + static const uint8_t kPerGap[3] = {1, 0, 5}; // PredictionRuntimeField4 + const uint32_t w = g.players.at(size_t(player)).w35c; + int gap = int16_t(team_average(g, team, 499).value - + int((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) >> 1)); + if (gap < -1) gap = -1; + const int t = int(times) - kPerGap[k] * gap; + times = t < 0 ? 0 : uint32_t(t); + } + sum += g.tactics.at(slot + 0x12 + size_t(k)) * base / 100 * times / 12; + } + return season_bonus_impl(g, manager, team, board_slot, rank & 0xFF, false) / 12 + sum; +} + +uint32_t expected_bonus(ModernState& g, int manager, int rank, int board_slot, int player, bool fitness) { + return expected_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),rank,board_slot,player,fitness); +} + +uint32_t expected_bonus_parked_club_source(ModernState& g, int rank, int board_slot, int player, bool fitness) { + constexpr size_t team_at=4*kRecord+0x290; + if(g.manager_teams!=std::vector{no_team()} || !g.memory.has(::bmh::layout::CoachActive) || + g.memory.u8(::bmh::layout::CoachActive)==0 || !g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 || + !g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + g.manager_records.size()<5*kRecord || + (int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=no_team() || + board_slot<0 || board_slot>=24 || g.tactics.size()<5*kBoard) + throw std::invalid_argument("expected_bonus: invalid FindManagerForClub parked club context"); + const int team=int(g.manager_records[team_at]) | int(g.manager_records[team_at+1])<<8; + if(team<0 || team>=league_clubs()) + throw std::invalid_argument("expected_bonus: parked record4 has no ordinary club"); + return expected_bonus_impl(g,4,team,rank,board_slot,player,fitness); +} + +} // namespace bmh::modern diff --git a/src/modern/game/prediction.hpp b/src/modern/game/prediction.hpp new file mode 100644 index 0000000..6915f56 --- /dev/null +++ b/src/modern/game/prediction.hpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/prediction.hpp" +// Table prediction and bonus expectations of human managers (BMH.exe V2.24). +// +// table_prediction Void5 which final ranks a club can still reach / has secured +// expected_bonus ContractOffer bonus a player on the tactics board can expect +// season_bonus SeasonBonus the board's season bonus (title, Europe, staying up) +// +// team_rating (rating.cpp) uses them for the players of human managers: a player who can +// expect a large bonus relative to his base pay tries harder (+5 with some probability). +// As a side effect the prediction posts the "still possible" / "no longer possible" +// messages about the season goals (champion, Europe, relegation) to the manager, once per +// goal and season (bits 0-5 of manager record +0x28b). + +#include +#include + +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// Void5(team, mode, buf). Fills buf[0..23], one entry per final rank: +// 0 the rank can no longer be reached (at least that many clubs stay ahead) +// 1 the predicted rank (modes other than 1) +// 0xFF a rank the club cannot fall to any more +// and returns the first rank (1-based) that is not 0, i.e. the best reachable rank. +// mode 1: maximum points = points + 3 per remaining game for every club (and messages); +// mode 2: the club's own points per game projected, the others stay where they are; +// mode 3: every club projected with its own points per game; +// mode >= 4: as 3, but the points per game over the last 5 * (mode / 4) matchdays. +// `size_word` receives the league size, which the original stores as a word in its frame +// (local_2c) unless it returns early (before the second matchday etc.; then it stays +// untouched). The side ratings read that stack word as a stale value, see team_rating. +// Returns 0 before the second matchday and after the last one (and for leagues >= 9), +// 9 for clubs outside the league system (ids from 138 on). +int table_prediction(ModernState& g, int team, int mode, std::array& buf, int* size_word = nullptr); + +// ContractOffer(manager, predicted rank, board slot, player, 0): goal, point and appearance +// bonus of the board slot, each weighted by how often it is earned (goals by position: +// PredictionRuntimeField3, points 34, appearances 25 per season), plus the season bonus for the +// predicted rank, all divided by 12. `rank` 0xFF means: predict it (table_prediction mode 4). +// Only the variant without the fitness correction (last argument 0) is ported. +uint32_t expected_bonus(ModernState& g, int manager, int rank, int board_slot, int player, bool fitness = false); + +// Checked FindManagerForClub record4 variant for a club parked during national takeover. +// Read the actual club from record4 without adding it to the active manager list. +uint32_t expected_bonus_parked_club_source(ModernState& g, int rank, int board_slot, int player, bool fitness = false); + +// SeasonBonus(manager, board slot, rank, 0): season bonus of the slot for a final rank: +// title (league 0 only, rank 0), top 5, top 10, staying up (bonus indices 3-6 of the slot, +// the first one that is set and applies). Not paid. +uint32_t season_bonus(ModernState& g, int manager, int board_slot, int rank, bool pay = false); + +} // namespace bmh::modern diff --git a/src/modern/game/reschedule.cpp b/src/modern/game/reschedule.cpp new file mode 100644 index 0000000..3c8bcb6 --- /dev/null +++ b/src/modern/game/reschedule.cpp @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/reschedule.hpp" + +#include + +#include "modern/game/matchday_setup.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" + +namespace bmh::modern { + +namespace { + +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; // u16 per season day +constexpr int kCalendarDays = 0x16e; // CalendarCell copies 0x16e words +constexpr uint32_t kPostponed = ::bmh::layout::Postponed; // 40 entries: u16 day, round, league, match +constexpr int kPostponedEntries = 0x28; +constexpr uint32_t kFriendlyTeams = ::bmh::layout::FriendlyTeams; // friendly plan: team pairs +constexpr uint32_t kFriendlyDays = ::bmh::layout::FriendlyDays; // friendly plan: days, 30 entries +constexpr int kFriendlyEntries = 30; +// MatchdaySetupRuntimeField3 / MatchdaySetupRuntimeField4: first and last day of the winter break. +constexpr int kWinterBreakFirst = 0x96, kWinterBreakLast = 0xc8; +// RescheduleLeagueMatch accepts replay days up to 0x11e; the draw loop wants the day after the +// target inside 0x15 .. 0x11e. +constexpr int kLastReplayDay = 0x11e, kFirstDayAfter = 0x15; +constexpr uint8_t kRescheduledMark = 0xce; // param_5 = -0x32 +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kFloodlights = 0x0e; // manager record byte (RescheduleRuntimeField) +// LeagueCalendarBits: calendar bit of a league (the two leagues 2 and 3 share bit 2, the four +// leagues of 12 clubs bit 4; compare kGroupLeague in matchday_setup.cpp). +// (kLeagueBit: schedule.hpp, set from the groups of the loaded game; 0xff = not played) + +size_t result_at(int league, int round, int match) { return size_t(match) + size_t(round) * 10 + size_t(league) * 0x17c; } + +bool memory_ok(const ModernState& g) { + return g.memory.has(kCalendar + kCalendarDays * 2 - 1) && + g.memory.has(kPostponed + kPostponedEntries * 6 - 1) && g.memory.has(kFriendlyDays + kFriendlyEntries * 2 - 1) && + g.memory.has(kFriendlyTeams + kFriendlyEntries * 4 - 1); +} + +// The club of a human manager in league play, or -1. +int manager_team(const ModernState& g, int manager) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return -1; + const int team = g.manager_teams[size_t(manager)]; + if (team < 0 || team_league(team) >= kLeagueCount) return -1; + return team; +} + +std::vector round_fixtures(int league, int round) { + return generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league)); +} + +// DayConflict(team, other, word, day): 1 when `day` (calendar word `word` of the screen's +// copy) cannot take a match of `team`/`other`: the word is taken (anything but 0, 0x4001 or +// a word marked eligible with bit 15) or the friendly plan already has a match of one of the +// teams - or of the national team - on that day. +bool day_conflict(const ModernState& g, int team, int other, uint16_t word, int day) { + if (word != 0 && word != 0x4001 && (word & 0x8000) == 0) return true; + for (int i = 0; i < kFriendlyEntries; i++) { + if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != uint16_t(day)) continue; + for (int side = 0; side < 2; side++) { + const int t = int16_t(g.memory.u16(kFriendlyTeams + uint32_t(i) * 4 + uint32_t(side) * 2)); + if (t == no_team() || t == team || t == other) return true; + } + } + return false; +} + +// RescheduleTargetDays(day, team, league): entry + 1 of a replay of `team` in `league` on `day`, or 0 +// (the last such entry, as the original keeps looking). +int team_replay_on(const ModernState& g, int day, int team, int league) { + int found = 0; + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != uint16_t(day) || g.memory.u8(at + 3) != league) continue; + const Fixture f = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4)); + if (f.home == team || f.away == team) found = e + 1; + } + return found; +} + +// The draw loop of CalendarCell in mode 2 on a copy of the calendar: a future day is marked +// (bit 15) when it is free (0, 0x4001 or a calendar event 0x1c0), neither it nor its two +// neighbours conflict for the club (the neighbours before it may already be marked), the +// day after it lies in 0x15 .. 0x11e and it is not in the winter break. The national team +// (manager 0 coaching team 0x165) also checks the club of the Bundestrainer, CupDraw_FormatError_RuntimeField3. +std::vector marked_calendar(const ModernState& g, int team) { + std::vector cal(kCalendarDays); + for (int d = 0; d < kCalendarDays; d++) cal[size_t(d)] = g.memory.u16(kCalendar + uint32_t(d) * 2); + // DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day + const int today = g.season_day(); + const bool national = !g.manager_teams.empty() && g.manager_teams[0] == no_team() && g.memory.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField); + for (int d = today + 1; d < kCalendarDays; d++) { + const uint16_t word = cal[size_t(d)]; + if (word != 0 && word != 0x4001 && (word & 0x1c0) == 0) continue; + bool ok = true; + for (int i = std::max(0, d - 1); i <= std::min(kCalendarDays - 1, d + 1); i++) { + if (day_conflict(g, team, -1, cal[size_t(i)], i)) ok = false; + if (national && day_conflict(g, int16_t(g.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)), -1, cal[size_t(i)], i)) ok = false; + } + if (d + 1 > kLastReplayDay || d + 1 < kFirstDayAfter) ok = false; + if (d >= kWinterBreakFirst && d <= kWinterBreakLast) ok = false; + if (team == no_team() && (word & 0x1c0) != 0) ok = false; + if (ok) cal[size_t(d)] |= 0x8000; + } + return cal; +} + +} // namespace + +std::vector reschedulable_matches(const ModernState& g, int manager) { + std::vector out; + const int team = manager_team(g, manager); + if (team < 0 || !memory_ok(g)) return out; + const int league = team_league(team); + // The screen only reacts to the calendar bit of the club's league for bits 0-3 + // (local_34 == bit); CalendarCell derives local_34 as league - (league > 2). + const int screen_bit = league > 2 ? league - 1 : league; + if (screen_bit > 3 || kLeagueBit[league] != screen_bit) return out; + // DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day + const int today = g.season_day(); + const int matchdays = league_matchdays(league); + int round = -1; + for (int day = 0; day < kCalendarDays; day++) { + const uint32_t comps = modern::day_competitions(g, g.memory.u16(kCalendar + uint32_t(day) * 2)); + if (kLeagueBit[league] > 7 || !((comps >> kLeagueBit[league]) & 1)) continue; + ++round; // local_58 - 1: the league days up to this one + if (day <= today || round == 0 || round + 2 >= matchdays) continue; + const std::vector fixtures = round_fixtures(league, round); + for (size_t m = 0; m < fixtures.size(); m++) { + const Fixture& f = fixtures[m]; + if (f.home != team && f.away != team) continue; + // the screen picks the club's match of the day; only a home match can be moved + if (f.home == team && g.results.at(result_at(league, round, int(m))) == kNotPlayed) + out.push_back({day, round, league, int(m), f.home, f.away}); + break; + } + } + return out; +} + +std::vector reschedule_target_days(const ModernState& g, int manager, const LeagueMatchRef& match) { + std::vector out; + const int team = manager_team(g, manager); + if (team < 0 || !memory_ok(g)) return out; + const std::vector movable = modern::reschedulable_matches(g, manager); + if (std::none_of(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) { + return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match; + })) + return out; + std::vector cal = marked_calendar(g, team); + // floodlights: the day before the matchday (the Friday) is offered as well + if ((size_t(manager) + 1) * kRecordSize <= g.manager_records.size() && + g.manager_records[size_t(manager) * kRecordSize + kFloodlights] != 0 && match.day > 0) + cal[size_t(match.day - 1)] |= 0x8000; + for (int d = 0; d < kCalendarDays; d++) + if ((cal[size_t(d)] & 0x8000) && d != match.day && d <= kLastReplayDay && team_replay_on(g, d, team, match.league) == 0) + out.push_back(d); + return out; +} + +RescheduleStatus reschedule_league_match(ModernState& g, int manager, const LeagueMatchRef& match, int day) { + if (manager_team(g, manager) < 0 || !memory_ok(g)) return RescheduleStatus::invalid_manager; + const std::vector movable = modern::reschedulable_matches(g, manager); + const auto it = std::find_if(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) { + return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match; + }); + if (it == movable.end()) return RescheduleStatus::invalid_match; + const std::vector days = modern::reschedule_target_days(g, manager, *it); + if (std::find(days.begin(), days.end(), day) == days.end()) return RescheduleStatus::invalid_day; + // the first free entry of the postponed list + int slot = -1; + for (int e = 0; e < kPostponedEntries && slot < 0; e++) + if (g.memory.u16(kPostponed + uint32_t(e) * 6) == 0) slot = e; + if (slot < 0) return RescheduleStatus::no_free_slot; + // RescheduleLeagueMatch(day, league, match, slot, -0x32, round): eight replays on the day or a + // team clash with one of them refuse the move. Like the winter mode the original builds + // the other replay's fixtures with the parameters of this league and compares the low + // bytes of the team ids only. + const int league = it->league; + const Fixture own = round_fixtures(league, it->round).at(size_t(it->match)); + int same_day = 0; + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != uint16_t(day)) continue; + if (++same_day == 8) return RescheduleStatus::day_full; + const Fixture other = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4)); + const uint8_t oh = uint8_t(other.home), oa = uint8_t(other.away), fh = uint8_t(own.home), fa = uint8_t(own.away); + if (fh == oh || fa == oa || fa == oh || fh == oa) return RescheduleStatus::team_clash; + } + const uint32_t at = kPostponed + uint32_t(slot) * 6; + g.memory.set16(at, uint16_t(day)); + g.memory.set8(at + 2, uint8_t(it->round)); + g.memory.set8(at + 3, uint8_t(league)); + g.memory.set8(at + 4, uint8_t(it->match)); + g.results.at(result_at(league, it->round, it->match)) = kRescheduledMark; + const uint32_t high = kCalendar + uint32_t(day) * 2 + 1; + g.memory.set8(high, g.memory.u8(high) | 0x40); + return RescheduleStatus::moved; +} + +std::vector moved_matches(const ModernState& g, int manager) { + std::vector out; + const int team = manager_team(g, manager); + if (team < 0 || !memory_ok(g)) return out; + const int league = team_league(team); + const int today = g.season_day(); + // CalendarCell: a click on a replay day (calendar bit 0xe) finds the club's replay with + // RescheduleTargetDays(day, team, league) and calls UndoReschedule when its result byte is 0xCE + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + const int day = g.memory.u16(at); + if (day == 0 || day <= today || g.memory.u8(at + 3) != league) continue; + if (team_replay_on(g, day, team, league) != e + 1) continue; + const int round = g.memory.u8(at + 2), m = g.memory.u8(at + 4); + if (round == 0 || round + 2 >= league_matchdays(league)) continue; + if ((g.results.at(result_at(league, round, m)) & 0xcf) != kRescheduledMark) continue; + const Fixture f = round_fixtures(league, round).at(size_t(m)); + out.push_back({day, round, league, m, f.home, f.away}); + } + std::sort(out.begin(), out.end(), [](const LeagueMatchRef& a, const LeagueMatchRef& b) { return a.day < b.day; }); + return out; +} + +bool undo_reschedule(ModernState& g, int manager, int day) { + const std::vector moved = modern::moved_matches(g, manager); + if (std::none_of(moved.begin(), moved.end(), [&](const LeagueMatchRef& m) { return m.day == day; })) return false; + const int team = manager_team(g, manager); + // UndoReschedule(day, 1, team): every replay of the club on that day, whatever its league + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != uint16_t(day)) continue; + const int league = g.memory.u8(at + 3), round = g.memory.u8(at + 2), m = g.memory.u8(at + 4); + const Fixture f = round_fixtures(league, round).at(size_t(m)); + if (f.home != team && f.away != team) continue; + g.results.at(result_at(league, round, m)) = kNotPlayed; + g.memory.set16(at, 0); + } + return true; +} + +} // namespace bmh::modern diff --git a/src/modern/game/reschedule.hpp b/src/modern/game/reschedule.hpp new file mode 100644 index 0000000..bce2453 --- /dev/null +++ b/src/modern/game/reschedule.hpp @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/reschedule.hpp" +// Rescheduling a home league match (desk menu 7, "Verlegen", H2 p. 49; BMH.exe V2.24 + +// supported rule profile patch). The original does it on the calendar screen CalendarCell with mode 2: +// +// 1. The manager clicks a matchday of his own league. The match of his club on that day +// is selected when it is a home match, still in the future, not on the first matchday +// and not on one of the last two matchdays. +// 2. The calendar then marks the days the match can move to (draw loop of CalendarCell, +// see reschedule_target_days). With floodlights (manager record +0x0e) the day before +// the matchday (the Friday) is offered as well. +// 3. A click on a marked day moves the match with RescheduleLeagueMatch(day, league, match, slot, +// -0x32, round): the match becomes a "replay" on that day (postponed list Postponed), +// its result byte becomes 0xCE and the calendar day gets bit 0x4000. On the original +// matchday the 0xCE turns into 0xCD (matchday_setup) and the match is played on the +// new day like a winter postponement. +// 4. A click on the new day of a moved match takes the move back (UndoReschedule(day, 1, +// team)): the entry is freed and the result byte is 0xCC again. The calendar keeps bit +// 0x4000, as in the original. +// +// Everything here works on the saved ModernState only: no random numbers are drawn, so a +// rescheduled career stays deterministic. + +#include +#include + +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// A league match: day of the season (index into the calendar CompetitionCalendar), the 0-based +// league round, the league and the index of the match in the fixture list of that round. + + +// The own home league matches that can be moved: future days, rounds 1 .. matchdays - 3 +// (0-based), result byte still 0xCC (not played, not postponed). Only clubs of leagues +// 0-4 (calendar bits 0-3) take part: the lower leagues have no own calendar bit. +std::vector reschedulable_matches(const ModernState& g, int manager); + +// The days `match` can be moved to (the days CalendarCell marks in mode 2), ascending. +// Days that already hold a replay of one of the teams in the same league are left out, as +// the second click refuses them (RescheduleTargetDays). +std::vector reschedule_target_days(const ModernState& g, int manager, const LeagueMatchRef& match); + +// Moves `match` to `day` (RescheduleLeagueMatch with param_5 = -0x32). Returns moved on success; on +// failure nothing is changed. +RescheduleStatus reschedule_league_match(ModernState& g, int manager, const LeagueMatchRef& match, int day); + +// The own matches moved with reschedule_league_match that can still be taken back: their new +// day (`day`) is in the future, the result byte is 0xCE and the round is one the screen +// accepts (1 .. matchdays - 3). Winter postponements (0xCD) are not listed. Like the +// original the club need not be the home side: in a hot seat game the opponent's manager can +// take back a move as well. +std::vector moved_matches(const ModernState& g, int manager); + +// Takes back the move of the club's match on `day` (one of moved_matches) - UndoReschedule with +// param_2 = 1: every replay on that day with the club gets result byte 0xCC and its entry is +// freed. Returns false if there is no such match. +bool undo_reschedule(ModernState& g, int manager, int day); + +} // namespace bmh::modern diff --git a/src/modern/game/save.cpp b/src/modern/game/save.cpp new file mode 100644 index 0000000..35ecd0a --- /dev/null +++ b/src/modern/game/save.cpp @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/save.hpp" + +#include +#include +#include + +#include "formats/savestate.hpp" +#include "modern/game/career.hpp" +#include "modern/game/national.hpp" + +namespace bmh::modern { + +namespace { + +void put(Bytes& d, const uint8_t* src, size_t n) { + for (size_t i = 0; i < n && i < d.size(); i++) d[i] = src[i]; +} +void put(Bytes& d, const std::vector& v) { put(d, v.data(), v.size()); } +void put16(Bytes& d, const std::vector& v) { + for (size_t i = 0; i < v.size() && 2 * i + 1 < d.size(); i++) d[2 * i] = uint8_t(v[i]), d[2 * i + 1] = uint8_t(v[i] >> 8); +} +void put32(Bytes& d, size_t at, uint32_t x) { + for (int i = 0; i < 4 && at + size_t(i) < d.size(); i++) d[at + size_t(i)] = uint8_t(x >> (8 * i)); +} + +// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a +// four-year leap cycle that starts with the third year). +std::string date_text(uint32_t counter, int start_year) { + static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int cycle = 3, years = 0, month = 7; + while (counter > uint32_t(364 + (cycle == 4))) { + if (cycle == 4) cycle = 0, --counter; + ++years, counter -= 365, ++cycle; + } + auto days = [&] { return month == 2 ? 28 + (cycle == 4) : kDays[month]; }; + while (counter > uint32_t(days())) { + counter -= uint32_t(days()); + if (++month == 13) month = 1, ++years; + } + int day = int(counter) + 1; + if (day > days()) { + day -= days(); + if (++month == 13) month = 1, ++years; + } + char buf[16]; + std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, start_year + years); + return buf; +} + +} // namespace + +Bytes save_stream(const ModernState& live) { + // NationalCoachAfterLoad writes a Bundestrainer's game with the slots swapped back (national.hpp) + const bool coach = live.memory.has(::bmh::layout::CoachActive) && live.memory.u8(::bmh::layout::CoachActive) != 0; + const ModernState swapped = coach ? modern::national_coach_save_form(live) : ModernState{}; + const ModernState& g = coach ? swapped : live; + const bool records = g.memory.has(::bmh::layout::ClubSeasonRecords) && g.memory.u32(::bmh::layout::ClubSeasonRecords) != 0; + Bytes stream; + for (const SaveBlock& b : save_layout(DbCounts{}, records)) { + Bytes d(b.size, 0); + if (b.heap) { + switch (b.address) { + case ::bmh::layout::PlayerBonuses: put(d, g.player_bonus); break; + case ::bmh::layout::TeamMorale: put(d, g.team_morale); break; + case ::bmh::layout::ClubBadgeSelectors: put(d, g.club_heap_78); break; + case ::bmh::layout::TeamFlags: put16(d, g.team_flags); break; + case ::bmh::layout::ClubIdentities: put16(d, g.club_ids); break; + case ::bmh::layout::PlayerNameOffsets: put16(d, g.player_name_offsets); break; + case ::bmh::layout::MasterDatabaseMetadata: put(d, g.master_database_metadata); break; + case ::bmh::layout::ClubAuxiliaryWords: put(d, g.club_heap_bc); break; + case ::bmh::layout::LeagueRankHistory: put(d, g.position_history); break; + case ::bmh::layout::ClubAuxiliaryBytes: put(d, g.club_heap_b8); break; + case ::bmh::layout::SquadSlots: put16(d, g.squad_slots); break; + case ::bmh::layout::PlayerCards: put16(d, g.player_cards); break; + case ::bmh::layout::ManagerMailbox: put(d, g.mailbox); break; + case ::bmh::layout::TournamentName: put(d, g.tournament_name); break; + case ::bmh::layout::ClubSeasonRecords: put(d, g.club_table); break; + case ::bmh::layout::PlayerConditionTechniqueForm: + case ::bmh::layout::PlayerSkillWords: + case ::bmh::layout::PlayerIdentityWords: + for (size_t i = 0; i < g.players.size(); i++) { + const Player& p = g.players[i]; + put32(d, i * 4, b.address == ::bmh::layout::PlayerConditionTechniqueForm ? p.w35c : b.address == ::bmh::layout::PlayerSkillWords ? p.w368 : p.w364); + } + break; + default: break; + } + } else { + for (size_t i = 0; i < b.size; i++) + if (g.memory.has(b.address + uint32_t(i))) d[i] = g.memory.u8(b.address + uint32_t(i)); + // the blocks ModernState keeps in typed fields + switch (b.address) { + case ::bmh::layout::ManagerRecords: put(d, g.manager_records); break; + case ::bmh::layout::ManagerMatchHistory: put(d, g.manager_results); break; + case ::bmh::layout::ManagerRatings: put(d, g.manager_ratings); break; + case ::bmh::layout::LeagueResults: put(d, g.results); break; + case ::bmh::layout::LeagueRoundCounters: put(d, g.league_rounds); break; + case ::bmh::layout::TacticsBoards: put(d, g.tactics); break; + case ::bmh::layout::StockExchange: put(d, g.stocks); break; + case ::bmh::layout::ManagerAutomation: put(d, g.manager_options); break; + case ::bmh::layout::Formations: put(d, g.formations); break; + case ::bmh::layout::ForeignClubStrength: put(d, g.foreign_strength); break; + case ::bmh::layout::Difficulty: d[0] = uint8_t(g.level); break; + case ::bmh::layout::CalendarDay: put32(d, 0, g.date); break; + case ::bmh::layout::DaysIntoSeason: d[0] = uint8_t(g.date - g.season_start), d[1] = uint8_t((g.date - g.season_start) >> 8); break; + case ::bmh::layout::PlayerDevelopmentBalance: put32(d, 0, uint32_t(g.development_balance)); break; + case ::bmh::layout::SeasonIndex: d[0] = uint8_t(g.season), d[1] = uint8_t(uint16_t(g.season) >> 8); break; + default: break; + } + } + stream.insert(stream.end(), d.begin(), d.end()); + } + for (const std::vector* pool : {&g.club_names, &g.player_names, &g.referee_names, &g.stadium_names}) { + stream.push_back(uint8_t(pool->size())); + stream.push_back(uint8_t(pool->size() >> 8)); + stream.insert(stream.end(), pool->begin(), pool->end()); + } + // the English cup memory has no place in the original layout: OpenBMH extension + std::vector extension; + for (const auto& [at, size] : kEnglishCompetitionBlocks) + if (g.memory.has(at) && g.memory.has(at + size - 1)) { + Bytes bytes(size); + for (uint32_t i = 0; i < size; ++i) bytes[i] = g.memory.u8(at + i); + extension.push_back({at, std::move(bytes)}); + } + append_save_extension(stream, extension); + return stream; +} + +Bytes save_header(const ModernState& g) { + const int managers = g.memory.u8(::bmh::layout::ManagerCount); + Bytes h; + h.push_back(uint8_t(managers)); + const std::string date = date_text(g.date, g.display_start_year); + for (size_t i = 0; i < 11; i++) h.push_back(i < date.size() ? uint8_t(date[i]) : 0); + Bytes list(0xa0, 0); + for (int m = 0; m < managers && m < 4; m++) { + const size_t rec = size_t(m) * 0xb0c; + const int team = int16_t(g.manager_records.at(rec + 0x290) | g.manager_records.at(rec + 0x291) << 8); + const bool national = team == no_team(); + const size_t at = size_t(m) * 0x28; + list[at] = national ? 0x1e : g.manager_records.at(rec + 0x210); // (0x1e: high byte of the loop word) + list[at + 1] = national ? 1 : 0; + for (size_t i = 0; i < 0x13; i++) list[at + 2 + i] = g.manager_records.at(rec + 0xa8 + i); + const size_t name = g.club_ids.at(size_t(team)); + for (size_t i = 0; i < 0x13 && name + i < g.club_names.size(); i++) list[at + 0x15 + i] = g.club_names[name + i]; + } + h.insert(h.end(), list.begin(), list.end()); + return h; +} + +Savegame make_savegame(const ModernState& g, WatcomRandom& rand) { + Savegame s; + s.plain_header = modern::save_header(g); + s.id1 = 0; + s.version = "V2.24"; + const uint32_t hi = uint32_t(rand.range(0, 0x8fff)), lo = uint32_t(rand.range(0, 0x8fff)); + s.id2 = lo + hi * 0x10000 + 1; + s.key = uint8_t(rand.range(0, 0xff) + 'n'); + s.random = uint8_t(rand.range(0, 0xff)); + s.stream = modern::save_stream(g); + uint8_t sum = s.key; + for (uint8_t b : s.stream) sum = uint8_t(sum + b); + s.checksum = sum; + s.checksum_ok = true; + return s; +} + +Bytes savegame_bytes(const Savegame& s) { + Bytes out = s.plain_header; + static const char magic[10] = {'K', 'R', 'O', 'N', '_', 'F', 'B', 'M', 0, 'k'}; + out.insert(out.end(), magic, magic + 10); + for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id1 >> (8 * i))); + for (size_t i = 0; i < 6; i++) out.push_back(i < s.version.size() ? uint8_t(s.version[i]) : 0); + for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id2 >> (8 * i))); + out.push_back(s.random); + out.push_back(s.key); + Bytes enc = s.stream; + fbm_encrypt(enc.data(), enc.size(), s.key); + out.insert(out.end(), enc.begin(), enc.end()); + out.push_back(s.checksum); + return out; +} + +void write_savegame(const std::filesystem::path& path, const Savegame& s) { + const Bytes b = modern::savegame_bytes(s); + std::ofstream f(path, std::ios::binary | std::ios::trunc); + if (!f) throw FormatError("cannot write " + path.string()); + f.write(reinterpret_cast(b.data()), std::streamsize(b.size())); + const bool written = bool(f); + f.close(); + // Buffered final bytes can fail only at close, after write reported the + // complete size. The autosave caller must not publish that temporary file. + if (!written || !f) throw FormatError("short write " + path.string()); +} + +} // namespace bmh::modern diff --git a/src/modern/game/save.hpp b/src/modern/game/save.hpp new file mode 100644 index 0000000..094b68e --- /dev/null +++ b/src/modern/game/save.hpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/save.hpp" +// Writing savegames (MakeSavegame with FbmDecrypt2 and NationalCoachAfterLoad). +// +// A ModernState keeps part of the savegame in typed fields (players, squads, records, ...) +// and the rest in StaticMemory; save_stream puts both back into the block order of the +// original, so that loading a savegame and saving it again gives the same stream. + +#include +#include + +#include "formats/binary.hpp" +#include "formats/fbm.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// The decrypted stream of a savegame: the 125 state blocks (NationalCoachAfterLoad, with the club +// records when their pointer ClubSeasonRecords is set) and the four name pools. +Bytes save_stream(const ModernState& g); + +// FbmDecrypt2: the plain header read by the load list - the number of managers, the date +// ("TT.MM.JJJJ") and per manager (0x28 bytes): start league, national team flag, his name +// and his club's name (0x13 bytes each). The original leaves stack bytes in the unused +// parts; they are zero here. +Bytes save_header(const ModernState& g); + +// MakeSavegame from the header on: "KRON_FBM", the previous id (here 0), "V2.24", the new +// id W(0, 0x8fff) << 16 + W(0, 0x8fff) + 1, the key byte W(0, 0xff) + 'n' and a random byte +// W(0, 0xff) (the four Watcom draws of saving), the encrypted stream and its checksum. +Savegame make_savegame(const ModernState& g, WatcomRandom& rand); + +// The file bytes of a savegame (inverse of load_savegame). +Bytes savegame_bytes(const Savegame& s); +void write_savegame(const std::filesystem::path& path, const Savegame& s); + +} // namespace bmh::modern diff --git a/src/modern/game/season.cpp b/src/modern/game/season.cpp new file mode 100644 index 0000000..9a5662b --- /dev/null +++ b/src/modern/game/season.cpp @@ -0,0 +1,1687 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/environment.hpp" +#include "modern/game/season.hpp" + +#include +#include +#include +#include +#include + +#include "modern/game/career.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/month.hpp" +#include "modern/game/national.hpp" +#include "modern/game/cup.hpp" +#include "game/lineup.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "game/messages.hpp" +#include "modern/game/prediction.hpp" +#include "modern/game/week.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { + +namespace { + +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 entries of 0x58 bytes +constexpr uint32_t kListEntry = 0x58; +constexpr uint32_t kOffers = ::bmh::layout::OfferSlots; // OfferSlots: 4 offers, -1 = free +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; + +uint32_t board32(const ModernState& g, size_t at) { + return uint32_t(g.tactics.at(at) | g.tactics.at(at + 1) << 8 | g.tactics.at(at + 2) << 16) | + uint32_t(g.tactics.at(at + 3)) << 24; +} + +} // namespace + +void answer_offers(ModernState& g, int manager, bool accept, WatcomRandom& rand, MinuteReport& report, GameRandom* game) { + StaticMemory& mem = g.memory; + const int team = g.manager_teams.at(size_t(manager)); + const SquadRange range = squad_range(team); + for (uint32_t k = 0; k < 4; k++) { + const uint32_t offer = mem.u32(kOffers + k * 4); + if (offer == 0xFFFFFFFFu || int(offer & 0x1f) != manager) continue; + const int player = int(offer >> 10) & 0xFFF; + size_t slot = range.first; + while (slot < range.first + range.count && (g.squad_slots.at(slot) & 0xFFF) != player) slot++; + if (slot != range.first + range.count) { + const uint32_t e = kTransferList + (0x28 + k) * kListEntry; + const size_t board = size_t(manager) * kBoard + (slot - range.first) * kBoardSlot; + if (!(offer & 0x80000000u)) { + if (!game) { + report.fail("an offer for a player: the transfer (IncomingTransferScreen)"); + return; + } + // Opening the negotiation restarts the game generator and picks the negotiator. + game->set_seed(int32_t(mem.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + game->range(0x5c, 0x6c); + // The fee offer is decided on its own (GameState::transfer_decision); `accept` + // answers the salary demands below. Without a controller the manager refuses + // the release, as in all recordings of the original. + const int offered_by = int16_t(mem.u16(e)); + const bool sell = g.transfer_decision && + g.transfer_decision(g, manager, player, offered_by, int32_t(mem.u32(e + 0x1c)), + int32_t(mem.u32(e + 0x0c))); + if (sell) { + const int buyer = offered_by; + if (buyer >= 0) { + const SquadRange target = squad_range(buyer); + size_t free = target.first; + while (free < target.first + target.count && g.squad_slots.at(free) != 0x0fff) free++; + if (free < target.first + target.count) { + if (!modern::remove_from_seller(g, team, player, report)) return; + g.squad_slots.at(free) = uint16_t(player); + modern::book_money(g, manager, -int32_t(mem.u32(e + 0x1c)), true, true); + modern::lineup_after_transfer(g, team); + modern::lineup_after_transfer(g, buyer); + } + } + } + g.squad_slots.at(transfer_list_slot() + 0x28 + k) = 0x0FFF; + mem.set32(kOffers + k * 4, 0xFFFFFFFFu); + continue; + } + // " fordert ein Gehalt von X EU - sonst nutzt er seine Ausstiegsklausel!" + if (!accept) { + if (!game) { + report.fail("a salary demand declined: the player leaves (IncomingTransferScreen)"); + return; + } + // "NEIN": IncomingTransferScreen opens the negotiation ("Entscheidung") like for a fee + // offer - the game generator restarts, the negotiator is drawn - and the + // manager refuses the release (right click): the offer is gone, the player + // stays (confirmed by the game 1 and 2P recordings against the original) + game->set_seed(int32_t(mem.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + game->range(0x5c, 0x6c); + g.squad_slots.at(transfer_list_slot() + 0x28 + k) = 0x0FFF; + mem.set32(kOffers + k * 4, 0xFFFFFFFFu); + continue; + } + if (!(offer & 0x20)) { + // the new salary and its percentage of the market salary (AddToSquad with + // 98 % and the contract years left) + uint32_t fee = 0, salary = 0; + modern::market_value(g, int(slot), 0, 0x62, fee, salary, (g.tactics.at(board + 0xc) + 6) / 0xc, 0, rand); + const uint32_t offered = mem.u32(e + 0xc); + for (int i = 0; i < 4; i++) g.tactics.at(board + 0x50 + size_t(i)) = uint8_t(offered >> (8 * i)); + // Deliberate deviation (#40): the original stores the percentage in the mood + // byte without a limit, so a raise to more than 255 % of the market salary + // (a rival's offer against few months left) wraps it to almost 0 - the player + // then asks for next to nothing at his renewal (60.900 -> 8.500 in the QA). + // Purchase and renewal clamp the same byte to 255; here too. + g.tactics.at(board + 0xd) = uint8_t(std::min(offered * 100 / salary, 0xff)); + } + } + g.squad_slots.at(transfer_list_slot() + 0x28 + k) = 0x0FFF; + mem.set32(kOffers + k * 4, 0xFFFFFFFFu); + } + (void)board32; +} + +void free_offer_slots(ModernState& g) { + for (size_t k = 0; k < 4; k++) g.squad_slots.at(transfer_list_slot() + 0x28 + k) = 0x0FFF; + for (uint32_t k = 0; k < 4; k++) g.memory.set32(kOffers + k * 4, 0xFFFFFFFFu); +} + +void reset_club_moods(ModernState& g, GameRandom& game, WatcomRandom& rand, bool new_career) { + const StaticMemory& mem = g.memory; + // the title holders (cup table entries 0, 15, 19 and 21, +0x22) start at the top + const uint16_t holders[4] = {mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4), mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField), mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6), mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5)}; + rand.range(0, 2); // local_18, a counter that is not used + for (size_t team = 0; team < g.team_flags.size(); team++) { + g.team_morale.at(team) = uint8_t((g.team_morale.at(team) & 0xc0) | rand.range(0x14, 0x1e)); + g.team_flags.at(team) = uint16_t(game.range(0, 2) * 2); + int high = 3, low = 0; // iVar7 (bits 14-15), iVar8 (bits 12-13) + if (new_career) { + high = 1, low = 1; // their initial values, never changed in this mode + } else if (std::find(std::begin(holders), std::end(holders), uint16_t(team)) == std::end(holders)) { + const int pos = int16_t(modern::table_position(g, int(team))); // TablePosition + high = std::max(3 - pos / 6, 0); + if (rand.range(0, 4) == 0) high = rand.range(0, 3); + low = std::min(pos / 5, 3); + if (rand.range(0, 6) == 0) low = rand.range(0, 3); + } + g.team_flags.at(team) = uint16_t(g.team_flags.at(team) | low << 12 | high << 14); + modern::club_balance(g, int(team), rand); // CareerSeasonSetup4 + } +} + +void club_balance(ModernState& g, int team, WatcomRandom& rand) { + // condition against technique of the whole squad, defence against attack, each shaken a + // little and cut to 51..149 %, give bits 8-9 and 10-11 of the club flags + const int a1 = team_average(g, team, 0xf1, &rand).value; + const int a2 = team_average(g, team, 0xf2, &rand).value; + const int a3 = team_average(g, team, 0x2f, &rand).value; + const int a4 = team_average(g, team, 0x8f, &rand).value; + uint32_t c = uint32_t(a1 * 100) / uint32_t(a2); + uint32_t d = uint32_t(a3 * 100) / uint32_t(a4); + c = (c & 0xffff) - uint32_t(int(c & 0xffff) / rand.range(2, 7)); + d = uint32_t(int(d & 0xffff) / rand.range(2, 6)) + (d & 0xffff); + const int cc = std::clamp(int(int16_t(c)), 0x33, 0x95); // ClampInteger + const int dd = std::clamp(int(int16_t(d)), 0x33, 0x95); + uint16_t f = uint16_t(g.team_flags.at(size_t(team)) & 0xf0ff); + f = uint16_t(f | ((cc - 0x32) / 0x19) << 8 | ((dd - 0x32) / 0x19) << 10); + g.team_flags.at(size_t(team)) = f; +} + +namespace { + +// TeamLeague2: the league of a club; ids above 0x164 (national teams) count as league 0 +int club_league(int team) { return team > 0x164 ? 0 : team_league(team); } + +// The European entrants (Career_CompetitionPointersEnglish_ExecutableField25 UEFA Cup, Career_CompetitionPointersEnglish_RuntimeField14 Champions League, +// Career_CompetitionPointersEnglish_ExecutableField19 Cup Winners' Cup) and their counts (Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3). +struct Entrants { + StaticMemory& mem; + static constexpr uint32_t kList[3] = {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}; + static constexpr uint32_t kCount[3] = {::bmh::layout::Career_EuropeanClub_ExecutableField, ::bmh::layout::Career_EuropeanClub_ExecutableField2, ::bmh::layout::Career_EuropeanClub_ExecutableField3}; + // EuropeanClub: 1 UEFA Cup, 2 Champions League, 3 Cup Winners' Cup, 0 none + int find(int team) const { + for (int l = 0; l < 3; l++) + for (int i = 0; i < int(int8_t(mem.u8(kCount[l]))); i++) + if (mem.u16(kList[l] + uint32_t(i) * 2) == uint16_t(team)) return l + 1; + return 0; + } + void add(int l, int team) { + const int n = int8_t(mem.u8(kCount[l])); + mem.set16(kList[l] + uint32_t(n) * 2, uint16_t(team)); + mem.set8(kCount[l], uint8_t(n + 1)); + } +}; + +// OnTableJust(league, rank, ranks): the club with that final rank (0 if none) +int club_at_rank(int league, int rank, const uint8_t* ranks) { + for (int i = 0; i < kLeagueSizes[league]; i++) + if (ranks[i] == rank) return league_first_team(league) + i; + return 0; +} + +// LeagueEntrants(league, cup winner, cup finalist, uefa places): the European places of a +// league - its champion (and the Champions League holder if he plays there, else the +// runner-up), the cup winner (or the finalist) and the cup winners' cup holder, the UEFA +// Cup holder and `uefa` more clubs by rank. Human managers note where they play. +void league_entrants(ModernState& g, int league, int winner, int finalist, int uefa) { + StaticMemory& mem = g.memory; + Entrants en{mem}; + const LeagueTable t = compute_league_table(g, league, 0, league_matchdays(league), 7, 1); + uint8_t ranks[24] = {}; + for (int i = 0; i < t.size; i++) ranks[i] = uint8_t(t.rank(i)); + en.add(1, club_at_rank(league, 0, ranks)); + const int cl_holder = mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5); + if (club_league(cl_holder) == league) en.add(1, en.find(cl_holder) == 0 ? cl_holder : club_at_rank(league, 1, ranks)); + if (en.find(winner) == 0) en.add(2, winner); + else if (en.find(finalist) == 0) en.add(2, finalist); + const int cw_holder = mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6); + if (club_league(cw_holder) == league) { + if (en.find(cw_holder) == 0) en.add(2, cw_holder); + else if (en.find(finalist) == 0) en.add(2, finalist); + } + const int uefa_holder = mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4); + if (club_league(uefa_holder) == league) { + if (en.find(uefa_holder) == 0) en.add(0, uefa_holder); + else uefa++; + } + for (int rank = 1; uefa != 0; rank++) { + const int team = club_at_rank(league, rank, ranks); + if (en.find(team) == 0) { + en.add(0, team); + uefa--; + } + } + static const uint8_t kRound[3] = {1, 3, 2}; // SeasonRuntimeField + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const int kind = en.find(g.manager_teams[m]); + if (kind == 0) continue; + // ManagerOf(manager, 2, ...): the European campaign of this season + const size_t at = m * 0xB0C + 0xda + 2 + size_t(std::min(g.season, 0x31)) * 3; + g.manager_records.at(at) = uint8_t(kRound[kind - 1] + (kind - 1) * 0x20); + } +} + +// CareerSeasonSetup(1) up to the German entrants: the cup tables restart, the international +// tournament of the year (competition 7 - season % 4, national teams from id 357) is drawn +// and the European entrants are found (SeasonEntrantsFromGame). +void observe_initial_international_groups(ModernState& g, WatcomRandom& rand, int competition, + const SeasonCupDrawHook& hook) { + StaticMemory& mem = g.memory; + const int first = modern::find_cup(mem, competition); + int group_ordinal = 0; + for (int index = first; index >= 0;) { + const uint32_t entry = modern::cup_entry_address(index); + SeasonCupDrawEvent event; + event.entry_address = entry; + event.competition = competition; + event.flags = mem.u8(entry + 0x14); + event.group_stage = (event.flags & 4) == 0; + event.group_index = group_ordinal; + event.group_count = mem.u8(entry + 0x1e) & 0xf; + event.round = modern::cup_round(mem, index); + event.offset = 0; + event.count = mem.u8(entry + 0x1a); + const uint32_t list = mem.pointer(entry); + event.participants.reserve(event.count); + for (size_t i = 0; i < event.count; ++i) event.participants.push_back(mem.u16(list + uint32_t(i) * 2)); + event.phase = SeasonCupDrawPhase::draw; + if (hook) hook(g, event); + event.phase = SeasonCupDrawPhase::overview; + modern::cup_group_overview_effects(g, event.group_index); + if(event.group_stage) { + const int schedule_teams=modern::cup_group_schedule_teams(mem,entry); + const int rounds=mem.u8(entry+0x1b)/((event.flags&1)+1); + const uint32_t teams=mem.pointer(entry); + for(const Fixture& fixture:generate_fixtures(schedule_teams,event.round+1,rounds,0)) { + for(int position:{fixture.home,fixture.away}) { + const int team=mem.u16(teams+uint32_t(position)*2); + const bool manager_national=mem.has(::bmh::layout::CupDraw_FormatError_RuntimeField2)&&mem.has(::bmh::layout::CupDraw_FormatError_RuntimeField3)&& + mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField2)==no_team()&&mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)==team; + const bool human_owned=g.manager_of(team)>=0||manager_national; + if(team blocks[8] = {{::bmh::layout::Career_CompetitionPointers_ExecutableField, 0x7e}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22, 0x80}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23, 0x80}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17, 0x9a}, + {::bmh::layout::Savestate_Layout_ExecutableField4, 0x62}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26, 0x40}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21, 0x40}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13, 0x68}}; + for (const auto& [at, size] : blocks) + for (uint32_t i = 0; i < size; i++) + if (mem.has(at + i)) mem.set8(at + i, 0xcc); + if (mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31)) mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, 0xcccc); + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (size_t i = 0; i < 2; i++) g.manager_records.at(m * 0xB0C + 0xdb + size_t(g.season) * 3 + i) = 0; + // the international tournament: its host (or last winner and finalist) and more teams + // drawn from four pools, none twice and none of the last field + static const uint8_t kPoolFixed[16] = {2, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 0, 10, 4, 8, 0}; // SeasonRuntimeField2 + static const uint8_t kField[4] = {4, 8, 6, 24}; // SeasonRuntimeField3 + static const uint8_t kPoolFrom[4] = {0x00, 0x0f, 0x20, 0x2f}; // SeasonRuntimeField4 + static const uint8_t kPoolTo[4] = {0x0f, 0x20, 0x2f, 0x3e}; // SeasonRuntimeField5 + constexpr uint32_t kField0 = ::bmh::layout::Field0; + if (!mem.has(kField0)) mem.add_block(kField0, 0x30); + const int s = g.season % 4; + const int base = no_team(); // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 + int n = 1; + std::vector last; + if (s % 2 == 0) { + mem.set16(kField0, uint16_t(base)); + } else { + const uint32_t e = modern::cup_entry_address(0xe - s / 2); + const int count = mem.u8(e + 0x1a); + for (int i = 0; i < count; i++) last.push_back(mem.u16(kField0 + uint32_t(i) * 2)); + mem.set16(kField0, mem.u16(e + 0x22)); + if (mem.u8(e + 0x1f) == 2) mem.set16(kField0 + 2, mem.u16(e + 0x24)), n = 2; + } + for (int k = 0; k < 4; k++) { + const int fixed = kPoolFixed[k + s * 4]; + int left = fixed != 0 ? rand.range(fixed - 2, fixed) : kField[s] - n; + while (int16_t(left) != 0) { + const uint16_t t = uint16_t(rand.range(base + kPoolFrom[k], kPoolTo[k] + base - 1)); + mem.set16(kField0 + uint32_t(n) * 2, t); + bool twice = false; + for (int i = 0; i < n && !twice; i++) twice = mem.u16(kField0 + uint32_t(i) * 2) == t; + if (!twice && std::find(last.begin(), last.end(), t) == last.end()) n++, left--; + } + } + for (uint32_t i = 0; i < kField[s]; i++) { // PrepareEvent + const uint32_t j = uint32_t(game.range(0, kField[s] - 1)); + const uint16_t a = mem.u16(kField0 + i * 2); + mem.set16(kField0 + i * 2, mem.u16(kField0 + j * 2)); + mem.set16(kField0 + j * 2, a); + } + // CupDrawFromGame(entry of competition 7 - s): the draw of the tournament's first round, + // shown unless switched off + const int shown_type = 7 - s; + if (mem.u8(::bmh::layout::LeaguePresentationOptions + uint32_t(shown_type + 5) * 9) == 0) + observe_initial_international_groups(g, rand, shown_type, cup_draw); + // SeasonEntrantsFromGame: the entrants of the first division (cup winner and finalist) and of + // the four foreign leagues (two random clubs), then the holders not placed yet + Entrants en{mem}; + mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField, 0), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField3, 0), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField2, 0); + static const uint8_t kLeague[5] = {0, 5, 6, 7, 8}; // SeasonRuntimeField6 + static const uint8_t kUefa[5] = {4, 4, 4, 4, 3}; // SeasonRuntimeField7 + for (int u = 0; u < 5; u++) { + int a = 0, b = 0; + if (u == 0) { + // the national cup winner and finalist (+0x22/+0x24): entry 0, in the English + // structure the FA Cup proper, entry 28 (U16: SeasonRuntimeField8/83c) + const uint32_t cup = kEnglishCompetitions ? ::bmh::layout::CupTable + 28 * 0x28 : ::bmh::layout::CupTable; + a = mem.u16(cup + 0x22), b = mem.u16(cup + 0x24); + if (mem.has(::bmh::layout::Season_CareerSeasonSetup_RuntimeField7)) mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField7, uint16_t(a)); + } else { + a = rand.range(0, kLeagueSizes[kLeague[u]] - 1); + do b = rand.range(0, kLeagueSizes[kLeague[u]] - 1); while (b == a); + } + const int first = kLeague[u] == 0 ? 0 : league_first_team(kLeague[u]); + league_entrants(g, kLeague[u], uint8_t(a + first), uint8_t(b + first), kUefa[u]); + } + const int holders[3][2] = {{0, mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4)}, {1, mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5)}, {2, mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6)}}; + for (const auto& h : holders) + if (en.find(h[1]) == 0) en.add(h[0], h[1]); + // CompetitionWinnerScreen(1, 2..4, list, count): the German clubs in each competition are shown + // (the first pause of the recording) +} + +// The rest of CareerSeasonSetup(1): the three European fields are filled up with foreign +// clubs (from id 168 on, one of every block of seven, none twice), shuffled +// (PrepareEvent) and their first rounds shown (CupDrawFromGame, no draws while switched off): +// Cup Winners' Cup to SeasonRuntimeField9 (32), Champions League to 24, UEFA Cup to +// SeasonRuntimeField10 (64, two per block after the first 16 blocks). +void european_fields(ModernState& g, GameRandom& game, WatcomRandom& rand) { + StaticMemory& mem = g.memory; + Entrants en{mem}; + const int pool = first_foreign_cup(); // CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6: the first foreign club + auto pick = [&](int from) { + int t; + do t = rand.range(from, from + 6); while (en.find(t) != 0); + return t; + }; + auto shuffle = [&](uint32_t list, int n) { // PrepareEvent + for (uint32_t i = 0; i < uint32_t(n); i++) { + const uint32_t j = uint32_t(game.range(0, n - 1)); + const uint16_t a = mem.u16(list + i * 2); + mem.set16(list + i * 2, mem.u16(list + j * 2)); + mem.set16(list + j * 2, a); + } + }; + int from = pool; + for (int i = int8_t(mem.u8(::bmh::layout::Career_EuropeanClub_ExecutableField3)); i < 0x20; i++, from += 7) en.add(2, pick(from)); + shuffle(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, 0x20); + from = pool; + for (int i = int8_t(mem.u8(::bmh::layout::Career_EuropeanClub_ExecutableField2)); i < 0x18; i++, from += 7) en.add(1, pick(from)); + shuffle(mem.pointer(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5), 0x10); // (the team list of cup entry 16, Career_CompetitionPointersEnglish_ExecutableField5) + from = pool; + const int start = int8_t(mem.u8(::bmh::layout::Career_EuropeanClub_ExecutableField)); + int per = 2; + for (int i = start; i < 0x40; i++, from += 7) { + for (int k = 0; k < per; k++) en.add(0, pick(from)); + if (i - start == 0x10) per = 1; + } + shuffle(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, 0x40); + mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField, 0x40), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField2, 0x18), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField3, 0x20); +} + +int32_t rec32(const ModernState& g, int m, size_t o) { + const size_t at = size_t(m) * 0xB0C + o; + return int32_t(uint32_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8 | g.manager_records.at(at + 2) << 16) | + uint32_t(g.manager_records.at(at + 3)) << 24); +} +void set_rec32(ModernState& g, int m, size_t o, int32_t v) { + for (size_t i = 0; i < 4; i++) g.manager_records.at(size_t(m) * 0xB0C + o + i) = uint8_t(uint32_t(v) >> (8 * i)); +} +uint8_t& rec8(ModernState& g, int m, size_t o) { return g.manager_records.at(size_t(m) * 0xB0C + o); } +uint16_t mem_u16(const ModernState& g, uint32_t a) { return g.memory.u16(a); } + +// HighscoreScore(mask, 0, 0xff): bit 0 the account (+0x314), 1 the deposit (+0x318), 2 the +// fixed deposits (Advertising_OriginalShareAdjustment_RuntimeField x FundBlock), 3 the shares (block StockExchange), 4 the credits: with +// mask 0x10 alone what is still owed (Analytics_SourceAssetMaskE_RuntimeField - bd720), otherwise minus the amounts +int32_t assets(const ModernState& g, int m, int mask) { + const StaticMemory& mem = g.memory; + int32_t sum = 0; + if (mask & 1) sum += rec32(g, m, 0x314); + if (mask & 2) sum += rec32(g, m, 0x318); + if (mask & 4) + for (uint32_t k = 0; k < 6; k++) + sum += int32_t(mem.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + k * 0x1c) * mem.u32(::bmh::layout::FundBlock + k * 0x1c)); + if (mask & 8) + for (size_t k = 0; k < 12; k++) + sum += int32_t(uint32_t(g.stocks.at(k * 0x5c + 0x50 + size_t(m) * 2) | g.stocks.at(k * 0x5c + 0x51 + size_t(m) * 2) << 8) * + uint32_t(g.stocks.at(k * 0x5c + 0x4e) | g.stocks.at(k * 0x5c + 0x4f) << 8)); + if (mask & 0x10) + for (uint32_t b = 0; b < 5; b++) { + const uint32_t at = ::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(m) * 0x78 + b * 0x18; + sum += mask == 0x10 ? int32_t(mem.u32(at) - mem.u32(at + 0x10)) : -int32_t(mem.u32(at)); + } + return sum; +} + +// ClubAttraction(club, pay): how popular a club is (0..100) - its European campaign, the +// championship and the cups it holds, its strength and position. With `pay` the +// manager (ActiveManager) gets the premiums for the titles (messages, record +0x874). +int club_popularity(ModernState& g, int m, int team, bool pay) { + StaticMemory& mem = g.memory; + Entrants en{mem}; + static const uint8_t kKind[4] = {0, 1, 3, 2}; // SeasonRuntimeField11 + static const uint8_t kEntry[4] = {0x00, 0x0f, 0x13, 0x15}; // SeasonRuntimeField12 + static const uint8_t kPlus[4] = {0x14, 0x1e, 0x14, 0x0f}; // SeasonRuntimeField13 + static const int32_t kPremium[4] = {500000, 1500000, 2500000, 1500000}; // SeasonRuntimeField14 + int8_t p = int8_t(kKind[en.find(team)] * 10 + 10); + if (team == mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6)) { + if (pay) { + post_composed(g, m, kChampionshipBonusText); // ChampionshipBonusText + modern::book_money(g, m, -700000, true); + set_rec32(g, m, 0x874, rec32(g, m, 0x874) + 1000000); + } + p = int8_t(p + 10); + } + for (int k = 0; k < 4; k++) { + if (team != mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField + uint32_t(kEntry[k]) * 0x28)) continue; + p = int8_t(p + kPlus[k]); + if (pay) { + post_composed(g, m, message_text(g, ::bmh::layout::Season_ClubPopularity_TextPointer) + message_text(g, ::bmh::layout::CupDraw_FormatError_ExecutableField6 + uint32_t(k) * 4) + + message_text(g, ::bmh::layout::Season_ClubPopularity_TextPointer2) + format_amount(g, kPremium[k]) + "."); + modern::book_money(g, m, -kPremium[k], true); + set_rec32(g, m, 0x874, rec32(g, m, 0x874) + kPremium[k]); + } + } + const int avg = team_average(g, team, 0xff).value; + int pos = int8_t(modern::table_position(g, team)); + if (pos == -1) pos = 10; + int league = club_league(team); + if (int8_t(league) > 2) league--; + int v = int16_t((int(p) << 2) / 5) + int16_t(uint32_t(uint16_t((4 - int8_t(league)) * 0x16 + (0x14 - int8_t(pos)))) * 0x28 / 0x6c) + + int16_t(uint32_t(uint16_t(avg)) * 2 / 10); + return std::clamp(int(int16_t(v)), 0, 100); // ClampInteger +} + +// CareerSeasonSetup2(manager): the season tickets - popularity above the league's base plus +// W(0, 10) in steps of 300 on top of the base number (SeasonRuntimeField15), less 5 % per game +// level, sold at the league's price (SeasonRuntimeField16); record +0x2ac, +0x754, +0x868 +void season_tickets(ModernState& g, int m, WatcomRandom& rand) { + static const uint8_t kBase[5] = {50, 40, 30, 30, 20}; // SeasonRuntimeField17 + static const uint16_t kTickets[5] = {5000, 2000, 1000, 1000, 300}; // SeasonRuntimeField15 + static const uint16_t kPrice[5] = {330, 270, 240, 240, 225}; // SeasonRuntimeField16 + const int team = g.manager_teams.at(size_t(m)); + const int league = std::min(club_league(team), 4); + const int pop = club_popularity(g, m, team, true); + const int low = std::max(pop - kBase[league], 0); + const int r = rand.range(low, low + 10); + const int sold = ((100 - g.level * 5) * (kTickets[league] + r * 300)) / 100; + g.manager_records.at(size_t(m) * 0xB0C + 0x2ac) = uint8_t(sold); + g.manager_records.at(size_t(m) * 0xB0C + 0x2ad) = uint8_t(sold >> 8); + const int32_t income = int32_t(kPrice[league]) * int16_t(sold); + modern::book_money(g, m, -income, true); + set_rec32(g, m, 0x754, rec32(g, m, 0x754) + income); + set_rec32(g, m, 0x868, rec32(g, m, 0x868) + income); + post_composed(g, m, message_text(g, ::bmh::layout::Season_SeasonTickets_TextPointer) + format_number(g, int16_t(sold), 1) + message_text(g, ::bmh::layout::Season_SeasonTickets_TextPointer2) + + format_amount(g, income) + message_text(g, ::bmh::layout::Season_SeasonTickets_TextPointer3)); +} + +// SeasonEvent: a random event of the summer (a bonus, a fine, ...) for a manager whose +// finances went badly; otherwise only its draw is spent +void season_event(ModernState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + const int32_t worth = assets(g, m, 0xf) - assets(g, m, 0x10) + game.range(500000, 1000000); + // Int64T: bankrupt, or out of credit + const uint8_t cut = rec8(g, m, 0x220); + const int32_t total = int32_t(rec8(g, m, 0x26f)) * 80000 + (assets(g, m, 0xf) - assets(g, m, 0x10)); + if (total < -6000000 || ((cut >> 5) == 2 && int32_t(cut & 0x1f) * 100000 <= rec32(g, m, 0x330))) return; + if (g.memory.u8(::bmh::layout::GameMode) < 3) set_rec32(g, m, 0x320, rec32(g, m, 0x314) - rec32(g, m, 0x324)); + bool poor = false; + int32_t w = worth; + if (rec32(g, m, 0x314) - rec32(g, m, 0x324) < rec32(g, m, 0x320) - 1000000) { + poor = true; + if (rec8(g, m, 0x26f) < 0x3c) w -= 1500000; + } + if ((!poor || rand.range(0, 1) == 0) && w + int32_t(rec8(g, m, 0x26f)) * 80000 > -3000001) return; + (void)report; + // The board's sanction (kind G(0, 3)): 0 and 2 last n weeks/points, 1 cuts the credit line + // to n * 100000, 3 is a fine paid at once. Ranges SeasonRuntimeField18 / SeasonRuntimeField19, factor + // SeasonRuntimeField20 (above 1: thousands of money). + static const int kMin[4] = {4, 8, 2, 4}, kMax[4] = {8, 15, 6, 10}, kFactor[4] = {1, 100, 1, 50}; + const int kind = game.range(0, 3); + std::string text = kind == 0 || kind == 3 ? message_text(g, ::bmh::layout::Season_SeasonEvent_TextPointer3) : std::string(); + int n = game.range(kMin[kind], kMax[kind]); + int32_t value = kFactor[kind] * n; + if (kFactor[kind] > 1) value *= 1000; + text += message_text(g, ::bmh::layout::Season_SeasonEvent_TextPointer + uint32_t(kind) * 4); // Season_SeasonEvent_TextPointer[kind] + // FormatNumber: the number (an amount of money for kinds 1 and 3), then Season_SeasonEvent_TextPointer2[kind] + text += format_number(g, value, kind == 1 || kind == 3 ? 0x101 : 1) + message_text(g, ::bmh::layout::Season_SeasonEvent_TextPointer2 + uint32_t(kind) * 4); + if (kind == 0) n--; + if (kind == 3) { + modern::book_money(g, m, value, true, true); // FinanceStatisticsEnabled = 1: into the statistics + } else { + // Season_SeasonAccounts_RuntimeField[manager]: becomes the record's sanction byte +0x220 at the season change + if (!g.memory.has(::bmh::layout::Season_SeasonAccounts_RuntimeField)) g.memory.add_block(::bmh::layout::Season_SeasonAccounts_RuntimeField, 4); + g.memory.set8(::bmh::layout::Season_SeasonAccounts_RuntimeField + uint32_t(m), uint8_t(n | (kind + 1) << 5)); + } + post_composed(g, m, text); // PostMessage +} + +} // namespace + +int32_t season_profit_tax(int32_t profit) { + // GameEndTaxAnimationScreen/SeasonProfitTax: six progressive bands. The original rounds the + // annual result to 100 EU before this point, divides each band by ten first, + // then multiplies by its 0..5 rate. Preserve that integer order. + if (profit <= 100000) return 0; + int32_t remaining = profit; + int32_t tax = 0; + for (int band = 0; band < 6 && remaining > 0; ++band) { + int32_t taxable = remaining; + if (band < 5 && taxable > 100000) taxable = 100000; + tax += (taxable / 10) * band; + remaining -= taxable; + } + return tax; +} + +int32_t season_profit_tax_refund(int32_t profit, int32_t previous_taxable_profit, + int32_t previous_tax_paid) { + if (profit >= 100000 || previous_taxable_profit <= 0 || previous_tax_paid <= 0 || + previous_taxable_profit / 100 == 0) + return 0; + // Keep GameEndTaxAnimationScreen's division and multiplication order. A malformed saved + // denominator is safely ignored; valid source values are rounded to 100 EU. + int32_t base = profit + previous_taxable_profit; + if (base < 200000) base = 200000; + int32_t retained_tax = (((previous_tax_paid / 100) * ((base - 200000) / 1000)) / + (previous_taxable_profit / 100)) * 1000; + if (retained_tax < 0) retained_tax = 0; + return std::max(previous_tax_paid - retained_tax, 0); +} + +void season_apply_profit_tax(ModernState& g, int manager, int32_t profit, + GameRandom& game, WatcomRandom& rand, + const SeasonTaxHooks& hooks, SeasonTaxState* continuation) { + if (profit <= 100000) return; + SeasonTaxEvent event; + event.manager_slot = manager; + event.team = g.manager_teams.at(size_t(manager)); + event.profit = profit; + event.legal_tax = modern::season_profit_tax(profit); + event.paid_tax = event.legal_tax; + event.fine = continuation ? continuation->carried_fine : 0; + // SystemIdentity is an acknowledgement, not PostMessage mailbox delivery. + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer) + format_amount(g, profit) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer2) + format_amount(g, event.legal_tax) + ")."; // SeasonRuntimeField21 + if (hooks.observe) hooks.observe(g, event); + event.kind = SeasonTaxEventKind::question; + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer3); + const bool adjust = hooks.choose && hooks.choose(g, event); + if (adjust) { + event.caught = game.range(1, 10) >= 10; + event.animation_variant = event.caught ? 4 : rand.range(1, 3); + event.kind = SeasonTaxEventKind::animation; + event.text.clear(); + if (hooks.observe) hooks.observe(g, event); + if (!event.caught) { + event.paid_tax = int32_t(uint32_t(event.legal_tax) * uint32_t(game.range(6, 9))) / 10; + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer6) + format_amount(g, event.legal_tax) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer7) + format_amount(g, event.paid_tax) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer8); + } else { + event.fine = rand.range(1, 3) * 100000; + if (continuation) continuation->carried_fine = event.fine; + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer4) + format_amount(g, event.fine) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer5); + // Source SeasonRuntimeField22: the last ten competition-4 ratings of this manager. + for (size_t i = 0; i < 10; ++i) + g.manager_ratings.at(size_t(manager) * 0x3c + 0x28 + i) = 0; + rec8(g, manager, 0x26f) = uint8_t(std::clamp(int(rec8(g, manager, 0x26f)) - 10, 0, 100)); + } + event.kind = SeasonTaxEventKind::outcome; + if (hooks.observe) hooks.observe(g, event); + } + // Both Source carries describe the tax, while the forced debit includes the fine. + set_rec32(g, manager, 0x328, event.paid_tax); + set_rec32(g, manager, 0x32c, profit); + modern::book_money(g, manager, event.paid_tax + event.fine, true); +} + +namespace { + +} // namespace + +// OpenBMH deviates from the original: retains the enhanced academy player-generation strength bands with monthly youth budgets. +// The middle youth budget enables the existing enhanced academy recruitment. +// Old lump-sum contracts remain eligible after their saved season payment. +// Player search, strength bands, age and board setup retain the shared rules. +bool youth_academy_player(ModernState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + const int team = g.manager_teams.at(size_t(m)); + const int league = club_league(team); + if (!modern::environment_academy_active(g, m)) return false; + if (modern::squad_count(g, team, 3) > 0x16) return false; + const auto budget = g.memory.u32(::bmh::layout::Spending + uint32_t(m) * 0x24 + kYouthAcademy * 4); + if (budget <= uint32_t(kEnvironmentStep[kYouthAcademy] * 6) && + g.memory.u8(::bmh::layout::CareerDuration) != 1 && + int(g.memory.u8(::bmh::layout::EnvironmentYouthTeams + uint32_t(m) * 0x24 + 2)) < + team_average(g, team, 0xf3).value - 25) + return false; + const SquadRange own = squad_range(team); + if (game.range(0, 0) != 0) return false; + for (int t = 0xf;; --t) { + for (int s = 0x86f; s >= 0; --s) { + const int club = s / 24; + if (g.manager_of(modern::slot_team(s)) >= 0) { + s -= 0x17; // the whole squad of a human manager + continue; + } + const int player = g.squad_slots.at(size_t(s)) & 0xfff; + if (player == 0xfff) continue; + bool loan = false; // BoughtEntry + for (int k = 0; k < 200 && !loan; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + loan = e != 0 && int(e & 0xfff) == player; + } + if (loan) continue; + const int age = int((g.players.at(size_t(player)).w364 >> 21) & 0x1f); + if (age > game.range(t, t + 3)) continue; + if (!modern::remove_from_seller(g, club, player, report)) return false; + static const int kLevel[4][2] = {{0x4f, 0x5f}, {0x45, 0x55}, {0x31, 0x44}, {0x1d, 0x30}}; + const int band = league == 0 ? 0 : league == 1 ? 1 : league < 4 ? 2 : 3; + const int level = game.range(kLevel[band][0], kLevel[band][1]); + modern::generate_player(g, player, level | 0x3000, game, rand); + // PendingOfferAnswer(manager, player | 0xf000, -1, squad start) + int slot = -1; + for (size_t q = own.first; q < own.first + 24 && slot < 0; q++) + if (g.squad_slots.at(q) == 0xfff) slot = int(q); + if (slot < 0) return false; // (the original shows PendingOffer_FormatError_ExecutableField) + g.squad_slots.at(size_t(slot)) = uint16_t(player); + modern::new_board_entry(g, m, slot - int(own.first), slot, rand); + g.tactics.at(size_t(m) * 0x840 + size_t(slot - int(own.first)) * 0x58 + 0xd) = 0x69; + uint32_t& w = g.players.at(size_t(player)).w364; + w = (w & 0xff00ffffu) | uint32_t(uint8_t(rand.range(0, 4) << 5)) << 16; + return true; + } + if (t == 0) return false; + } +} + +namespace { + +// GameEndTaxAnimationScreen for one manager (SeasonProfitTax repeats it for the others): the summer +// event, the players' season bonuses, the championship mark, the new credit line from +// the season's result, taxes on a profit and refunds, then the season tickets +void season_accounts(ModernState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const SeasonTaxHooks& tax_hooks, SeasonTaxState& tax_state) { + for (size_t i = 0; i < 0xc; i++) rec8(g, m, 0x754 + i) = 0; + modern::finish_youth_season(g, m); + if (!g.memory.has(::bmh::layout::Season_SeasonAccounts_RuntimeField)) g.memory.add_block(::bmh::layout::Season_SeasonAccounts_RuntimeField, 4); // (runtime only, not saved) + g.memory.set8(::bmh::layout::Season_SeasonAccounts_RuntimeField + uint32_t(m), 0); + season_event(g, m, game, rand, report); + if (report.unsupported) return; + const int team = g.manager_teams.at(size_t(m)); + rec8(g, m, 0x21f) = 0; + if (g.manager_teams.size() > 1) rec8(g, m, 0x21c) = 0; + const int pos = int16_t(modern::table_position(g, team)); + const int league = club_league(team); + const SquadRange range = squad_range(team); + for (size_t s = 0; s < 24; s++) + if (g.squad_slots.at(range.first + s) != 0x0FFF) modern::season_bonus(g, m, int(s), uint8_t(pos), true); + // OpenBMH deviates from the original: retains the enhanced academy player-generation strength bands with monthly youth budgets. + // Academy recruitment is posted after the youth season has settled. + if (modern::youth_academy_player(g, m, game, rand, report)) post_text(g, m, text_id(::bmh::layout::Season_SeasonAccounts_TextPointer)); + if (report.unsupported) return; + if (league == 0 && pos < 100) rec8(g, m, 0x21c) = 1; // the best human club of the first division + set_rec32(g, m, 0x324, rec32(g, m, 0x324) + rec32(g, m, 0x30c)); + set_rec32(g, m, 0x30c, 0); + const int32_t result = ((rec32(g, m, 0x314) - rec32(g, m, 0x324)) / 100) * 100; + const int32_t before = rec32(g, m, 0x320); + const int16_t step = int16_t(int64_t(std::abs(result - before)) / 200000); + int16_t credit = 0; + if (result < 0 && result + 1000000 + (10 - g.level) * 100000 < before) credit = int16_t(-step); + if (result > 0 && std::abs(result + 800000 - before) < 1500000) credit = int16_t(result / 250000 - step); + credit = int16_t(std::clamp(int(int16_t(credit + rec8(g, m, 0x26f))), 0, 100)); + set_rec32(g, m, 0x31c, credit * 20000); + post_composed(g, m, message_text(g, ::bmh::layout::Season_SeasonAccounts_TextPointer2) + format_amount(g, credit * 20000) + message_text(g, ::bmh::layout::Season_SeasonAccounts_TextPointer3)); + rec8(g, m, 0x26f) = uint8_t(credit); + if (result > 100000) { + modern::season_apply_profit_tax(g, m, result, game, rand, tax_hooks, &tax_state); + } + const int32_t taxed = rec32(g, m, 0x32c), tax = rec32(g, m, 0x328); + if (result < 100000 && taxed != 0 && tax != 0) { + const int32_t back = modern::season_profit_tax_refund(result, taxed, tax); + if (back > 0) { + post_composed(g, m, message_text(g, ::bmh::layout::Season_SeasonAccounts_TextPointer4) + format_amount(g, back) + "."); + set_rec32(g, m, 0x314, rec32(g, m, 0x314) + back); + } + } + if (result < 0x186a1) set_rec32(g, m, 0x32c, 0); + set_rec32(g, m, 0x320, 0); + set_rec32(g, m, 0x324, rec32(g, m, 0x314)); + for (size_t i = 0; i < 0x48; i++) rec8(g, m, 0x85c + i) = 0; + season_tickets(g, m, rand); // ChangePlaces -> CareerSeasonSetup2 +} + +// ClubsChangePlaces(a, b): two clubs (ids below 168) change places - every table per club id +// swaps its entries, lists of club ids replace the one by the other. Squads, position +// histories and loans only move between league clubs (ids below 138); the table *ClubAuxiliaryBytes +// swaps twice for them (no change), once otherwise. +void change_places(ModernState& g, int a, int b) { + StaticMemory& mem = g.memory; + if (a >= first_foreign_cup() || b >= first_foreign_cup()) return; + auto swap_bytes = [](std::vector& v, size_t x, size_t y, size_t n) { + for (size_t i = 0; i < n; i++) + if (x + i < v.size() && y + i < v.size()) std::swap(v[x + i], v[y + i]); + }; + auto swap_mem8 = [&](uint32_t base) { + const uint8_t t = mem.u8(base + uint32_t(a)); + mem.set8(base + uint32_t(a), mem.u8(base + uint32_t(b))); + mem.set8(base + uint32_t(b), t); + }; + auto replace = [&](uint32_t at, int n) { // U163 + for (int i = 0; i < n; i++) { + const uint16_t v = mem.u16(at + uint32_t(i) * 2); + if (v == uint16_t(a)) mem.set16(at + uint32_t(i) * 2, uint16_t(b)); + else if (v == uint16_t(b)) mem.set16(at + uint32_t(i) * 2, uint16_t(a)); + } + }; + const bool both_league_clubs = a < league_clubs() && b < league_clubs(); + if (both_league_clubs) + for (uint32_t k = 0; k < 200; k++) { // loans: seller and buyer + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e == 0) continue; + int seller = int(e >> 12) & 0x3ff, buyer = int(e >> 22) & 0x3ff; + seller = seller == a ? b : seller == b ? a : seller; + buyer = buyer == a ? b : buyer == b ? a : buyer; + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4, (e & 0xfff) | uint32_t(seller) << 12 | uint32_t(buyer) << 22); + } + if (!g.club_table.empty() && a < first_foreign_cup() && b < first_foreign_cup()) swap_bytes(g.club_table, size_t(a) * 0x4a, size_t(b) * 0x4a, 0x4a); + std::swap(g.club_ids.at(size_t(a)), g.club_ids.at(size_t(b))); + swap_bytes(g.club_heap_bc, size_t(a) * 2, size_t(b) * 2, 2); + std::swap(g.team_morale.at(size_t(a)), g.team_morale.at(size_t(b))); + swap_mem8(::bmh::layout::ClubShortNameOffsets); + swap_mem8(::bmh::layout::ClubKitSelectors); + swap_bytes(g.club_heap_78, size_t(a) * 2, size_t(b) * 2, 2); + std::swap(g.team_flags.at(size_t(a)), g.team_flags.at(size_t(b))); + if (both_league_clubs) { + swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2); + swap_bytes(g.position_history, size_t(a) * 0x1a, size_t(b) * 0x1a, 0x1a); + const SquadRange ra = squad_range(a), rb = squad_range(b); + for (size_t i = 0; i < ra.count; i++) std::swap(g.squad_slots.at(ra.first + i), g.squad_slots.at(rb.first + i)); + } + swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2); + replace(::bmh::layout::Titles, 0x1c2); // title holders + replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, 2); + if (!mem.has(::bmh::layout::CareerSession_FormatError_RuntimeField6) || mem.u8(::bmh::layout::CareerSession_FormatError_RuntimeField6) == 0) { + replace(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, 0x20); + replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, 0x20); + replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, 0x40); + // (the English national cup field: 68 clubs at layout field, InitializeNationalCup(0x44, ...)) + if (kEnglishCompetitions) { + if (mem.has(kEnglishFaField)) replace(kEnglishFaField, 0x44); + } else { + replace(::bmh::layout::Field, 0x40); + } + replace(::bmh::layout::Cup_AdvanceCup_RuntimeField6, 3); + } + for (size_t m = 0; m < g.manager_teams.size(); m++) { + auto& t = g.manager_teams[m]; + const int old = t; + if (old == a) t = b; + else if (old == b) t = a; + if (t != old) { + g.manager_records.at(m * 0xB0C + 0x290) = uint8_t(t); + g.manager_records.at(m * 0xB0C + 0x291) = uint8_t(uint16_t(t) >> 8); + } + for (size_t i = 0; i < 12; i++) { // record +0x292 + const size_t at = m * 0xB0C + 0x292 + i * 2; + const uint16_t v = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); + const uint16_t w = v == uint16_t(a) ? uint16_t(b) : v == uint16_t(b) ? uint16_t(a) : v; + g.manager_records.at(at) = uint8_t(w), g.manager_records.at(at + 1) = uint8_t(w >> 8); + } + swap_bytes(g.manager_results, size_t(a) * 10 + m * 0x690, size_t(b) * 10 + m * 0x690, 10); + } +} + +// Getenv(teams, offset): the national cup's ties from `offset` on (list of cup +// entry 0): a lower club (from the third division on, SeasonRuntimeField23) gets home advantage, +// then the ties are ordered by the leagues' weight (SeasonRuntimeField24), heaviest first. +void order_cup_ties(ModernState& g, int teams, int offset) { + StaticMemory& mem = g.memory; + uint32_t list = mem.pointer(::bmh::layout::CupTable) + uint32_t(offset) * 2; + if (kEnglishCompetitions) { + // the Football Limited CupField: the FA Cup stage decides the range - qualifying + // round 1 (48 clubs from 0), round 2 (24 from 48), the proper rounds (entry 28); + // with 0x80 the League Cup (entry 25) + if ((teams & 0x80) == 0) { + const uint8_t played = mem.u8(::bmh::layout::CupTable + 0x1d); + if (played == 0) teams = 0x30, offset = 0; + if (played == 1) teams = 0x18, offset = 0x30; + const uint32_t base = played == 3 ? mem.pointer(::bmh::layout::CupTable + 28 * 0x28) : mem.pointer(::bmh::layout::CupTable); + list = base + uint32_t(offset) * 2; + } else { + teams ^= 0x80; + list = mem.pointer(::bmh::layout::CupTable + 25 * 0x28) + uint32_t(offset) * 2; + } + } + static const uint8_t kWeight[10] = {3, 1, 0, 0, 2, 0, 0, 0, 7, 0}; // SeasonRuntimeField24 + const int lower = league_first_team(2); + std::vector w; + for (int i = 0; i < teams; i += 2) { + const uint32_t at = list + uint32_t(i) * 2; + if (int16_t(mem.u16(at + 2)) >= lower && int16_t(mem.u16(at)) < lower) { + const uint16_t t = mem.u16(at); + mem.set16(at, mem.u16(at + 2)); + mem.set16(at + 2, t); + } + w.push_back(uint8_t(kWeight[club_league(mem.u16(at))] + kWeight[club_league(mem.u16(at + 2))])); + } + for (int i = 0; i < teams / 2 - 1; i++) + for (int j = i + 1; j < teams / 2; j++) + if (w[size_t(i)] < w[size_t(j)]) { + std::swap(w[size_t(i)], w[size_t(j)]); + for (uint32_t k = 0; k < 2; k++) { + const uint32_t x = list + uint32_t(i) * 4 + k * 2, y = list + uint32_t(j) * 4 + k * 2; + const uint16_t t = mem.u16(x); + mem.set16(x, mem.u16(y)); + mem.set16(y, t); + } + } +} + +} // namespace + +void clubs_change_places(ModernState& g, int a, int b) { change_places(g, a, b); } + +// The side effects of the cup overview screen CupGroupOverviewEffects (otherwise display only): slot 4 +// of the running competitions is this year's international tournament (7 - season % 4), +// the screen state of the manager (CareerSession_DispatchOtherGames_RuntimeField) is reset, and the friendlies +// (competition 0xc) run while their entry (cup entry 30) has teams. +void cup_overview_effects(ModernState& g) { + StaticMemory& mem = g.memory; + if (mem.has(::bmh::layout::CareerSession_FormatError_RuntimeField3)) mem.set8(::bmh::layout::CareerSession_FormatError_RuntimeField3, uint8_t(7 - uint16_t(g.season) % 4)); + // CupGroupOverviewEffects normalizes the active manager byte before selecting that manager's + // screen-state slot. This is a real Source mutation (and is serialized where present). + uint8_t active = mem.has(::bmh::layout::ActiveManager) ? mem.u8(::bmh::layout::ActiveManager) : 0; + if (active > 3) { + active = 0; + if (mem.has(::bmh::layout::ActiveManager)) mem.set8(::bmh::layout::ActiveManager, active); + } + if (mem.has(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + active)) mem.set8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + active, 0x80); + if (mem.u8(::bmh::layout::FriendlyPlanCount) == 0) { + modern::end_competition(mem, 0xc); + } else { + for (uint32_t i = 0; i < 8; i++) { // AddCompetition(0xc) + if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + i)) == 0xc) break; + if (mem.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + mem.set8(::bmh::layout::ActiveSelectors + i, 0xc); + break; + } + } + } +} + +void cup_group_overview_effects(ModernState& g, int group_index) { + // This Source traversal cursor is runtime state, absent from native FBMs. + // Own it at the overview boundary even after loading a saved career. + if (!g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField8)) g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField8, 1); + g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField8, uint8_t(group_index)); + modern::cup_overview_effects(g); +} + +namespace { + +// Getenv2: every club of every league changes places with a random other club of the +// same league (ClubsChangePlaces) - this mixes the fixture positions of the new season +void shuffle_leagues(ModernState& g, WatcomRandom& rand) { + int first = 0; + for (int l = 0; l < kLeagueCount; l++) { + const int end = first + kLeagueSizes[l]; + for (int t = first; t < end; t++) { + int r; + do r = rand.range(first, end - 1); while (uint8_t(r) == uint8_t(t)); + change_places(g, t, r); + } + first = end; + } +} + +// CareerSeasonSetup(2): the national cup's field - the first 18 of the first two divisions and +// the first 14 of the two third divisions by the final tables, shuffled (PrepareEvent). +// Human managers note the cup in their season record (ManagerOf(m, 1, 1)). Its first +// round is shown (CupDrawFromGame on cup entry 0) unless switched off; then Getenv gives +// the lower club home advantage and sorts the ties by the leagues' weight (SeasonRuntimeField24). +void observe_cup_draw(const ModernState& g, SeasonCupDrawPhase phase, + const SeasonCupDrawHook& hook) { + if (!hook) return; + const StaticMemory& mem = g.memory; + constexpr uint32_t entry = kCupTable; + SeasonCupDrawEvent event; + event.phase = phase; + event.entry_address = entry; + event.competition = mem.u8(entry + 0x18); + event.flags = mem.u8(entry + 0x14); + event.group_stage = (event.flags & 4) == 0; + event.group_index = mem.u8(entry + 0x1e) >> 4; + event.group_count = mem.u8(entry + 0x1e) & 0xf; + event.round = modern::cup_round(mem, 0); + event.offset = modern::cup_round_offset(mem, 0, event.round); + event.count = size_t(mem.u8(entry + 0x1a)) >> event.round; + const uint32_t field = mem.pointer(entry) + uint32_t(event.offset) * 2; + event.participants.reserve(event.count); + for (size_t i = 0; i < event.count; ++i) + event.participants.push_back(mem.u16(field + uint32_t(i) * 2)); + hook(g, event); +} + +// The English national cups (the Football Limited CupFieldsEnglish(2)): the FA Cup field of 68 +// clubs - the first three divisions complete and the best 8 of the fourth - whose 20 Premier +// League clubs and 48 others are shuffled apart (the 48 play the qualifying stage of entry +// 0), and the League Cup field of 44 - the first two divisions and the best 4 of the third, +// 20 and 24 shuffled apart (entry 25) - whose ties are ordered (CupField(0x98, 0)). +void cup_fields_english(ModernState& g, GameRandom& game, const uint8_t (&ranks)[4][24], + const std::function& pause, const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + modern::english_competition_blocks(mem); + auto shuffle = [&](uint32_t list, uint32_t n) { // Uint32T2 = PrepareEvent + for (uint32_t i = 0; i < n; i++) { + const uint32_t j = uint32_t(game.range(0, int(n) - 1)); + const uint16_t a = mem.u16(list + i * 2); + mem.set16(list + i * 2, mem.u16(list + j * 2)); + mem.set16(list + j * 2, a); + } + }; + uint32_t n = 0; + for (int l = 0; l < 4; l++) + for (int i = 0; i < kLeagueSizes[l]; i++) { + if (l >= 3 && i >= 8) continue; + const int team = club_at_rank(l, i, ranks[l]); + mem.set16(kEnglishFaField + n++ * 2, uint16_t(team)); + if (const int m = g.manager_of(team); m >= 0) + g.manager_records.at(size_t(m) * 0xB0C + 0xda + 1 + size_t(std::min(g.season, 0x31)) * 3) = 1; + } + shuffle(kEnglishFaField, 0x14); + shuffle(kEnglishFaQualifyingField, 0x30); + if (mem.u8(::bmh::layout::LeaguePresentationOptions + 5 * 9) == 0) { // CupOverviewEffects(entry 0) unless the draw display is off + observe_cup_draw(g, SeasonCupDrawPhase::draw, cup_draw); + if (pause) pause("the FA Cup draw (CupOverviewEffects)"); + order_cup_ties(g, 0x30, 0); // (CupOverviewEffects orders the ties: CupField, stage 0) + modern::cup_overview_effects(g); + observe_cup_draw(g, SeasonCupDrawPhase::overview, cup_draw); + } + n = 0; + for (int l = 0; l < 3; l++) + for (int i = 0; i < kLeagueSizes[l]; i++) { + if (l >= 2 && i >= 4) continue; + mem.set16(kEnglishLeagueCupField + n++ * 2, uint16_t(club_at_rank(l, i, ranks[l]))); + } + shuffle(kEnglishLeagueCupField, 0x14); + shuffle(kEnglishLeagueCupField + 0x28, n - 0x14); + order_cup_ties(g, 0x98, 0); // CupField(0x98, 0): the League Cup ties +} + +void cup_field(ModernState& g, GameRandom& game, const std::function& pause, + const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + uint8_t ranks[4][24] = {}; + for (int l = 0; l < 4; l++) { + const LeagueTable t = compute_league_table(g, l, 0, league_matchdays(l), 7, 1); + for (int i = 0; i < t.size; i++) ranks[l][i] = uint8_t(t.rank(i)); + } + if (kEnglishCompetitions) { + cup_fields_english(g, game, ranks, pause, cup_draw); + return; + } + constexpr uint32_t kField = ::bmh::layout::Field; + uint32_t n = 0; + for (int l = 0; l < 4; l++) + for (int i = 0; i < kLeagueSizes[l]; i++) { + if (l >= 2 && i >= 0xe) continue; + const int team = club_at_rank(l, i, ranks[l]); + mem.set16(kField + n++ * 2, uint16_t(team)); + if (const int m = g.manager_of(team); m >= 0) + g.manager_records.at(size_t(m) * 0xB0C + 0xda + 1 + size_t(std::min(g.season, 0x31)) * 3) = 1; + } + for (uint32_t i = 0; i < 0x40; i++) { // PrepareEvent + const uint32_t j = uint32_t(game.range(0, 0x3f)); + const uint16_t a = mem.u16(kField + i * 2); + mem.set16(kField + i * 2, mem.u16(kField + j * 2)); + mem.set16(kField + j * 2, a); + } + if (mem.u8(::bmh::layout::LeaguePresentationOptions + 5 * 9) != 0) return; // the draw display is switched off + observe_cup_draw(g, SeasonCupDrawPhase::draw, cup_draw); + if (pause) pause("the national cup draw (CupDrawFromGame)"); + order_cup_ties(g, mem.u8(::bmh::layout::CupTable + 0x1a), 0); // (round 0 of cup entry 0) + modern::cup_overview_effects(g); // CupGroupOverviewEffects lists the ties + observe_cup_draw(g, SeasonCupDrawPhase::overview, cup_draw); +} + +// GeneratePlayer: see generate_player (career.hpp) +void regenerate_player(ModernState& g, int player, int strength, GameRandom& game, WatcomRandom& rand) { + modern::generate_player(g, player, strength, game, rand); +} + +// SetAge(player, age): the age (w364 bits 21-25); bits 2-12 are cleared as well +void set_age(ModernState& g, int player, int age) { + Player& p = g.players.at(size_t(player)); + p.w364 = (p.w364 & 0x1fe003u) | uint32_t(age) << 21; +} + +} // namespace + +// MonthChange(slot): a player leaves his club for the free agents (foreigners to their own +// pool): his loan entry and youth mark go, he gets new values (RegeneratePlayer: all but w35c), +// an age W(4, 15) and no injury; the club closes the gap (ReleasePlayer) +bool release_player(ModernState& g, int slot, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + for (uint32_t k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e == 0 || int(e & 0xFFF) != player) continue; + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4, 0); + for (uint32_t i = 0; i < 12; i++) + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2) == uint16_t(player)) { + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2, 0xFFF); + const uint32_t owner = ::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(int8_t(mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + i))); + mem.set8(owner, uint8_t(mem.u8(owner) - 1)); + } + break; + } + const int team = modern::slot_team(slot); + const bool foreign = modern::nationality(g, player) != 0; + const int start = foreign ? int(foreign_offer_slot()) : int(free_agent_slot()), count = foreign ? 0x14 : 0x50; // FirstFreeSlotSquad + int free = -1; + for (int s = start; s < start + count && free < 0; s++) + if (g.squad_slots.at(size_t(s)) == 0x0FFF) free = s; + const uint32_t skills = g.players.at(size_t(player)).w35c; // RegeneratePlayer + regenerate_player(g, player, 0x32, game, rand); + Player& p = g.players.at(size_t(player)); + p.w35c = skills; + g.player_bonus.at(size_t(player)) &= 0x80; + p.w368 &= 0xf8003fffu; + p.w364 &= 3; + p.w364 |= uint32_t(rand.range(4, 0xf)) << 21; + p.w35c &= 0x07ffffffu; + if (free < 0) { + // no room among the free agents: a club takes him (TransferBid(slot, 0, 0, -1)) + modern::transfer_bid(g, slot, 0, false, -1, game, rand, report); + if (report.unsupported) return false; + } else { + g.squad_slots.at(size_t(free)) = uint16_t(player); + } + if (team >= 0) return modern::remove_from_seller(g, team, player, report); + return true; +} + +namespace { + +// CareerSeasonSetup3: the players' new season. Records and boards of the managers restart +// (with new advertising offers, TransferListCountdown2); then every squad and pool slot: players +// out for their career recover now and then with a human club's good doctor, else leave; +// everybody grows a year older (w364 bits 21-25), and at a computer club an old player +// retires (unless the squad is small: then he is replaced by a young one) - the first old +// one of every club always goes (a quirk: the counter starts at 0xFF). Last the rounds, +// cards, position histories and results of the old season are cleared. +void season_players(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + auto fill8 = [&](uint32_t at, uint32_t n, uint8_t v) { + for (uint32_t i = 0; i < n; i++) + if (mem.has(at + i)) mem.set8(at + i, v); + }; + auto fill16 = [&](uint32_t at, uint32_t n, uint16_t v) { + for (uint32_t i = 0; i < n; i++) + if (mem.has(at + i * 2)) mem.set16(at + i * 2, v); + }; + // Fill8: desk and screen states + fill8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField, 4, 0x80), fill8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField, 4, 1); + fill16(::bmh::layout::LeagueTableDisplayModes, 4, 0x11), fill16(::bmh::layout::ManagerSettings, 4, 0x1ff), fill16(::bmh::layout::CareerSession_AnyOf_ExecutableField, 4, 0x15), fill16(::bmh::layout::Savestate_Layout_ExecutableField3, 4, 0xdf0); + fill8(::bmh::layout::Flags, 0xc, 0x40); + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (size_t i = 0; i < 10; i++) rec8(g, int(m), 0x8b6 + i) = 0xff; + modern::end_competition(mem, 0xd); // EndCompetition + fill8(::bmh::layout::Season_SeasonPlayers_ExecutableField, 1, 0); + for (size_t mi = 0; mi < g.manager_teams.size() && !report.unsupported; mi++) { + const int m = int(mi); + // CareerSeasonSetup3 invokes StartingSponsors for each manager before resetting + // seasonal records and constructing new advertising offers. + modern::starting_sponsors(g, m); + rec8(g, m, 0x284) = 0, rec8(g, m, 0x21e) = 0, rec8(g, m, 0x283) = 0; + set_rec32(g, m, 0x330, 0); + rec8(g, m, 0x28b) = 0; + for (size_t i = 0; i < 3; i++) rec8(g, m, 0x28c + i) = 0; + for (size_t i = 0; i < 10; i++) rec8(g, m, 0x170 + i) = 0; + for (size_t i = 0; i < 0x48; i++) rec8(g, m, 0x1ae + i) = 0; + for (size_t i = 0; i < 0x30; i++) rec8(g, m, 0x718 + i) = 0; + for (size_t i = 0; i < 0xc; i++) rec8(g, m, 0x8c0 + i) = 0, rec8(g, m, 0x748 + i) = 0; + modern::advertising_offers(g, m, rand, report); // TransferListCountdown2 + if (report.unsupported) return; + set_rec32(g, m, 0x33c, 0), set_rec32(g, m, 0x338, 0), set_rec32(g, m, 0x334, 0); + for (size_t s = 0; s < 24; s++) { + const size_t at = mi * 0x840 + s * 0x58; + g.tactics.at(at + 6) = 0; + g.tactics.at(at + 0xf) = uint8_t(rand.range(0x14, 0x32)); + } + for (uint32_t i = 0; i < 12; i++) + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2) != 0xfff && int8_t(mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + i)) == m) { + mem.set8(::bmh::layout::Season_SeasonPlayers_RuntimeField + i * 0x58, 0); + mem.set8(::bmh::layout::Season_SeasonPlayers_RuntimeField2 + i * 0x58, uint8_t(rand.range(0x14, 0x32))); + } + } + if (g.date > 0) { + g.lineups_frozen = true; // LineupRuntimeField + uint8_t loans[0x1d3] = {}; + for (uint32_t k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e != 0) loans[(e >> 12) & 0x3ff]++; + } + uint16_t last_team = 0xffff; // local_30 + uint8_t count = 0xff; // local_20 + int8_t owner = -1; // local_24: the club's human manager + size_t board_first = 0; // local_3c + for (int s = 0; s < int(pool_end_slot()) && !report.unsupported; s++) { + for (;;) { + const int player = g.squad_slots.at(size_t(s)) & 0xFFF; + if (player == 0xFFF) break; + const int team = modern::slot_team(s); + if (team != int(last_team)) { // (-1 for the pool never equals 0xFFFF) + count = 0xff; + const int mm = g.manager_of(team); + owner = int8_t(mm >= 0 ? mm : -1); + if (mm >= 0) board_first = squad_range(team).first; + } + Player& p = g.players.at(size_t(player)); + bool leaves = false; + if (s < int(transfer_list_slot()) && (p.w35c >> 27) == 0x1f) { + // out for his career + bool gone = true; + if (owner != -1) { + std::string text; + const int doctor = int16_t(g.manager_records.at(size_t(owner) * 0xB0C + 0x8ae) | + g.manager_records.at(size_t(owner) * 0xB0C + 0x8af) << 8); + if (doctor > rand.range(700, 0x4b0)) { + text = message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer2); + gone = false; + p.w35c &= 0x07ffffffu; + p.w364 &= ~(0x1fu << 16); + } else { + text = g.player_name(player) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer3); + const size_t board = size_t(owner) * 0x840 + size_t(s - int(board_first)) * 0x58; + const int8_t insured = int8_t(g.tactics.at(board + 0x43)); + if (insured != 0) { + const int k = (insured >> 6) & 3; + const int32_t pay = int32_t(uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16) | + uint32_t(g.tactics.at(board + 0x53)) << 24) * + int8_t(k * 3 + 3); + modern::book_money(g, owner, -pay, true); + text += message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer4) + format_amount(g, pay) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer5); + } + } + post_composed(g, owner, text); + } + if (gone) { + if (count != 0xff) count = uint8_t(modern::squad_count(g, team, 2) + loans[team]); + if (owner == -1 && count <= 0xd) { + set_age(g, player, rand.range(0x12, 0x19) - 0x10); + } else { + count--; + leaves = true; + // a loaned player: his club's manager is told + for (uint32_t k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e == 0 || int(e & 0xFFF) != player) continue; + const int mm = g.manager_of(int(e >> 12) & 0x3ff); + owner = int8_t(mm >= 0 ? mm : -1); + if (mm >= 0) + post_composed(g, mm, message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer6) + g.player_name(player) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer7)); + break; + } + } + } + } + if (!leaves) { + // a year older + p.w368 &= 0xf8003fffu; + int age = int16_t(((p.w364 >> 21) & 0x1f) + 1); + if (s < int(transfer_list_slot()) && rand.range(0x10, 0x16) < age && owner == -1) { + if (count != 0xff) count = uint8_t(modern::squad_count(g, team, 2) + loans[team]); + if (count > 0xd) { + count--; + leaves = true; + } else { + age = rand.range(0x12, 0x19) - 0x10; + } + } + if (!leaves) { + set_age(g, player, age); // SetAge + last_team = uint16_t(team); + break; + } + } + if (std::getenv("BMH_TRACE")) + std::printf(" [release slot %d player %d team %d age %u count %u]\n", s, player, team, (p.w364 >> 21) & 0x1f, count); + if (!modern::release_player(g, s, game, rand, report)) return; + } + } + g.lineups_frozen = false; + } + for (size_t l = 0; l < g.league_rounds.size() && l < 9; l++) g.league_rounds[l] = 0; + fill8(::bmh::layout::DeskRecords_Teams_RuntimeField, 0x114, 0); + for (size_t i = 0; i < size_t(league_clubs()) * 0x1a && i < g.position_history.size(); i++) g.position_history[i] = 0; + std::fill(g.results.begin(), g.results.end(), uint8_t(0xcc)); +} + +// The end of the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest: histories beyond 50 seasons shift +// (SeasonEndSteps), the managers' season record starts (ManagerOf(m, 0, -2)), the +// limited game length counts down (CareerDuration), the days pass (DayStepRest) up to the +// first Wednesday, new players come onto the transfer list (CareerFirstSteps), and the new +// season starts on that day (DaysIntoSeason = 0) with its calendar cleared of replay days. +SeasonTransitionOutcome season_end_steps(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const SeasonHighscoreHook& highscore, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + if (g.season > 0x31) { // SeasonEndSteps + for (uint32_t k = 0; k < 9; k++) { + for (uint32_t i = 0; i < 0x62; i++) mem.set8(::bmh::layout::Titles + k * 100 + i, mem.u8(::bmh::layout::Season_SeasonEndSteps_RuntimeField + k * 100 + i)); + mem.set16(::bmh::layout::Season_SeasonEndSteps_RuntimeField2 + k * 100, 0xffff); + } + for (size_t m = 0; m < g.manager_teams.size(); m++) { + for (size_t i = 0; i < 0x93; i++) rec8(g, int(m), 0xda + i) = rec8(g, int(m), 0xdd + i); + const size_t at = m * 0xB0C + 0x2aa; + const uint16_t n = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8) + 1; + g.manager_records.at(at) = uint8_t(n), g.manager_records.at(at + 1) = uint8_t(n >> 8); + } + } + for (size_t m = 0; m < g.manager_teams.size(); m++) + rec8(g, int(m), 0xda + size_t(std::min(g.season, 0x31)) * 3) = 0xfe; + // GameEndAlternateScoreScreen(0): update the external highscore table before decrement. + if (highscore) highscore(g, false); + if (mem.has(::bmh::layout::CareerDuration)) { + uint8_t left = mem.u8(::bmh::layout::CareerDuration); + if (left < 5) mem.set8(::bmh::layout::CareerDuration, --left); + if (left == 0) { + // DailyInterest returns here before first-Wednesday day steps. + if (highscore) highscore(g, true); + return SeasonTransitionOutcome::CareerComplete; + } + } + const bool full = (mem.u8(::bmh::layout::CompetitionSelection) & 1) != 0; + while (modern::weekday_code(g.date) != 2) { // DayStepRest + g.date++; + modern::daily_interest(g, rand); + if (std::getenv("BMH_TRACE")) + std::printf(" [day %u (weekday %d): game %llu, Watcom %llu]\n", g.date, modern::weekday_code(g.date), (unsigned long long)game.calls(), + (unsigned long long)rand.calls()); + const int wd = modern::weekday_code(g.date - 1); + if (wd == 2 || wd == 6) { + if (full && modern::weekday_code(g.date) == 3) { + modern::weekly_processing(g, game, rand, report, allocator); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + } + modern::familiarity_decay(g, game, rand); + for (size_t m = 0; m < g.manager_teams.size(); m++) modern::train_squad(g, int(m), game, rand); + } + if (full && modern::month_code(g.date - 1) != modern::month_code(g.date)) { + modern::month_change(g, rand, report, &game); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + } + } + if (std::getenv("BMH_TRACE")) + std::printf(" [before CareerFirstSteps: game %llu, Watcom %llu]\n", (unsigned long long)game.calls(), (unsigned long long)rand.calls()); + modern::new_transfer_list_entries(g, rand, report); // CareerFirstSteps + if (report.unsupported) return SeasonTransitionOutcome::Failed; + if (mem.has(::bmh::layout::CalendarState_FormatError_RuntimeField3)) mem.set16(::bmh::layout::CalendarState_FormatError_RuntimeField3, uint16_t(g.date)); // (a 16-bit copy of the date) + g.season_start = g.date; // DaysIntoSeason = 0 + mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, 0); + for (uint32_t d = 0; d < 0x16d; d++) + if ((mem.u16(::bmh::layout::CompetitionCalendar + d * 2) & 0x4f0e) == 0x4000) mem.set16(::bmh::layout::CompetitionCalendar + d * 2, 0); + return SeasonTransitionOutcome::NextSeason; +} + +// LicenceWithdrawals(league, ...): clubs losing their licence - a bankrupt human club placed +// below 6th (its manager's league marker was set to 0x1e before), and with fewer than six +// managers now and then (G(0, 12 - 7 * league) == 0) a computer club of the first two +// divisions placed 10th-15th. They go down first; `places` counts down. +void licence_withdrawals(ModernState& g, int league, std::vector& down, int& places, const uint8_t* ranks, + GameRandom& game, WatcomRandom& rand) { + const int first = league_first_team(league); + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const int team = g.manager_teams[m]; + if (team < first || team >= first + kLeagueSizes[league] || ranks[team - first] <= 5) continue; + static const uint8_t kDownPlaces[kLeagueCount] = {3, 4, 2, 2, 3, 0, 0, 0, 0}; // CareerSession_InstallLeagueSizes_RuntimeField2 + if (kDownPlaces[league] == 0) continue; + const uint8_t cut = rec8(g, int(m), 0x220); + const int32_t total = int32_t(rec8(g, int(m), 0x26f)) * 80000 + (assets(g, int(m), 0xf) - assets(g, int(m), 0x10)); + const bool broke = total < -6000000 || ((cut >> 5) == 2 && int32_t(cut & 0x1f) * 100000 <= rec32(g, int(m), 0x330)); + if (broke && rec8(g, int(m), 0x210) == 0x1e) { + rec8(g, int(m), 0x210) = 0; + post_text(g, int(m), text_id(::bmh::layout::Season_LicenceWithdrawals_TextPointer)); + down.push_back(uint16_t(team)); + if (places != 0) places--; + } + } + if (g.manager_teams.size() < 6 && league < 2 && game.range(0, 12 - 7 * league) == 0) { + int t = 0, r = 0; + do { + do { + r = rand.range(0, kLeagueSizes[league] - 1); + t = first + r; + } while (g.manager_of(t) >= 0); + } while (ranks[r] < 10 || ranks[r] > 15); + down.push_back(uint16_t(t)); + post_composed(g, -1, message_text(g, ::bmh::layout::Season_LicenceWithdrawals_TextPointer2) + g.club_name(t) + message_text(g, ::bmh::layout::Season_LicenceWithdrawals_TextPointer3)); + places--; + } +} + +// A real club name has a letter; the English database fills unused club ids with blanks and +// punctuation (", ", " :"). +bool club_has_name(const std::string& name) { + return std::any_of(name.begin(), name.end(), [](char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }); +} + +// Void: settle transfers and compute each group's local lists. Source +// displays them with SeasonPromotionScreen immediately before that group's club swaps. +void promotion(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause, + const SeasonPromotionHook& promotion_hook, TransferAllocatorContext allocator) { + modern::transfer_list_countdown(g, game, rand, report, true, allocator); // TransferListCountdown(1) + if (report.unsupported) return; + std::vector was; // the managers' leagues before (record +0x210) + for (size_t m = 0; m < g.manager_teams.size(); m++) was.push_back(rec8(g, int(m), 0x210)), rec8(g, int(m), 0x210) = 0x1e; + uint8_t ranks[5][24] = {}; + for (int l = 0; l < 5; l++) { + const LeagueTable t = compute_league_table(g, l, 0, league_matchdays(l), 7, 1); + for (int i = 0; i < t.size; i++) ranks[l][i] = uint8_t(t.rank(i)); + } + // The league ladder is data of the loaded game (schedule.hpp, installed from the EXE): + // Void reads the German tables, the English ClubName its own copies - + // first league / number of leagues of each promotion group (kGroupLeague/s), relegation + // places (kLeagueRelegation), the league(s) below (kGroupBelow/Count). German: + // 0 | 1 | 2+3 (Regionalliga A/B) | 4; English: 0 | 1 | 2 | 3. + const uint8_t* kFirst = kGroupLeague; + const uint8_t* kCount = kGroupLeagues; + const uint8_t* kDown = kLeagueRelegation; + const uint8_t* kBelow = kGroupBelow; + const uint8_t* kBelowCount = kGroupBelowCount; + // The clubs that refill the lowest league: kNewcomerCount clubs from kNewcomerFirst + // (German: the 30 amateur clubs 138-167). The English game draws from its 12 further + // English clubs (ClubName: range(CareerSession_DispatchLineup_RuntimeField, CareerSession_DispatchLineup_RuntimeField + 11)); its later ids have no name. + // The span ends at the last named club, which keeps the German draws unchanged. + // (OpenBMH deviates from the English original here: its extra coin flip per draw is not + // ported.) + const int newcomer_first = kNewcomerFirst; + int newcomer_count = kNewcomerCount; + while (newcomer_count > 1) { + const std::string name = g.club_name(newcomer_first + newcomer_count - 1); + if (club_has_name(name)) break; + newcomer_count--; + } + for (int grp = 0; grp < 4; grp++) { + std::vector down, up; + for (int l = kFirst[grp]; l < kFirst[grp] + kCount[grp]; l++) { + int places = kDown[l]; + licence_withdrawals(g, l, down, places, ranks[l], game, rand); + for (int rank = kLeagueSizes[l] - 1; places != 0; rank--) { + const int team = club_at_rank(l, rank, ranks[l]); + if (std::find(down.begin(), down.end(), uint16_t(team)) == down.end()) down.push_back(uint16_t(team)), places--; + } + } + size_t count = down.size(); + if (grp < 3) { + // the top of the division(s) below; from the two third divisions their + // champions and the play-off winners (Season_Promotion_ExecutableField2 / Season_Promotion_ExecutableField), without a play-off + // only the champions + size_t per = count / kBelowCount[grp]; + for (int l = kBelow[grp]; l < kBelow[grp] + kBelowCount[grp]; l++) { + if (kBelowCount[grp] > 1) { + if (mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField) == 0) count = 2; + else up.push_back(l > kBelow[grp] ? mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField) : mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField2)); + per = 1; + } + for (size_t i = 0; i < per; i++) up.push_back(uint16_t(club_at_rank(l, int(i), ranks[l]))); + } + } else { + // into the fourth division come amateur clubs (ids 138-167) at random + for (size_t i = 0; i < count; i++) { + uint16_t t; + do t = uint16_t(rand.range(newcomer_first, newcomer_first + newcomer_count - 1)); + // (never a club without a name: the English range has gaps; German draws are + // unchanged, all thirty amateur clubs have names) + while (std::find(up.begin(), up.end(), t) != up.end() || + !club_has_name(g.club_name(t))); + up.push_back(t); + } + } + static const char* kScreen[4] = {"promotion and relegation of the first division (SeasonPromotionScreen)", + "promotion and relegation of the second division (SeasonPromotionScreen)", + "promotion and relegation of the third divisions (SeasonPromotionScreen)", + "promotion and relegation of the fourth division (SeasonPromotionScreen)"}; + if (std::getenv("BMH_TRACE")) { + std::printf(" [group %d: count %zu down", grp, count); + for (uint16_t t : down) std::printf(" %d", t); + std::printf(" up"); + for (uint16_t t : up) std::printf(" %d", t); + std::printf(" a3204 %d a3206 %d]\n", mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField), mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField2)); + } + if (promotion_hook) promotion_hook(g, SeasonPromotionEvent{grp, count, down, up}); + if (pause) pause(kScreen[grp]); + for (size_t i = 0; i < count && i < up.size() && i < down.size(); i++) { + if (grp == 3 && g.manager_of(down[i]) >= 0) continue; + const int m = g.manager_of(up[i]); + if (m >= 0) { + // a promoted human club: its advertising contracts are marked, and a message + for (size_t k = 0; k < 0x12; k++) rec8(g, m, 0xa3a + k * 0xc) |= 0x80; + post_text(g, m, text_id(::bmh::layout::Season_Promotion_TextPointer)); + } + change_places(g, up[i], down[i]); + } + } + // the managers' leagues (record +0x210) and the desk buttons of leagues they left or + // joined (block LeaguePresentationOptions, 9 per league) + StaticMemory& mem = g.memory; + bool left[5] = {}, joined[5] = {}; + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const uint8_t before = uint8_t(was[m]); + const int now = club_league(g.manager_teams[m]); + rec8(g, int(m), 0x210) = uint8_t(now); + if (now < 5) joined[now] = true; + if (before < 5) left[before] = true; + for (uint32_t k = 0; k < 4; k++) + if (mem.u8(::bmh::layout::LeaguePresentationOptions + uint32_t(before) * 9 + k) == 0) mem.set8(::bmh::layout::LeaguePresentationOptions + uint32_t(now) * 9 + k, 0); + } + for (int l = 0; l < 5; l++) + if (!joined[l] && left[l]) + for (uint32_t k = 0; k < 4; k++) mem.set8(::bmh::layout::LeaguePresentationOptions + uint32_t(l) * 9 + k, 1); +} + +} // namespace + +// LeagueName(buf, league): the name of a league (< 5): the texts from Achievements_FormatError_TextPointer3 on - a +// league whose suffix letter (CareerSession_InstallLeagueSizes_RuntimeField3, two bytes per league) is set shares the text of +// the one before when its letter is from 'B' on (LeagueName2) - with " " + the letter. +std::string league_name(const ModernState& g, int league) { + // CareerSession_InstallLeagueSizes_RuntimeField3 of the loaded game (schedule.hpp: German A/B for the two Regionalligen, + // English none - its four divisions are one ladder) + const char* kSuffix = kLeagueSuffix; + int index = 0; + for (int l = 0; l < league; l++) + if (uint8_t(kSuffix[l + 1]) < 0x42) index++; + std::string name = message_text(g, ::bmh::layout::Achievements_FormatError_TextPointer3 + uint32_t(index) * 4); + if (kSuffix[league] != 0) { + name += message_text(g, ::bmh::layout::Manager_FormatError_TextPointer2); + if (!name.empty()) name.back() = kSuffix[league]; + } + return name; +} + +namespace { + +// TopScorersFromGame(league, flags): the ten best scorers of a league into Season_List_RuntimeField (10 x +// slot, team, goals, assists): goals (w364 bits 2-7, flag 2) plus assists (w368 bits 18-23, +// flag 4); flag 1 only counts human clubs. A player goes before the first one with fewer +// points (equal ones keep the earlier club / squad slot first). Returns the team of the best. +int best_scorer_team(ModernState& g, int league, int flags) { + std::vector list(40, 0); + for (int i = 0; i < 40; i += 4) list[size_t(i)] = 0xfff, list[size_t(i) + 1] = 0xfff; + int16_t best[10] = {}; + const int first = league_first_team(league); + for (int team = first; team < first + kLeagueSizes[league]; team++) { + if (g.manager_of(team) < 0 && (flags & 1)) continue; + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const int player = g.squad_slots.at(s) & 0xfff; + if (player == 0xfff) continue; + const Player& p = g.players.at(size_t(player)); + const uint16_t goals = (flags & 2) ? uint16_t((p.w364 >> 2) & 0x3f) : 0; + const uint16_t assists = (flags & 4) ? uint16_t((p.w368 >> 18) & 0x3f) : 0; + const uint8_t points = uint8_t(goals + assists); + if (points == 0) continue; + for (int i = 0; i < 10; i++) { + if (best[i] >= int16_t(points)) continue; + for (int k = 9; k > i; k--) { + best[k] = best[k - 1]; + for (int j = 0; j < 4; j++) list[size_t(k * 4 + j)] = list[size_t((k - 1) * 4 + j)]; + } + list[size_t(i * 4)] = uint16_t(s), list[size_t(i * 4 + 1)] = uint16_t(team); + list[size_t(i * 4 + 2)] = goals, list[size_t(i * 4 + 3)] = assists; + best[i] = int16_t(points); + break; + } + } + } + if (g.memory.has(::bmh::layout::Season_List_RuntimeField)) + for (uint32_t i = 0; i < 40; i++) g.memory.set16(::bmh::layout::Season_List_RuntimeField + i * 2, list[i]); + return list[1]; +} + +// FairPlayStateFromGame(league, 0): the fair play table - 4 points per red card (high byte of the +// club's card counter DeskRecords_Teams_RuntimeField) and 1 per yellow, sorted ascending (Games). +// Returns the club with the fewest points. +int fair_play_team(const ModernState& g, int league) { + const int first = league_first_team(league), count = kLeagueSizes[league]; + std::vector teams(static_cast(count)); + std::vector points(static_cast(count)); + for (int i = 0; i < count; i++) { + teams[size_t(i)] = int16_t(first + i); + const uint16_t cards = g.memory.u16(::bmh::layout::DeskRecords_Teams_RuntimeField + uint32_t(first + i) * 2); + points[size_t(i)] = uint32_t((int16_t(cards) >> 8) * 4 + (cards & 0xff)); + } + quicksort_by_key(teams.data(), points.data(), count, true); + return teams[0]; +} + +} // namespace + +void season_awards(ModernState& g) { + static const uint8_t kFlags[2] = {2, 6}; // SeasonRuntimeField25: top scorer, best scorer (+ assists) + // SeasonRuntimeField26: the prizes in 10000s per league (top scorer, best scorer, fair play) + static const uint8_t kPrize[5][3] = {{30, 20, 25}, {20, 15, 17}, {15, 10, 12}, {15, 10, 12}, {10, 7, 9}}; + for (int kind = 0; kind < 3; kind++) + for (int league = 0; league < 5; league++) { + const int team = kind < 2 ? best_scorer_team(g, league, kFlags[kind]) : fair_play_team(g, league); + for (size_t m = 0; m < g.manager_teams.size(); m++) { + if (g.manager_teams[m] != team) continue; + const int32_t prize = int32_t(kPrize[league][kind]) * 10000; + // "Ihr Spieler / Ihre Mannschaft gewinnt den ... der . Prämie: ." + std::string text = message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer3) + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer2 + (kind == 2 ? 4u : 0u)) + + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer4) + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer + uint32_t(kind) * 4) + + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer5) + modern::league_name(g, league) + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer6) + + format_amount(g, prize) + "."; + post_composed(g, int(m), text); + modern::book_money(g, int(m), -prize, true, true); // BookMoney2(team, -prize, 1), FinanceStatisticsEnabled + } + } +} + +SeasonTransitionOutcome season_transition(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause, + const SeasonHighscoreHook& highscore, + const SeasonTaxHooks& tax_hooks, + const SeasonPromotionHook& promotion_hook, + const SeasonCupDrawHook& cup_draw, + TransferAllocatorContext allocator) { + if (g.memory.has(::bmh::layout::CareerDuration) && g.memory.u8(::bmh::layout::CareerDuration) == 0) { + report.fail("season transition: career already completed"); + return SeasonTransitionOutcome::Failed; + } + g.memory.set8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4, 0); + if (g.memory.has(::bmh::layout::Season_SeasonTransition_RuntimeField)) g.memory.set8(::bmh::layout::Season_SeasonTransition_RuntimeField, 0); + g.season = int16_t(g.season + 1); // SeasonIndex + modern::reset_club_moods(g, game, rand); + european_setup(g, game, rand, cup_draw); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + if (pause) pause("the German entrants (CompetitionWinnerScreen)"); + european_fields(g, game, rand); + SeasonTaxState tax_state; + for (size_t m = 0; m < g.manager_teams.size() && !report.unsupported; m++) + season_accounts(g, int(m), game, rand, report, tax_hooks, tax_state); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + promotion(g, game, rand, report, pause, promotion_hook, allocator); // Void + if (report.unsupported) return SeasonTransitionOutcome::Failed; + // DailyInterest: the summer sanctions (SeasonEvent, Season_SeasonAccounts_RuntimeField) take effect + if (g.memory.has(::bmh::layout::Season_SeasonAccounts_RuntimeField)) + for (size_t m = 0; m < g.manager_teams.size(); m++) rec8(g, int(m), 0x220) = g.memory.u8(::bmh::layout::Season_SeasonAccounts_RuntimeField + uint32_t(m)); + cup_field(g, game, pause, cup_draw); // CareerSeasonSetup(2) + // Getenv2: every club changes places with a random one of its league (the new + // fixtures), then the cup's ties are ordered again (Getenv(0x40, 0)) + auto trace = [&](const char* what) { + if (std::getenv("BMH_TRACE")) + std::printf(" [%s: game %llu, Watcom %llu draws so far]\n", what, (unsigned long long)game.calls(), + (unsigned long long)rand.calls()); + }; + trace("after the cup draw"); + shuffle_leagues(g, rand); + trace("after Getenv2"); + order_cup_ties(g, 0x40, 0); + season_players(g, game, rand, report); // CareerSeasonSetup3 + trace("after CareerSeasonSetup3"); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + const auto outcome = season_end_steps(g, game, rand, report, highscore, allocator); + trace("after the day steps"); + return outcome; +} + +} // namespace bmh::modern + +namespace bmh::modern { + +bool career_season_setup(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause, + const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + g.team_morale.at(size_t(no_team())) |= 0x80; + for (int team = 0; team < league_clubs(); team++) { + modern::club_balance(g, team, rand); + auto_lineup(g, team, g.manager_of(team) >= 0 ? 0xe4 : 100); // (byte 100 - 0x80 for humans) + } + // the title holders of the cup entries (+0x22): none yet, the placeholder clubs + const uint16_t first_small = 90; // TeamsWithSquads + const uint16_t foreign = no_team(); // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 (0x165) + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField2, foreign); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6, uint16_t(first_small + 7)); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField, 7); + if (kEnglishCompetitions) mem.set16(::bmh::layout::CupTable + 28 * 0x28 + 0x22, 7); // (EN: the FA Cup proper, SeasonRuntimeField8) + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5, uint16_t(first_small + 0x1f)); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4, uint16_t(first_small + 0x13)); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField3, uint16_t(foreign + 1)); + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, 0); + mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, 0); + mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, 7); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField7, 7); + european_setup(g, game, rand, cup_draw); // CareerSeasonSetup(3) + if (report.unsupported) return false; + if (pause) pause("the German entrants (CompetitionWinnerScreen)"); + european_fields(g, game, rand); + cup_field(g, game, pause, cup_draw); + for (size_t m = 0; m < g.manager_teams.size(); m++) season_tickets(g, int(m), rand); // CareerSeasonSetup2 + order_cup_ties(g, 0x40, 0); + season_players(g, game, rand, report); // CareerSeasonSetup3 + return !report.unsupported; +} + +} // namespace bmh::modern + +namespace bmh::modern { + +bool career_first_steps(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + g.memory.set32(::bmh::layout::CareerSession_Invalid_RuntimeField2, uint32_t(game.seed())); // CareerFirstSteps2: CareerSession_Invalid_RuntimeField2 = CareerSession_Save_RuntimeField + g.memory.set8(::bmh::layout::ActiveManager, 4); + g.autosave_month = 7; // DailyInterest(0): SeasonRuntimeField27 + shuffle_leagues(g, rand); // Getenv2 + modern::new_transfer_list_entries(g, rand, report); // CareerFirstSteps + return !report.unsupported; +} + +} // namespace bmh::modern diff --git a/src/modern/game/season.hpp b/src/modern/game/season.hpp new file mode 100644 index 0000000..5f6b352 --- /dev/null +++ b/src/modern/game/season.hpp @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +#include "game/season.hpp" +// OpenBMH deviates from the original: retains the enhanced academy player-generation strength bands with monthly youth budgets. +// From one season to the next (BMH.exe V2.24 + supported rule profile patch). +// +// On 1 July the "Weiter" loop (DailyInterest) ends the season: CareerSession_RuntimeError_RuntimeField4 = 1, the season +// bonuses (SeasonAwards) and the manager's desk "Saisonende". When he leaves it with +// "Anstoss" the offers still open for his players are answered (DispatchClubPlayerPendingOffers, from +// AdvanceTurn) and the new season is set up (the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest): +// season + 1 (SeasonIndex), the clubs' moods and flags (ClubBalance), the European +// cups and their foreign clubs (CareerSeasonSetup(1)), contracts (GameEndTaxAnimationScreen, Void), +// the league tables to the cups (CareerSeasonSetup(2)), the German clubs in Europe shown +// (SeasonOperation), the national cup draw (Getenv), promotion and relegation +// (CareerSeasonSetup3, SeasonEndSteps), the managers' season records (ManagerOf), the day steps +// up to the first Wednesday and the new transfer list (CareerFirstSteps); the season day +// DaysIntoSeason restarts at 0. +// Annual accounts expose the Original acknowledgement/decision boundary before +// booking tax. Headless callers without a selector use the Original NO branch. + +#include +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" +#include "game/transfer_allocator.hpp" + +namespace bmh::modern { + +// SeasonProfitTax continues GameEndTaxAnimationScreen's loop without reinitialising its local fine. +// This state lives for one annual-accounts pass across all human managers. + +// CupDrawFromGame: the generated order, then Getenv/CupGroupOverviewEffects. +// Participants are owned copies of the current round at each boundary. + +// DispatchClubPlayerPendingOffers (the loop at the end of AdvanceTurn): the offers for players of human +// manager `manager` (OfferSlots) are answered. A salary demand (a club tries to lure the +// player away) is accepted with `accept`: the board salary becomes the offered one and +// its percentage of the market salary is noted (+0xd). Declining it needs the transfer +// (IncomingTransferScreen) and is reported. A fee offer opens the negotiation screen (IncomingTransferScreen / +// OpenTransferEditor), which restarts the game generator from CareerSession_Invalid_RuntimeField2 and draws the +// negotiator's picture; with `game` the manager refuses the release (right click, the +// message box "Sie verweigern dem Spieler die Freigabe!"). A transfer_decision callback +// may accept a fee offer. Interactive Main uses process_natural_pending_offers_after_desk +// with its typed presenters and shared human-buyer settlement instead of this legacy API. +// (The offer slots are freed by free_offer_slots after all desks.) +void answer_offers(ModernState& g, int manager, bool accept, WatcomRandom& rand, MinuteReport& report, + GameRandom* game = nullptr); +// The end of the desk loop of AdvanceTurn, after every manager's desk and answers: the four +// offer slots (transfer list entries 0x28..0x2b, OfferSlots) are freed. +void free_offer_slots(ModernState& g); + +// OpenBMH deviates from the original: retains the enhanced academy player-generation strength bands with monthly youth budgets. +// Annual recruitment with an active middle youth budget (or a paid legacy +// academy contract), provided the squad has room. Shared player strength bands +// remain in effect; see season.cpp. +bool youth_academy_player(ModernState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ClubBalance(0): every club's mood (TeamMorale, W(20, 30)) and flags (*TeamFlags): a random +// base, two levels from the final table position (title holders get the top one) with +// random exceptions, and two from the balance of its squad (CareerSeasonSetup4). +// CareerSeasonSetup4(team): bits 8-11 of the club flags from the balance of its squad (W draws). +void club_balance(ModernState& g, int team, WatcomRandom& rand); + +// The end of InitializeCareer (a new career, after the managers): the national team flag, every +// league club's balance (CareerSeasonSetup4) and automatic line-up (humans with the bit 0x80), +// the title holders of the cups, CareerSeasonSetup(3) (international tournament, European +// entrants, national cup field), the season tickets (CareerSeasonSetup2), Getenv(0x40, 0) and +// the players' season (CareerSeasonSetup3). +// `pause` is called at the screens the original waits at (as in season_transition). +bool career_season_setup(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause = nullptr, + const SeasonCupDrawHook& cup_draw = {}); + +// CareerFirstSteps2 after InitializeCareer and the start of DailyInterest(0): the game generator's seed is +// saved (CareerSession_Invalid_RuntimeField2), the clubs of each league change places at random (Getenv2) and the +// transfer list gets its first players (CareerFirstSteps). The "Weiter" loop then prepares the +// first event (AdvanceTurn) up to the first desk. +bool career_first_steps(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ClubsChangePlaces(a, b): two clubs (ids below 168) change places in every table per club id. +void clubs_change_places(ModernState& g, int a, int b); + +// With `new_career` (ClubBalance(1), start of a career) both levels are 1 for every club and +// the position draws are skipped. +void reset_club_moods(ModernState& g, GameRandom& game, WatcomRandom& rand, bool new_career = false); + +// The CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest (see above). Missing runtime context or +// invalid state is reported through MinuteReport; presenters are supplied by the caller. +// `pause` is called where the original waits for the manager (a screen): week_check compares +// the recorded pauses there. +// Void -> SeasonPromotionScreen: already computed local lists, before swaps. +// The arrays are owned; only their first `count` entries are displayed/swapped. +// In group 1 without play-offs, count may be smaller than relegated.size(). + +SeasonTransitionOutcome season_transition(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause = {}, + const SeasonHighscoreHook& highscore = {}, + const SeasonTaxHooks& tax_hooks = {}, + const SeasonPromotionHook& promotion_hook = {}, + const SeasonCupDrawHook& cup_draw = {}, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +// GameEndTaxAnimationScreen/SeasonProfitTax profit branch: show ACK, ask JA/NEIN, perform its exact RNG +// and sanctions, then store the carry values and debit tax plus any fine once. +// The caller supplies the already rounded seasonal profit, before ticket income. +void season_apply_profit_tax(ModernState& g, int manager, int32_t profit, + GameRandom& game, WatcomRandom& rand, + const SeasonTaxHooks& hooks = {}, + SeasonTaxState* continuation = nullptr); + +// GameEndTaxAnimationScreen / SeasonProfitTax: progressive tax on a rounded seasonal profit. +// Exposed so the threshold and integer-rounding rules can be tested directly. +int32_t season_profit_tax(int32_t profit); +// GameEndTaxAnimationScreen: next-season tax refund after a lower profit; returns zero when +// the original conditions do not grant a refund. +int32_t season_profit_tax_refund(int32_t profit, int32_t previous_taxable_profit, + int32_t previous_tax_paid); + +// SeasonAwards, on 1 July before the "Saisonende" desk: per league (< 5) the club of the +// top scorer (goals), of the best scorer (goals + assists, list Season_List_RuntimeField) and the fair +// play winner (fewest card points); a human manager's club gets the prize (SeasonRuntimeField26) +// with a message. +void season_awards(ModernState& g); + +// The side effects of the cup overview screen CupGroupOverviewEffects (otherwise display only): the +// running competitions' slot 4 (this year's international tournament), the manager's screen +// state and the friendlies 0xc while their entry 30 has teams. +void cup_overview_effects(ModernState& g); +// CupGroupOverviewEffects's group cursor is owned by this stage entry; the national cup's +// existing overview path intentionally keeps its original effects unchanged. +void cup_group_overview_effects(ModernState& g, int group_index); + +// LeagueName: the name of a league below 5 (with its letter, e.g. for the third divisions). +std::string league_name(const ModernState& g, int league); + +// MonthChange(absolute squad slot): the player leaves his club for the free agents with new +// values (W and game draws) and an age W(4, 15); his club closes the gap (ReleasePlayer, +// with a human club its tactics board as well). False if the source ownership/state +// cannot be validated; the player movement and human board compaction are implemented. +bool release_player(ModernState& g, int slot, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh::modern diff --git a/src/modern/game/source_tip.cpp b/src/modern/game/source_tip.cpp new file mode 100644 index 0000000..4abf08e --- /dev/null +++ b/src/modern/game/source_tip.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/game/source_tip.hpp" + +#include +#include + +namespace bmh::modern { + +uint8_t source_tip_result(GameRandom& game, const std::array& gap, + int home_rating, int away_rating, + int home_secondary, int away_secondary) { + uint8_t home = uint8_t((away_secondary + 0x14 < home_secondary) + game.range(0, 1)); + uint8_t away = uint8_t((away_secondary < home_secondary) + game.range(0, 1)); + const uint32_t wrapped = uint32_t(home_rating) - uint32_t(away_rating); + const int32_t signed_difference = std::bit_cast(wrapped); + int32_t scaled = signed_difference / 10; + if (scaled < 0) scaled = -scaled; + uint8_t local_c = uint8_t(scaled); + if (home_rating > away_rating) { + if (local_c > 9) local_c = 9; + home = uint8_t(home + game.range(0, int(gap[local_c]) + 1)); + } + if (home_rating < away_rating) { + // ComputeLeagueTableForecast negates the byte before clamping it to the gap table. + local_c = uint8_t(-int(local_c)); + if (local_c > 9) local_c = 9; + away = uint8_t(away + game.range(0, int(gap[local_c]))); + if (local_c < 5) home = uint8_t(home + 1); + } + for (;;) { + const int cap = game.range(2, 6); + if (int(home) + int(away) <= cap) break; + if (home) --home; + if (away) --away; + } + return uint8_t((home << 4) | away); +} + +} // namespace bmh::modern diff --git a/src/modern/game/source_tip.hpp b/src/modern/game/source_tip.hpp new file mode 100644 index 0000000..259e31f --- /dev/null +++ b/src/modern/game/source_tip.hpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "modern/game/modern_state.hpp" +#include "game/source_tip.hpp" + +#include +#include + +#include "game/random.hpp" + +namespace bmh::modern { + +// ComputeLeagueTableForecast's pure score arithmetic after the caller has obtained the four +// QuoteNationalFriendlyMatch ratings. Each invocation consumes the same G draws, including +// the final goal-cap draw that terminates the loop. +uint8_t source_tip_result(GameRandom& game, const std::array& gap, + int home_rating, int away_rating, + int home_secondary, int away_secondary); + +} // namespace bmh::modern diff --git a/src/modern/game/stadium_blocks.cpp b/src/modern/game/stadium_blocks.cpp new file mode 100644 index 0000000..aa084c3 --- /dev/null +++ b/src/modern/game/stadium_blocks.cpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/game/stadium_blocks.hpp" +#include "modern/game/modern_state.hpp" + +#include "modern/game/matchday.hpp" + +#include +#include + +namespace bmh::modern { +namespace { +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kManagerClub = 0x290; +constexpr size_t kBuild = 0x34; +constexpr size_t kFlags = 0x44; +constexpr size_t kCapacity = 0x4c; +constexpr size_t kFutureCapacity = 0x54; +constexpr uint8_t kSeat = 1; +constexpr uint8_t kRoof = 2; +constexpr uint8_t kKnownFeatures = kSeat | kRoof; + +bool slot_index(StadiumBlockSlot slot, size_t& out) { + const auto raw = static_cast(slot); + if (raw >= 8) return false; + out = raw; + return true; +} + +uint16_t record_u16(const std::vector& records, size_t at) { + return uint16_t(records.at(at)) | uint16_t(records.at(at + 1)) << 8; +} + +std::optional checked_component(uint32_t price_per_1000, uint32_t places, + uint32_t multiplier, uint32_t divisor) { + const uint64_t units = places / 1000; + const uint64_t multiplied = uint64_t(price_per_1000) * units * multiplier; + if (multiplied > uint64_t(std::numeric_limits::max())) return std::nullopt; + return uint32_t(multiplied / divisor); +} + +bool valid_resolved_offer(const StandBlockOffer& offer, const StadiumBlockExpansionQuote& quote) { + if (offer.percent < 6 || offer.percent > 14 || offer.base_price != quote.base_price || + offer.base_days != quote.base_weeks || offer.base_days < 0 || offer.base_days > 255 || + offer.offered_price != uint32_t(uint64_t(quote.base_price) * uint32_t(100 + offer.percent) / 100) || + offer.price > uint32_t(std::numeric_limits::max())) + return false; + switch (offer.decision) { + case StandBlockOfferDecision::Declined: + return offer.price == offer.base_price && offer.construction_days == offer.base_days; + case StandBlockOfferDecision::Accepted: + // PrepareStandBlockOffer forms base_price * (100 + percent) in a signed + // 32-bit intermediate before dividing by 100. Do not accept a + // mathematically representable final uint32 when that Source + // intermediate would overflow. Declined offers do not use it. + return uint64_t(quote.base_price) * uint32_t(100 + offer.percent) <= + uint64_t(std::numeric_limits::max()) && + offer.price == offer.offered_price && + offer.construction_days <= offer.base_days - (offer.base_days >> 3) && + offer.construction_days >= offer.base_days - (offer.base_days >> 1); + case StandBlockOfferDecision::Pending: + default: + return false; + } +} +} // namespace + +std::optional quote_stadium_block_expansion( + const ModernState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places, + uint8_t desired_features, int company_price_percent, + const StadiumBlockExpansionConstants& constants) { + size_t block = 0; + if (!slot_index(slot, block) || manager < 0 || + size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size()) + return std::nullopt; + const int club = g.manager_teams[size_t(manager)]; + const size_t rec = size_t(manager) * kRecordSize; + if (club < 0 || club == no_team() || record_u16(g.manager_records, rec + kManagerClub) != uint16_t(club)) + return std::nullopt; + + const uint8_t build_weeks = g.manager_records.at(rec + kBuild + block); + const uint8_t raw_flags = g.manager_records.at(rec + kFlags + block); + const uint8_t current_capacity = g.manager_records.at(rec + kCapacity + block); + const uint8_t future_capacity = g.manager_records.at(rec + kFutureCapacity + block); + const uint32_t maximum = constants.max_places[block]; + const uint32_t unit_price = constants.price_per_1000[block]; + const uint8_t duration = constants.weeks[block]; + + // Active construction and idle unknown bits are not editable A–H source states. + if (build_weeks != 0 || (raw_flags & uint8_t(~kKnownFeatures)) != 0 || + (desired_features & uint8_t(~kKnownFeatures)) != 0 || + (desired_features & uint8_t(raw_flags & kKnownFeatures)) != uint8_t(raw_flags & kKnownFeatures) || + company_price_percent < 0 || company_price_percent > 427 || unit_price == 0 || + maximum == 0 || maximum > 255000 || maximum % 1000 != 0 || duration == 0) + return std::nullopt; + + const uint32_t current_places = uint32_t(current_capacity) * 1000; + if (total_target_places < current_places || total_target_places > maximum || + total_target_places / 1000 > 255) + return std::nullopt; + const uint32_t new_places = total_target_places - current_places; + const auto new_cost = checked_component(unit_price, new_places, 1, 1); + if (!new_cost) return std::nullopt; + const uint32_t seats_places = (raw_flags & kSeat) != 0 ? new_places : total_target_places; + const uint32_t roof_places = (raw_flags & kRoof) != 0 ? new_places : total_target_places; + const auto seats_cost = (desired_features & kSeat) != 0 + ? checked_component(unit_price, seats_places, 45, 100) : std::optional(0); + const auto roof_cost = (desired_features & kRoof) != 0 + ? checked_component(unit_price, roof_places, 30, 100) : std::optional(0); + if (!seats_cost || !roof_cost) return std::nullopt; + + const uint64_t sum = uint64_t(*new_cost) + *seats_cost + *roof_cost; + if (sum > uint64_t(std::numeric_limits::max()) || + sum * uint32_t(company_price_percent) > uint64_t(std::numeric_limits::max())) + return std::nullopt; + const uint32_t price = uint32_t(sum * uint32_t(company_price_percent) / 100); + + StadiumBlockExpansionQuote quote; + quote.manager = manager; + quote.manager_club = club; + quote.slot = slot; + quote.current_build_weeks = build_weeks; + quote.current_raw_flags = raw_flags; + quote.current_capacity_thousands = current_capacity; + quote.current_future_capacity_thousands = future_capacity; + quote.total_target_places = total_target_places; + quote.desired_features = desired_features; + quote.company_price_percent = company_price_percent; + quote.price_per_1000 = unit_price; + quote.max_places = maximum; + quote.new_places = new_places; + quote.new_places_cost = *new_cost; + quote.seats_cost = *seats_cost; + quote.roof_cost = *roof_cost; + quote.undiscounted_cost = uint32_t(sum); + quote.base_price = price; + quote.base_weeks = duration; + return quote; +} + +bool build_stadium_block_expansion( + ModernState& g, int manager, StadiumBlockSlot slot, + const StadiumBlockExpansionConstants& constants, + const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer, + WatcomRandom& rand, const ConstructionNoticeHook& payment_notice, + const SeasonTicketCompensationNoticeHook& compensation_notice) { + if (manager != quote.manager || slot != quote.slot || quote.base_price == 0 || + !valid_resolved_offer(resolved_offer, quote)) + return false; + const auto fresh = modern::quote_stadium_block_expansion(g, manager, slot, quote.total_target_places, + quote.desired_features, quote.company_price_percent, constants); + if (!fresh || *fresh != quote) return false; + + // Sponsor is always false for Original A–H construction. In particular this + // preserves +0x171 and prevents pay_construction's sponsor-only W draws. + if (!modern::pay_construction(g, manager, resolved_offer.price, false, rand, payment_notice)) return false; + + const size_t rec = size_t(manager) * kRecordSize; + const size_t block = static_cast(slot); + g.manager_records.at(rec + kBuild + block) = resolved_offer.construction_days; + g.manager_records.at(rec + kFlags + block) = uint8_t( + g.manager_records.at(rec + kFlags + block) | uint8_t(quote.desired_features << 4)); + g.manager_records.at(rec + kFutureCapacity + block) = uint8_t(quote.total_target_places / 1000); + modern::season_ticket_compensation_source(g, manager, compensation_notice); + return true; +} + +} // namespace bmh::modern diff --git a/src/modern/game/stadium_blocks.hpp b/src/modern/game/stadium_blocks.hpp new file mode 100644 index 0000000..3739d77 --- /dev/null +++ b/src/modern/game/stadium_blocks.hpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "modern/game/modern_state.hpp" +#include "game/stadium_blocks.hpp" + +#include "modern/game/desk_actions.hpp" +#include "modern/game/weekly.hpp" + +#include +#include +#include + +namespace bmh::modern { + +// Source choices 8..15 map to eight independent A–H record slots. These must +// not be confused with StadiumInvestment's facilities 0..7. + + +// An immutable quote binds the Source owner and every record/table value that +// affects the quote. Commit recomputes this value before it touches money. + +// Pure Source projection. Manual totals need not be multiples of 1000; only the +// eventual +54 byte is floored to thousands. The supported source boundary is +// 0..427 company percent, 0..255 thousand places, a positive duration, and +// trusted table maxima <=255000. Current/target placement must satisfy +// current<=target<=maximum; busy blocks, unknown idle feature bits, owner +// mismatches, disabled existing features, malformed constants and any +// intermediate that overflows Source's signed 32-bit arithmetic have no quote. +// A valid zero-price quote remains previewable; commit refuses to construct it. +std::optional quote_stadium_block_expansion( + const ModernState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places, + uint8_t desired_features, int company_price_percent, + const StadiumBlockExpansionConstants& constants); + +// Commit an already resolved tip decision exactly once. `Declined` proceeds at +// the base quote; `Accepted` uses its precomputed price and weeks. A zero-price +// quote never constructs. Notice exceptions propagate so the caller can restore +// its full transaction checkpoint. +bool build_stadium_block_expansion( + ModernState& g, int manager, StadiumBlockSlot slot, + const StadiumBlockExpansionConstants& constants, + const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer, + WatcomRandom& rand, const ConstructionNoticeHook& payment_notice = {}, + const SeasonTicketCompensationNoticeHook& compensation_notice = {}); + +} // namespace bmh::modern diff --git a/src/modern/game/table_forecast.cpp b/src/modern/game/table_forecast.cpp new file mode 100644 index 0000000..a161a92 --- /dev/null +++ b/src/modern/game/table_forecast.cpp @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/table_forecast.hpp" + +#include +#include + +#include "game/schedule.hpp" +#include "modern/game/source_tip.hpp" + +namespace bmh::modern { + +LeagueTableForecast compute_league_table_forecast( + const ModernState& game, int league, int source_param2, int matchdays, + int flags, int normal_mode, int sort_extra, + const std::array& gap, const GameRandom& game_random) { + if (league < 0 || league >= kLeagueCount) + throw std::invalid_argument("table forecast: invalid league"); + if (source_param2 != 0) + throw std::invalid_argument("table forecast: only Source param2 zero is reviewed"); + const int source_matchdays = league_matchdays(league); + if (matchdays != source_matchdays) + throw std::invalid_argument("table forecast: matchday count differs from Source league"); + if (flags < 0 || flags > 7) + throw std::invalid_argument("table forecast: unsupported Source aggregation flags"); + if (normal_mode < 0 || normal_mode > 1 || sort_extra < 0 || sort_extra > 14 || (sort_extra & 1)) + throw std::invalid_argument("table forecast: unsupported Source points/sort parameters"); + if (game.league_rounds.size() < size_t(kLeagueCount) || game.results.size() < kResultsSize) + throw std::invalid_argument("table forecast: Native round/results inputs unavailable"); + + const int points_mode = normal_mode + sort_extra; + LeagueTableForecast out; + out.table = compute_league_table(game, league, 0, matchdays, flags, points_mode); + out.game_after = game_random; + const int raw_round = int(game.league_rounds[size_t(league)]); + out.first_simulated_round = raw_round + (source_param2 != 0); + const int first_team = league_first_team(league); + const int teams = league_table_teams(league); + int32_t source_seed = 0; + if (out.first_simulated_round < matchdays) { + if (!game.memory.has(::bmh::layout::TableForecast_InvalidArgument_RuntimeField)) + throw std::invalid_argument("table forecast: Native Source seed unavailable for future rounds"); + source_seed = std::bit_cast(game.memory.u32(::bmh::layout::CurrentMatchday)); + if (source_seed < 0 || source_seed > 10000) + throw std::invalid_argument("table forecast: Native Source seed outside 0..10000"); + } + + for (int round = out.first_simulated_round; round < matchdays; ++round) { + const auto fixtures = generate_fixtures(teams, round + 1, matchdays / 2, first_team); + // ComputeLeagueTableForecast is invoked once per round and reseeds once at entry, + // before iterating that round's fixture pairs. + out.game_after.set_seed(source_seed); + for (const auto& fixture : fixtures) { + const int home_primary = team_average(game, fixture.home, 0x3f3).value; + const int home_secondary = team_average(game, fixture.home, 0x3fc).value; + const int away_primary = team_average(game, fixture.away, 0x3f3).value; + const int away_secondary = team_average(game, fixture.away, 0x3fc).value; + + // GameRandom::set_seed deliberately preserves the cumulative call count. + const uint8_t encoded = modern::source_tip_result(out.game_after, gap, + home_primary, away_primary, home_secondary, away_secondary); + const int clubs[2] = {fixture.home - first_team, fixture.away - first_team}; + const uint8_t goals[2] = {uint8_t(encoded >> 4), uint8_t(encoded & 0x0f)}; + add_result(out.table, clubs, goals, flags & 3, normal_mode); + } + if (matchdays < round + 3) sort_table(out.table, sort_extra >> 1); + ++out.simulated_rounds; + } + return out; +} + +} // namespace bmh::modern diff --git a/src/modern/game/table_forecast.hpp b/src/modern/game/table_forecast.hpp new file mode 100644 index 0000000..436804a --- /dev/null +++ b/src/modern/game/table_forecast.hpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "modern/game/modern_state.hpp" +#include "game/table_forecast.hpp" + +#include +#include + +#include "game/random.hpp" +#include "game/table.hpp" + +namespace bmh::modern { + +// Scratch result of the Table screen's one-shot KI projection. `game_after` +// contains Source G after all per-ComputeLeagueTableForecast reseeds/draws; callers commit it +// only with the accepted UI/session transition. Native results and CurrentMatchday are +// never changed here. + +// Only the reviewed E37 normal family entry (Source param2 == 0) is supported. +// All work is local: invalid input or a projection exception cannot mutate the +// caller's GameRandom or ModernState. +LeagueTableForecast compute_league_table_forecast( + const ModernState& game, int league, int source_param2, int matchdays, + int flags, int normal_mode, int sort_extra, + const std::array& gap, const GameRandom& game_random); + +} // namespace bmh::modern diff --git a/src/modern/game/turn.cpp b/src/modern/game/turn.cpp new file mode 100644 index 0000000..cb75358 --- /dev/null +++ b/src/modern/game/turn.cpp @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/turn.hpp" +#include "game/trace.hpp" + +#include "modern/game/month.hpp" +#include "modern/game/national.hpp" +#include "modern/game/week.hpp" +#include "modern/game/weekly.hpp" + +namespace bmh::modern { + +bool full_game(const ModernState& g) { return g.memory.has(::bmh::layout::CompetitionSelection) && (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) != 0; } + +void event_end(ModernState& g) { + if (g.memory.has(::bmh::layout::Savestate_Layout_ExecutableField8)) g.memory.set8(::bmh::layout::Turn_EventEnd_RuntimeField, 1); +} + +void day_stock_market(ModernState& g, GameRandom& game) { + if (modern::full_game(g)) modern::stock_market(g, game); +} + +bool month_step(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + if (!modern::full_game(g) || g.date == 0 || modern::month_code(g.date - 1) == modern::month_code(g.date)) return true; + modern::month_change(g, rand, report, &game); // DayStepRest2 + return !report.unsupported; +} + +bool day_step_rest(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + uint16_t source_season_day, TransferAllocatorContext allocator) { + // DayStepRest tests CareerSession_PairingsRuntimeDraw_ExecutableField6 after DeskDate2(date - 1): the weekday of the + // previous day decides whether it is a training day + const int wd = modern::weekday_code(g.date - 1); + const bool training = wd == 2 || wd == 6; + const bool month = modern::full_game(g) && g.date > 0 && modern::month_code(g.date - 1) != modern::month_code(g.date); + // the Bundestrainer leaves the national team for the day's processing: on a training day + // the national squad trains first (FamiliarityDecay), then the slots are swapped back + // (NationalCoachHandBack); at the end he takes it over again (SwapManagerSlots2, ActiveManager left at + // the number of managers by the loop below) + const bool coach = (training || month) && modern::national_coach_active(g); + if (coach) { + if (training) modern::familiarity_decay(g, game, rand); + modern::national_coach_hand_back(g); + } + if (training) { + if (modern::full_game(g) && modern::weekday_code(g.date) == 3) { + turn_step = "weekly_processing"; + modern::weekly_processing(g, game, rand, report, allocator); // DayStepRest3 + if (report.unsupported) return false; + } + turn_step = "training"; + modern::familiarity_decay(g, game, rand); + for (size_t m = 0; m < g.manager_teams.size(); m++) modern::train_squad(g, int(m), game, rand); + } + turn_step = "month_step"; + const bool ok = modern::month_step(g, game, rand, report); + if (coach) modern::national_coach_take_over(g, int(g.manager_teams.size()), source_season_day); + return ok; +} + +} // namespace bmh::modern + +#include "modern/game/matchday_setup.hpp" +#include "modern/game/season.hpp" + +namespace bmh::modern { + +void plain_day(ModernState& g, GameRandom& game, WatcomRandom& rand) { + modern::day_stock_market(g, game); + g.date++; + modern::daily_interest(g, rand); +} + +bool empty_event_day(ModernState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + modern::setup_matchday(g, 0, ctx, game, rand, report); + turn_step = "prepare_event: matchday number"; + modern::draw_matchday_number(g, rand); // CurrentMatchday + modern::shuffle_manager_order(g, game); + modern::event_end(g); + g.date++; + modern::daily_interest(g, rand); + return !report.unsupported; +} + +bool is_season_end(const ModernState& g) { return g.date > 0 && modern::month_code(g.date) == 7 && modern::month_code(g.date - 1) != 7; } + +void season_end_day(ModernState& g) { + if (modern::national_coach_active(g)) modern::national_coach_hand_back(g); // DailyInterest: NationalCoachHandBack first + if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) g.memory.set8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4, 1); + modern::season_awards(g); + if (g.memory.has(::bmh::layout::EventPasses)) g.memory.set8(::bmh::layout::EventPasses, 0); +} + +} // namespace bmh::modern + +#include "modern/game/desk.hpp" + +namespace bmh::modern { + +std::vector prepare_event(ModernState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game, + WatcomRandom& rand, MinuteReport& report) { + std::vector groups = modern::setup_matchday(g, modern::day_competitions(g, calendar_entry), ctx, game, rand, report); + modern::draw_matchday_number(g, rand); // CurrentMatchday + turn_step = "prepare_event: manager order"; + const std::vector order = modern::shuffle_manager_order(g, game); + for (size_t k = 0; k < order.size() && g.memory.has(::bmh::layout::NextDeskManager + uint32_t(k) * 2); k++) + g.memory.set16(::bmh::layout::NextDeskManager + uint32_t(k) * 2, uint16_t(order[k])); + return groups; +} + +bool enter_event_desk(ModernState& g, int position, const std::vector& groups, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer, + const DeskAutosaveHook& autosave) { + const int manager = g.manager_teams.size() > 1 ? g.memory.u16(::bmh::layout::NextDeskManager + uint32_t(position) * 2) : position; + if (g.memory.has(::bmh::layout::DeskPosition)) g.memory.set8(::bmh::layout::DeskPosition, uint8_t(position)); + if (g.memory.has(::bmh::layout::ActiveManager)) g.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager)); + // AdvanceTurn(param1 != 0) suppresses only PreMatchOffer on the remaining + // desks of a loaded manager loop. Coupon preparation and desk entry still run. + // (an out-of-range access below names its step: the error reaches the player as text) + const char* step = "pre_match_offer"; + try { + const bool offer = prepare_pre_match_offer + ? modern::pre_match_offer(g, manager, game, rand, report) : false; + step = "build_pools_coupon"; + modern::build_pools_coupon(g, groups, &rand); // BuildPoolsCoupon + step = "enter_desk"; + modern::enter_desk(g, manager, game, rand, autosave); // DeskDate + return offer; + } catch (const std::out_of_range& e) { + throw std::out_of_range(std::string(e.what()) + " (" + step + ", manager " + std::to_string(manager) + ")"); + } +} + +} // namespace bmh::modern + +#include "formats/binary.hpp" +#include "modern/game/cup.hpp" +#include "modern/game/matchday.hpp" + +namespace bmh::modern { + +void finish_event(ModernState& g, std::vector& groups, uint16_t calendar_entry, const std::vector& buttons, + const std::vector& saved_records, const std::vector& saved_options, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw, + const SportschauPresentationHooks* sportschau, const std::vector* show_events, + bool source_sportschau_replay, const SportschauRatingTables* ratings) { + if (report.unsupported) return; + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (int s = 0; s < 24; s++) + for (int k = 0; k < 2; k++) { + const size_t at = m * 0x840 + size_t(s) * 0x58 + 0x44 + size_t(k) * 2; + g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F; + } + auto show_intro = [&](int group_index) { + if (!sportschau || !sportschau->intro) return; + SportschauIntroView view; + view.group_index = group_index; + for (size_t i = 0; i < groups.size() && i <= 0xff; ++i) { + const MatchGroup& group = groups[i]; + view.groups.push_back({uint8_t(i), group.desc.at(0), le32(group.desc, 0xcc), + int16_t(modern::sportschau_source_setting_index(g, group))}); + } + sportschau->intro(g, view); + }; + show_intro(-1); + for (size_t group_index = 0; group_index < groups.size(); ++group_index) { + MatchGroup& grp = groups[group_index]; + // FinishEvent sets DeskPosition to the current match-group index. Its final nonempty + // iteration leaves the last index visible to the following cup presentation. + if (g.memory.has(::bmh::layout::DeskPosition) && group_index <= 0xff) + g.memory.set8(::bmh::layout::DeskPosition, uint8_t(group_index)); + if (group_index <= 0xff) show_intro(int(group_index)); + if (ratings && !source_sportschau_replay) { + // FinishEvent/BuildSideRecords clear eleven scores outside the CareerSession_SportschauSourceOptions_ExecutableField gate. + // The loaded EXE owner still performs that reset when it skips + // MatchdayIntro entirely; old slot words remain untouched. + for (size_t i = 0; i < 11; ++i) { + grp.desc.at(0x70 + i) = 0; + const uint32_t address = ::bmh::layout::Turn_FinishEvent_ExecutableField + uint32_t(group_index) * 0xd0 + uint32_t(i); + if (group_index < 6 && g.memory.has(address)) g.memory.set8(address, 0); + } + } + modern::process_group(g, grp, game, rand, report, int(group_index), + sportschau ? sportschau->fixture : SportschauFixtureHook{}, show_events, + source_sportschau_replay && sportschau ? &sportschau->replay : nullptr, + source_sportschau_replay ? ratings : nullptr); + if (report.unsupported) return; + if (source_sportschau_replay && ratings) { + const auto awards = finish_sportschau_awards(g, grp, int(group_index)); + if (awards && sportschau && sportschau->awards) sportschau->awards(g, *awards); + if (sportschau && sportschau->team_info) { + const auto info = sportschau_team_info_view(g, grp, int(group_index)); + if (info) sportschau->team_info(g, *info); + } + } + const uint32_t id = le32(grp.desc, 0xcc); + if (id < 0x15) { + if (modern::league_screen_shown(buttons, 1, 90, int(id))) modern::stir_random(game, rand); + const int round = g.league_rounds.at(id); + for (int m = 0; m < grp.matches(); m++) g.results.at(size_t(id) * 0x17C + size_t(round) * 10 + size_t(m)) = grp.results.at(size_t(m)); + } else { + modern::store_cup_results(g, grp); + } + } + // FinishEvent/BuildSideRecords call EvaluatePoolsCoupon(1) after every group's processing, + // before returning to AdvanceTurn's calendar/round advancement. Result evaluation + // at the second half is separate; pools_open does not gate this settlement. + modern::settle_pools_coupon(g, groups); + for (size_t m = 0; m < g.manager_teams.size() && !saved_records.empty(); m++) { + for (size_t k = 0; k < 8; k++) g.manager_records.at(m * 0xB0C + 0xd2 + k) = saved_records.at(m * 0xB0C + 0xd2 + k); + g.manager_options.at(m * 5 + 2) = saved_options.at(m * 5 + 2); + } + const uint32_t competitions = modern::day_competitions(g, calendar_entry); + modern::advance_league_rounds(g, competitions & 0x1F, rand, report, + sportschau ? sportschau->winner : CompetitionWinnerHook{}); + for (int bit = 5; bit < 0x13; bit++) + if ((competitions >> bit) & 1) modern::advance_cup(g, bit - 5, rand, report, &game, cup_draw, + sportschau ? sportschau->winner : CompetitionWinnerHook{}); + modern::event_end(g); +} + +} // namespace bmh::modern diff --git a/src/modern/game/turn.hpp b/src/modern/game/turn.hpp new file mode 100644 index 0000000..39c7b42 --- /dev/null +++ b/src/modern/game/turn.hpp @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/turn.hpp" +// The "Weiter" loop of the original (DailyInterest) - everything between two desks of the +// human managers: the day steps, the weekly and monthly processing, the matchdays with +// their preparation, the cups, the season end and the season change. +// +// Built up step by step from the parts verified with tests/week_check (which uses these +// functions, so every regression run checks them against the recordings). + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/season.hpp" +#include "game/sportschau_presentation.hpp" +#include "modern/game/modern_state.hpp" +#include "game/transfer_allocator.hpp" + +namespace bmh::modern { + +// Whether the career plays the leagues (CompetitionSelection bit 0, "full game"); without them +// there is no weekly or monthly processing. +bool full_game(const ModernState& g); +// DailyInterest: the daily share price run (DailyInterest3) only with the leagues on +// (CompetitionSelection bit 0) - the world game without leagues keeps its prices. +void day_stock_market(ModernState& g, GameRandom& game); +// The end of AdvanceTurn: EventEnd(TurnRuntimeField), with the value layout field the program +// start leaves there, sets Turn_EventEnd_RuntimeField = 1. +void event_end(ModernState& g); + +// The rest of the day step DayStepRest after the date moved on: on a training day (the +// previous day's weekday code 2 or 6) the weekly processing (DayStepRest3, full game, +// when the new day has weekday code 3), the decay of the familiarity and every human +// manager's training; then the month change (DayStepRest2) when the month moved on. +// Returns false on a reported state/context failure; see MinuteReport::reason. +bool day_step_rest(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + uint16_t source_season_day, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +// The month change part alone (full game only, when the new day is in another month). +bool month_step(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh::modern + +namespace bmh::modern { + + +// A day without an event (the "Weiter" loop): the shares move (DailyInterest3), then the +// date counts on and the daily interest is booked (the start of DayStepRest). The rest +// of the day step (day_step_rest) follows. +void plain_day(ModernState& g, GameRandom& game, WatcomRandom& rand); + +// A calendar entry whose competitions are all switched off (e.g. 0x4006 without the +// option CompetitionSelection bit 1) is still an event for DailyInterest: AdvanceTurn prepares an +// empty matchday (DayCompetitions2, the matchday number, the manager order) without a desk; +// then the date counts on (with the daily interest) as after any event. +bool empty_event_day(ModernState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// 1 July (DailyInterest: CareerSession_PairingsRuntimeDraw_ExecutableField4 == 1, CareerSession_PairingsRuntimeDraw_ExecutableField5 == 7): the season is over - +// CareerSession_RuntimeError_RuntimeField4 = 1, the prizes for top scorers and fair play (SeasonAwards); no event is +// due any more (EventPasses = 0). The managers' "Saisonende" desk follows. +bool is_season_end(const ModernState& g); +void season_end_day(ModernState& g); + +} // namespace bmh::modern + +#include +#include "modern/game/desk.hpp" + +namespace bmh::modern { + +// AdvanceTurn up to its desk loop for the day's calendar entry: the match groups +// (DayCompetitions2), the matchday number (CurrentMatchday) and the shuffled order of the +// managers' desks (PrepareEvent, kept in NextDeskManager). +std::vector prepare_event(ModernState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game, + WatcomRandom& rand, MinuteReport& report); + +// One pass of that desk loop for the manager at `position` of the order: ActiveManager / +// DeskPosition, a pre-match offer (PreMatchOffer; true = its message box comes first), the +// pools coupon (BuildPoolsCoupon) and entering the desk (DeskDate). +bool enter_event_desk(ModernState& g, int position, const std::vector& groups, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer = true, + const DeskAutosaveHook& autosave = {}); + +} // namespace bmh::modern + +namespace bmh::modern { + +// The end of a matchday after its last phase (the part of FinishEvent / AdvanceTurn after +// the matches): the human boards' substitution marks are cleared, every group is processed +// (process_group; a league's result screen - when shown - stirs the numbers, its results go +// into the season table, a cup's into its rounds), the managers' match settings changed +// during the matches (record +0xd2..+0xd9, option byte 2) return to `saved_records` / +// `saved_options` (taken at the kick-off), the leagues count their round and the cups of the +// day move on. +void finish_event(ModernState& g, std::vector& groups, uint16_t calendar_entry, const std::vector& buttons, + const std::vector& saved_records, const std::vector& saved_options, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw = {}, + const SportschauPresentationHooks* sportschau = nullptr, + const std::vector* show_events = nullptr, + bool source_sportschau_replay = false, + const SportschauRatingTables* ratings = nullptr); + +} // namespace bmh::modern diff --git a/src/modern/game/turn_driver.cpp b/src/modern/game/turn_driver.cpp new file mode 100644 index 0000000..ffaa41f --- /dev/null +++ b/src/modern/game/turn_driver.cpp @@ -0,0 +1,594 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/turn_driver.hpp" + +#include +#include +#include + +#include "modern/game/desk.hpp" +#include "modern/game/driver.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" +#include "game/trace.hpp" +#include "modern/game/national.hpp" +#include "modern/game/season.hpp" +#include "modern/game/turn.hpp" +#include "modern/game/week.hpp" + +namespace bmh::modern { +namespace { + +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; +// The calendar entry of a season day. The table has 366 days (0-365); a season that starts +// on 1 July and spans 29 February ends on day 366, where the original reads the next bytes +// of its data (the fixture pointer table at CareerSession_RuntimeError_ExecutableField) - no competition. OpenBMH deviates from +// the original here: such a day has no calendar entry (0) instead of whatever lies behind. +uint16_t calendar_day(const ModernState& g, int day) { + const uint32_t at = kCalendar + uint32_t(day) * 2; + return day >= 0 && g.memory.has(at + 1) && at + 1 < ::bmh::layout::CareerSession_RuntimeError_ExecutableField ? g.memory.u16(at) : uint16_t(0); +} +constexpr uint32_t kDeskButtons = ::bmh::layout::LeaguePresentationOptions; +constexpr uint32_t kSavedCompetition = ::bmh::layout::SavedCompetition; +constexpr uint32_t kCoachActive = ::bmh::layout::CoachActive; +constexpr uint32_t kOriginalManagerCount = ::bmh::layout::OriginalManagerCount; +constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount; +constexpr uint32_t kManagerOrder = ::bmh::layout::NextDeskManager; +constexpr uint32_t kDeskPosition = ::bmh::layout::DeskPosition; +constexpr uint32_t kActiveManager = ::bmh::layout::ActiveManager; +constexpr uint32_t kEventPasses = ::bmh::layout::EventPasses; + +// DailyInterest sets the saved loop count once per calendar date: three Hall +// rounds on the first of two consecutive Hall days, two on the last day. +// Completing a round does not run another date/training/interest step. +void start_event_passes(ModernState& g, uint16_t entry) { + if (!g.memory.has(kEventPasses)) return; + uint8_t passes = 1; + if (entry == 0x4002) { + const uint32_t next = kCalendar + uint32_t(g.season_day() + 1) * 2; + passes = g.memory.has(next + 1) && g.memory.u16(next) == 0x4002 ? 3 : 2; + } + g.memory.set8(kEventPasses, passes); +} + +bool consume_event_pass(TurnDriver& driver, ModernState& g) { + if (!g.memory.has(kEventPasses)) return false; + // Only the Hall calendar cell has multiple passes. Old OpenBMH saves + // carried a stale Hall count into ordinary dates; do not repeat leagues. + const bool hall = driver.calendar_entry == 0x4002 && g.indoor; + const uint8_t count = hall ? g.memory.u8(kEventPasses) : 1; + const uint8_t remaining = count == 0 ? 0 : uint8_t(count - 1); + g.memory.set8(kEventPasses, remaining); + return hall && remaining != 0; +} + +std::vector read_buttons(const ModernState& g) { + std::vector result; + if (!g.memory.has(kDeskButtons + 0xb3)) return result; + result.reserve(0xb4); + for (uint32_t i = 0; i < 0xb4; ++i) result.push_back(g.memory.u8(kDeskButtons + i)); + return result; +} + +MatchdayContext matchday_context(const ModernState& g, std::vector& referees) { + MatchdayContext context; + context.month = modern::month_code(g.date); + context.season_day = g.season_day(); + context.weekday = modern::weekday_code(g.date); + context.referees = &referees; + return context; +} + +bool saved_national_nomination_desk(const ModernState& g, const std::vector& groups, + uint16_t calendar_entry) { + const auto& mem = g.memory; + if (!groups.empty() || g.manager_teams.size() != 1 || g.manager_teams[0] != no_team() || + !mem.has(kCalendar + uint32_t(g.season_day()) * 2 + 1) || + !mem.has(kSavedCompetition + 3) || !mem.has(kCoachActive) || + !mem.has(kOriginalManagerCount) || !mem.has(kManagerCount) || + !mem.has(kManagerOrder + 1) || !mem.has(kDeskPosition) || !mem.has(kActiveManager)) + return false; + const uint16_t saved_entry = mem.u16(kCalendar + uint32_t(g.season_day()) * 2); + if (saved_entry != calendar_entry || modern::day_competitions(g, saved_entry) != 0x800000 || + mem.u32(kSavedCompetition) != 0 || mem.u8(kCoachActive) == 0 || + mem.u8(kManagerCount) != 1 || mem.u8(kOriginalManagerCount) < 1 || + mem.u8(kOriginalManagerCount) > 4 || mem.u16(kManagerOrder) >= mem.u8(kOriginalManagerCount) || + mem.u8(kDeskPosition) != 0 || mem.u8(kActiveManager) != 0) + return false; + return true; +} + +TurnAdvanceResult fail(TurnDriver& driver, const ModernState& g, const MinuteReport& report, + const char* fallback) { + driver.stage = TurnDriver::Stage::Failed; + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + out.date = g.date; + out.revision = driver.revision; + out.reason = report.reason.empty() ? fallback : report.reason; + return out; +} + +TurnAudioEvent audio_event(TurnDriver& driver, TurnAudioKind kind) { + // Cue mapping is deliberately absent until a concrete original call site is proven. + return {driver.session_id, driver.next_event_id++, kind, std::nullopt}; +} + +TurnAdvanceResult desk_result(TurnDriver& driver, const ModernState& g, TurnDeskKind kind, + bool offer_pending = false) { + TurnAdvanceResult out; + out.kind = kind; + out.manager_slot = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + out.date = g.date; + out.revision = driver.revision; + out.offer_pending = offer_pending; + return out; +} + +bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, + std::vector& events) { + const std::vector saved_records = g.manager_records; + const std::vector saved_options = g.manager_options; + MatchdayContext context = matchday_context(g, driver.referees); + + turn_step = "kick_off"; + modern::kick_off(g, driver.groups, context, rand, game, report, + driver.sportschau_source.intro_after_matchday != 0, + driver.sportschau_source.rated_club_threshold); + if (report.unsupported) return false; + if (driver.sportschau_source.intro_after_matchday != 0 && driver.sportschau.kickoff) { + const auto intro = matchday_intro_view(g, driver.groups); + if (intro) driver.sportschau.kickoff(g, *intro); + } + bool manager_match_played = false; + for (const MatchGroup& group : driver.groups) + for (int m = 0; m < group.matches(); ++m) { + if (group.void_mask() >> m & 1) continue; + const size_t fixture = size_t(m * 2); + if (fixture + 1 < group.fixtures.size() && + (g.manager_of(group.fixtures[fixture]) >= 0 || + g.manager_of(group.fixtures[fixture + 1]) >= 0)) + manager_match_played = true; + } + // Matchday resolution is synchronous. Emit cues only for fixtures involving a + // human-managed club so background AI schedules do not flood the audio queue. + if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::kickoff_whistle)); + + MatchEngine engine{g, driver.groups, game, rand, driver.referees}; + if (driver.original_sound) { + engine.original_sound = [&driver, &g](uint8_t id) { driver.original_sound(id, g); }; + if (manager_match_played) engine.original_sound(3); // EndPhase / ReadButtons, crowd. + } + std::vector sportschau_show_events; + if (driver.sportschau.fixture) engine.show = &sportschau_show_events; + engine.month = context.month; + engine.buttons = read_buttons(g); + engine.reality_rules = driver.reality_rules; + engine.live_scene_visible = g.live_scene && driver.reality_rules; + engine.phase_results = driver.phase_results; + if (driver.live_reality) { + engine.live_reality = [&driver, &g](const LiveRealityEvent& event) { + return driver.live_reality(event, driver.groups, g); + }; + } + // LiveDeskDisabled is a saved settings byte. It also changes attitude, assistant + // substitutions and RNG consumption, so a background driver must preserve it. + engine.live_desk_disabled = g.memory.has(::bmh::layout::LiveDeskDisabled) && g.memory.u8(::bmh::layout::LiveDeskDisabled) != 0; + engine.alternate_event_roll = driver.alternate_match_event_roll; + engine.match_events_disabled = driver.disable_match_events; + engine.leave_screens = true; + if (driver.live_shootout) { + engine.live_shootout = [&driver, &g](const LiveShootoutEvent& event) { + driver.live_shootout(event, driver.groups, g); + }; + } + if (driver.live_booking) { + engine.live_booking = [&driver, &g](const LiveBookingEvent& event) { + driver.live_booking(event, driver.groups, g); + }; + } + if (driver.live_set_piece) { + engine.live_set_piece = [&driver, &g](const LiveSetPieceEvent& event) { + driver.live_set_piece(event, driver.groups, g); + }; + } + if (driver.live_shot) { + engine.live_shot = [&driver, &g](const LiveShotEvent& event) { + driver.live_shot(event, driver.groups, g); + }; + } + if (driver.live_chance) { + engine.live_chance = [&driver, &g](const LiveChanceEvent& event) { + driver.live_chance(event, driver.groups, g); + }; + } + if (driver.live_ball) { + engine.live_ball = [&driver, &g](const LiveBallEvent& event) { + driver.live_ball(event, driver.groups, g); + }; + } + if (driver.live_event) { + engine.live_event = [&driver, &engine](const LiveMatchEvent& event) { + driver.live_event(event, engine, driver.groups, static_cast(engine.state)); + }; + } + std::vector>> previous(driver.groups.size()); + for (size_t gi = 0; gi < driver.groups.size(); ++gi) { + const MatchGroup& group = driver.groups[gi]; + previous[gi].resize(size_t(group.matches())); + for (int m = 0; m < group.matches(); ++m) { + int home = 0, away = 0; + modern::match_score(group, m, home, away); + previous[gi][size_t(m)] = {home, away}; + } + } + bool manager_match_scored = false; + auto collect_goals = [&](int) { + for (size_t gi = 0; gi < driver.groups.size(); ++gi) { + const MatchGroup& group = driver.groups[gi]; + for (int m = 0; m < group.matches(); ++m) { + const size_t fixture = size_t(m * 2); + if ((group.void_mask() >> m & 1) || fixture + 1 >= group.fixtures.size() || + (g.manager_of(group.fixtures[fixture]) < 0 && + g.manager_of(group.fixtures[fixture + 1]) < 0)) + continue; + int home = 0, away = 0; + if (!modern::match_score(group, m, home, away)) continue; + auto& old = previous[gi][size_t(m)]; + const int goals = std::max(0, home - old[0]) + std::max(0, away - old[1]); + manager_match_scored = manager_match_scored || goals > 0; + old = {home, away}; + } + } + }; + auto after_minute = [&](int minute) { + collect_goals(minute); + if (driver.live_minute) driver.live_minute(minute, engine, driver.groups, g); + }; + turn_step = "play_matchday"; + modern::play_matchday(engine, g, driver.groups, engine.buttons, game, rand, report, after_minute); + if (report.unsupported) return false; + // The app receives the whole synchronous turn at once. One summary goal cue + // per manager matchday is bounded and avoids replaying a stream of missed goals. + if (manager_match_scored) events.push_back(audio_event(driver, TurnAudioKind::goal)); + if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::full_time_whistle)); + + turn_step = "finish_event"; + modern::store_group_descriptors(g, driver.groups, true); + modern::finish_event(g, driver.groups, driver.calendar_entry, engine.buttons, + saved_records, saved_options, game, rand, report, driver.season_cup_draw, + &driver.sportschau, &sportschau_show_events, + driver.sportschau_source.intro_after_matchday != 0, + driver.sportschau_source.ratings ? &*driver.sportschau_source.ratings : nullptr); + return !report.unsupported; +} + +bool next_event(TurnDriver& driver, ModernState& g, GameRandom& game, WatcomRandom& rand, + MinuteReport& report, bool& offer_pending, bool after_event, + bool first_day_preprocessed = false, bool repeat_event = false) { + for (int day = 0; day < 366 * 5; ++day) { + // DailyInterest enters AdvanceTurn on season day zero even when its + // calendar cell is empty. The prepared first Wednesday is a manager + // desk, not a day to skip while seeking the first scheduled fixture. + const bool opening_desk = first_day_preprocessed && g.season_day() == 0; + // DailyInterest advances DaysIntoSeason before DayStepRest on a quiet day, + // but after DayStepRest when completing an event. Preserve that Source-visible + // context for a nested Bundestrainer re-takeover; the typed date is already one + // day ahead in the latter case. + const uint16_t source_rest_day = uint16_t( + g.date - g.season_start - uint32_t(after_event ? 1 : 0)); + turn_step = "day_step_rest"; + if (!first_day_preprocessed && + !modern::day_step_rest(g, game, rand, report, source_rest_day, + driver.transfer_allocator_context)) return false; + // DailyInterest tests for 1 July only after DayStepRest has advanced a day. The + // prepared first day of a new season is not such a step: when 1 July is itself the + // first Wednesday (2037), the season change leaves the date there, and testing it + // again started the season change over and over (endless loop after ten seasons). + const bool day_stepped = !first_day_preprocessed; + first_day_preprocessed = false; + if (day_stepped && modern::is_season_end(g)) { + turn_step = "season_end_day"; + modern::season_end_day(g); + // DailyInterest calls AdvanceTurn after the annual awards. DayCompetitions2's + // closing branch supplies FF opponents / competition32 without + // preparing teams, fixtures or cycling manager options. Its old + // descriptors remain available to BuildPoolsCoupon's coupon scan. + if (modern::full_game(g)) { // DailyInterest calls this desk loop only with leagues. + driver.calendar_entry = calendar_day(g, g.season_day()); + const uint32_t closing_competitions = modern::day_competitions(g, driver.calendar_entry); + g.memory.set32(kSavedCompetition, closing_competitions == 0x800000 ? 0 : closing_competitions); + modern::draw_matchday_number(g, rand); + modern::shuffle_manager_order(g, game); + driver.manager_position = 0; + driver.national_nomination_desk = false; + turn_step = "enter_closing_desk"; + offer_pending = modern::enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave); + if (report.unsupported) return false; + } + driver.stage = TurnDriver::Stage::SeasonEndDesk; + ++driver.revision; + return true; + } + + turn_step = "stock market"; + if (after_event) modern::day_stock_market(g, game); + after_event = false; + const uint16_t entry = calendar_day(g, g.season_day()); + if (!(entry & 0x7fff) && !opening_desk) { + turn_step = "plain_day"; + modern::plain_day(g, game, rand); + continue; + } + turn_step = "calendar day"; + const uint32_t competitions = modern::day_competitions(g, entry); + driver.referees = driver.referee_source; // clear the per-day chosen flags + MatchdayContext context = matchday_context(g, driver.referees); + if (competitions == 0 && !opening_desk) { + turn_step = "empty_event_day"; + if (!modern::empty_event_day(g, context, game, rand, report)) return false; + after_event = true; + continue; + } + if (competitions == 0x800000 && !opening_desk) { + // The return means that a human national-coach desk follows, not + // that the calendar step succeeded. The ordinary no-coach case + // still performs the Source national-team preparation and continues. + const bool has_national_coach = modern::national_team_day(g, rand, report); + if (report.unsupported) return false; + const bool enter_national_desk = has_national_coach && driver.enable_national_nomination_desks; + // AdvanceTurn clears the transient competition result before its empty + // setup. Keep the legacy/no-coach behavior byte-identical; the opted-in + // coach path clears it before preparing the real national desk. + if (enter_national_desk) { + if (g.manager_teams.size() != 1 || g.manager_teams[0] != no_team()) { + report.fail("national nomination returned a coach without the one-manager national context"); + return false; + } + if (g.memory.has(kSavedCompetition + 3)) g.memory.set32(kSavedCompetition, 0); + context.national_team_day = true; + } + turn_step = "modern::setup_matchday (national)"; + const std::vector none = modern::setup_matchday(g, 0, context, game, rand, report); + if (report.unsupported) return false; + if (!none.empty()) { + report.fail("national team day unexpectedly prepared match groups"); + return false; + } + modern::draw_matchday_number(g, rand); + modern::shuffle_manager_order(g, game); + if (enter_national_desk) { + driver.calendar_entry = entry; + driver.groups = none; + driver.manager_position = 0; + turn_step = "enter_event_desk"; + offer_pending = modern::enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave); + if (report.unsupported) return false; + driver.national_nomination_desk = true; + driver.stage = TurnDriver::Stage::MatchdayDesks; + ++driver.revision; + return true; + } + modern::event_end(g); + ++g.date; + modern::daily_interest(g, rand); + after_event = true; + continue; + } + + driver.calendar_entry = entry; + if (!repeat_event) start_event_passes(g, entry); + repeat_event = false; + turn_step = "prepare_event"; + driver.groups = modern::prepare_event(g, entry, context, game, rand, report); + if (report.unsupported) return false; + if (!modern::matchday_needs_manager_desks(g, entry, driver.groups)) { + std::vector background_events; + if (!run_current_matchday(driver, g, game, rand, report, background_events)) return false; + if (consume_event_pass(driver, g)) { + first_day_preprocessed = true; + repeat_event = true; + continue; + } + ++g.date; + modern::daily_interest(g, rand); + after_event = true; + continue; + } + driver.manager_position = 0; + turn_step = "enter_event_desk"; + offer_pending = modern::enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave); + if (report.unsupported) return false; + driver.stage = TurnDriver::Stage::MatchdayDesks; + ++driver.revision; + return true; + } + report.fail("turn driver exceeded five seasons without a manager desk"); + return false; +} + +} // namespace + +bool begin_turn_driver(TurnDriver& driver, const ModernState& g, std::vector groups, + uint16_t calendar_entry, std::vector referees, + uint64_t session_id, uint64_t revision, std::string& error) { + if (driver.stage != TurnDriver::Stage::Empty || revision == 0 || session_id == 0) { + error = "turn driver is already active or has invalid identity"; + return false; + } + if (g.manager_teams.empty()) { + error = "turn driver needs at least one human manager"; + return false; + } + driver.stage = TurnDriver::Stage::MatchdayDesks; + driver.calendar_entry = calendar_entry; + driver.manager_position = g.memory.has(::bmh::layout::DeskPosition) ? int(g.memory.u8(::bmh::layout::DeskPosition)) : 0; + driver.revision = revision; + driver.session_id = session_id; + driver.groups = std::move(groups); + driver.referee_source = std::move(referees); + driver.referees = driver.referee_source; + driver.national_nomination_desk = saved_national_nomination_desk( + g, driver.groups, calendar_entry); + return true; +} + +TurnAdvanceResult advance_to_next_desk(TurnDriver& driver, ModernState& g, + const TurnAdvanceRequest& request, + GameRandom& game, WatcomRandom& rand, + MinuteReport& report) { + const int active_manager = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + // AdvanceTurn restores the retained club-order owner after every temporary + // national desk, including desks with real fixtures. That owner can be1–3 + // although the visible/runtime national manager is0. Qualify the completed + // pending batch below without turning an actual match into a nomination day. + const bool national_handoff = driver.enable_national_nomination_desks && + (driver.national_nomination_desk || + (g.manager_teams.size() == 1 && g.manager_teams[0] == no_team() && + g.memory.has(kCoachActive) && g.memory.u8(kCoachActive) != 0)); + if (national_handoff) { + const int original_count = g.memory.has(kOriginalManagerCount) + ? int(g.memory.u8(kOriginalManagerCount)) : 0; + const int source_owner = g.memory.has(kManagerOrder + 1) + ? int(g.memory.u16(kManagerOrder)) : -1; + const bool completed_pending = g.memory.has(kDeskPosition) && + g.memory.u8(kDeskPosition) == 1 && active_manager == source_owner && + original_count >= 1 && original_count <= 4 && source_owner >= 0 && + source_owner < original_count; + if (!completed_pending) { + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = active_manager; + out.date = g.date; + out.revision = driver.revision; + out.reason = "national_nomination_pending_not_completed"; + return out; + } + if (driver.stage != TurnDriver::Stage::MatchdayDesks || + request.manager_slot != 0 || driver.manager_position != 0 || + request.revision != driver.revision || g.manager_teams.size() != 1 || + g.manager_teams[0] != no_team() || !g.memory.has(kCoachActive) || + g.memory.u8(kCoachActive) == 0 || !g.memory.has(kManagerCount) || + g.memory.u8(kManagerCount) != 1) { + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = active_manager; + out.date = g.date; + out.revision = driver.revision; + out.reason = "stale_national_coach_manager_or_revision"; + return out; + } + } else if ((driver.stage != TurnDriver::Stage::MatchdayDesks && driver.stage != TurnDriver::Stage::SeasonEndDesk) || + request.manager_slot != active_manager || request.revision != driver.revision) { + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = active_manager; + out.date = g.date; + out.revision = driver.revision; + out.reason = "stale_manager_or_revision"; + return out; + } + + // Claim the request before any RNG or state mutation. A failure is terminal for this + // cursor, so replaying the same request cannot repeat a partially completed turn. + const auto previous_stage = driver.stage; + driver.stage = TurnDriver::Stage::Failed; + std::vector events; + bool offer_pending = false; + try { + if (driver.manager_position + 1 < int(g.manager_teams.size())) { + ++driver.manager_position; + const bool prepare_pre_match_offer = + !(driver.loaded_matchday_resume && driver.suppress_remaining_pre_match_offers); + turn_step = "enter_event_desk"; + offer_pending = modern::enter_event_desk(g, driver.manager_position, driver.groups, + game, rand, report, prepare_pre_match_offer, driver.desk_autosave); + if (report.unsupported) return fail(driver, g, report, "manager pre-match desk unsupported"); + driver.stage = previous_stage; + ++driver.revision; + return desk_result(driver, g, previous_stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + } + if (previous_stage == TurnDriver::Stage::SeasonEndDesk) { + // Every manager has now left the closing desk. Do not carry the + // loaded desk-resume policy into the annual transition or a new event. + driver.complete_loaded_manager_loop(); + // AdvanceTurn's completed manager-desk loop leaves DeskPosition == ManagerCount + // before DailyInterest enters the annual transition. This native byte is + // serialized at modal checkpoints; the next real desk resets it. + if (g.memory.has(::bmh::layout::DeskPosition)) + g.memory.set8(::bmh::layout::DeskPosition, g.memory.has(::bmh::layout::ManagerCount) + ? g.memory.u8(::bmh::layout::ManagerCount) : uint8_t(g.manager_teams.size())); + const auto outcome = modern::season_transition(g, game, rand, report, driver.season_pause + ? std::function([&](const char* screen) { driver.season_pause(screen, g); }) + : std::function{}, driver.season_highscore, driver.season_tax, + driver.season_promotion, driver.season_cup_draw, driver.transfer_allocator_context); + if (report.unsupported || outcome == SeasonTransitionOutcome::Failed) + return fail(driver, g, report, "season transition unsupported"); + if (outcome == SeasonTransitionOutcome::CareerComplete) { + driver.stage = TurnDriver::Stage::CareerComplete; + ++driver.revision; + return desk_result(driver, g, TurnDeskKind::CareerComplete); + } + driver.stage = TurnDriver::Stage::MatchdayDesks; + // season_end_steps has already performed the calendar days up to the new + // season's first Wednesday; the next loop starts from that prepared date. + if (!next_event(driver, g, game, rand, report, offer_pending, false, true)) + return fail(driver, g, report, "season transition could not reach a desk"); + auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + out.audio_events = std::move(events); + return out; + } + + // The current manager desk loop is complete, so these flags have no further + // desk to govern. Consume them before match simulation and future event setup. + driver.complete_loaded_manager_loop(); + if (driver.enable_national_nomination_desks && driver.national_nomination_desk) { + // AdvanceTurn's national nomination event has an empty desk, not a + // matchday: Source skips kick_off/play/finish and advances the event + // calendar directly after the pending cleanup performed by App. + driver.national_nomination_desk = false; + modern::event_end(g); + ++g.date; + modern::daily_interest(g, rand); + if (!next_event(driver, g, game, rand, report, offer_pending, true)) + return fail(driver, g, report, "national nomination could not advance to next desk"); + auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + out.audio_events = std::move(events); + return out; + } + // A legacy caller can bind a genuine saved national desk, but it keeps the + // historic matchday path unless the App explicitly opted into this lifecycle. + driver.national_nomination_desk = false; + const auto result_tournament_name = g.tournament_name; + if (!run_current_matchday(driver, g, game, rand, report, events)) + return fail(driver, g, report, "matchday unsupported"); + driver.last_results.valid = true; + driver.last_results.date = g.date; + driver.last_results.calendar_entry = driver.calendar_entry; + driver.last_results.matchday = g.memory.has(::bmh::layout::CurrentMatchday) ? g.memory.u16(::bmh::layout::CurrentMatchday) : 0; + driver.last_results.groups = driver.groups; + driver.last_results.tournament_name = result_tournament_name; + const bool repeat = consume_event_pass(driver, g); + if (!repeat) { + ++g.date; + modern::daily_interest(g, rand); + } + if (!next_event(driver, g, game, rand, report, offer_pending, !repeat, repeat, repeat)) + return fail(driver, g, report, "could not advance to next desk"); + auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + out.audio_events = std::move(events); + return out; + } catch (const std::exception& ex) { + report.fail(std::string("turn driver exception: ") + ex.what() + " (in " + std::string(turn_step.load()) + ")"); + return fail(driver, g, report, "turn driver exception"); + } +} + +} // namespace bmh::modern diff --git a/src/modern/game/turn_driver.hpp b/src/modern/game/turn_driver.hpp new file mode 100644 index 0000000..ec13cfe --- /dev/null +++ b/src/modern/game/turn_driver.hpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/turn_driver.hpp" + +#include +#include +#include +#include +#include + +#include "game/match_engine.hpp" +#include "modern/game/desk.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/season.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/transfer_allocator.hpp" + +namespace bmh::modern { + + +// Controller-level sound events carry stable identities. An original cue is optional: +// only attach one when its concrete BMH call site is mapped to a cue by evidence. + +// WaitingAtDesk has not claimed the driver: its original request may be retried. + +// Read-only-ready copy of the most recently completed human matchday. Kept apart +// from `groups`, which is replaced while seeking the next calendar event. + +// Runtime state between a desk's kickoff request and the next desk. The group objects, +// referee table, presentation settings and random generators remain owned by the caller/ +// controller for each synchronous advance; only this cursor survives the desk handoff. + +// Bind an event already prepared by prepare_event and with its first human desk open. +// No generators are drawn here; the object becomes the only accepted continuation for it. +bool begin_turn_driver(TurnDriver& driver, const ModernState& g, std::vector groups, + uint16_t calendar_entry, std::vector referees, + uint64_t session_id, uint64_t revision, std::string& error); + +// Accept the current desk's advance request, show the next manager desk when applicable, +// then play the event in the background and advance through calendar days to the next desk. +// Rejected/stale requests leave state and both random generators untouched. +TurnAdvanceResult advance_to_next_desk(TurnDriver& driver, ModernState& g, + const TurnAdvanceRequest& request, + GameRandom& game, WatcomRandom& rand, + MinuteReport& report); + +} // namespace bmh::modern diff --git a/src/modern/game/week.cpp b/src/modern/game/week.cpp new file mode 100644 index 0000000..d331f59 --- /dev/null +++ b/src/modern/game/week.cpp @@ -0,0 +1,395 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/week.hpp" + +#include "modern/game/matchday.hpp" +#include "game/lineup.hpp" +#include "game/schedule.hpp" + +#include + +namespace bmh::modern { + +namespace { + +constexpr size_t kManagerRecord = 0xB0C; + +int32_t rd32(const std::vector& v, size_t o) { + return int32_t(uint32_t(v.at(o)) | uint32_t(v.at(o + 1)) << 8 | uint32_t(v.at(o + 2)) << 16 | uint32_t(v.at(o + 3)) << 24); +} +void wr32(std::vector& v, size_t o, int32_t x) { + for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(uint32_t(x) >> (8 * i)); +} + +} // namespace + +void daily_interest(ModernState& g, WatcomRandom& rand) { + // (DailyInterest before the day step: the training camp visits of today are over) + for (size_t m = 0; m < g.manager_teams.size(); m++) g.manager_records.at(m * kManagerRecord + 0x21f) &= 0x7f; + for (int k = 0; k < 4; k++) { + const size_t rec = size_t(k) * kManagerRecord; + const int32_t balance = rd32(g.manager_records, rec + 0x314); + const int32_t deposit = rd32(g.manager_records, rec + 0x318); + const int32_t credit = rd32(g.manager_records, rec + 0x31c); + int32_t amount = 0; // positive = cost + if (balance < 0) { + if (balance + credit < 0) amount = ((balance + credit) * 18) / -36500; + int32_t used = -credit < balance ? balance : -credit; + amount += (used * 12) / -36500; + wr32(g.manager_records, rec + 0x89c, rd32(g.manager_records, rec + 0x89c) + amount); + modern::book_money(g, k, amount, true); + amount = 0; + } else { + amount = balance / -36500; + } + amount += ((deposit / 10000) * 20000) / -36500; + wr32(g.manager_records, rec + 0x870, rd32(g.manager_records, rec + 0x870) - amount); + modern::book_money(g, k, amount, true); + if (rd32(g.manager_records, rec + 0x314) > 100000000) { // read again after the bookings + int32_t extra = int32_t(rand.range(10000, 20000)) * 1000; + // BookMoney2 with the statistics flag set: counts as an expense (+0x8a0) + wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + extra); + modern::book_money(g, k, extra, true); + } + } +} + +} // namespace bmh::modern + +namespace bmh::modern { + +namespace { + +uint16_t rd16w(const std::vector& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); } +void wr16w(std::vector& v, size_t o, uint16_t x) { + v.at(o) = uint8_t(x); + v.at(o + 1) = uint8_t(x >> 8); +} +int8_t clamp8(int v, int lo, int hi) { // Int8T on a signed char + int8_t c = int8_t(v); + int s = c < lo ? lo : c; + if (s > hi) s = hi; + return int8_t(s); +} + +// Training areas (WeekRuntimeField shift, WeekRuntimeField2 mask): 0 condition, 1 technique (w35c), +// 2-8 the seven skills (w368, 2 bits each). +constexpr uint8_t kAreaShift[9] = {14, 7, 12, 10, 8, 6, 4, 2, 0}; +constexpr uint8_t kAreaMask[9] = {127, 127, 3, 3, 3, 3, 3, 3, 3}; +constexpr uint8_t kIntensityValue[4] = {0, 80, 100, 120}; // WeekRuntimeField3 +constexpr int8_t kFamiliarityStep[4] = {0, -4, 0, 4}; // WeekRuntimeField4 + +// Attribute: read (write = false) or change an attribute by `delta` within 0..max. +int attribute(Player& p, int area, bool write, int delta, int max) { + uint32_t& word = area < 2 ? p.w35c : p.w368; + const int shift = kAreaShift[area], mask = kAreaMask[area]; + int v = int(int32_t(word) >> shift) & mask; + if (!write) return v; + int8_t n = clamp8(int8_t(delta + v), 0, max); + word = (word & ~(uint32_t(mask) << shift)) | uint32_t(int32_t(n)) << shift; + return 0; +} + +} // namespace + +int weekday_code(uint32_t date) { + int c = int(date % 7) + 2; + if (c > 6) c = int(date % 7) - 5; + return c; +} + +void familiarity_decay(ModernState& g, GameRandom& game, WatcomRandom& rand) { + for (size_t k = 0; k < g.manager_teams.size(); k++) { + const int team = g.manager_teams[k]; + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const int player = g.squad_slots.at(s) & 0x0FFF; + if (player == 0xFFF) continue; + const Player& p = g.players.at(player); + uint8_t& used = g.tactics.at(k * 0x840 + (s - range.first) * 0x58 + 0xf); + int r = rand.range(0, 2); + uint8_t rate = uint8_t(r + 4); + if (p.condition() < p.technique()) rate = uint8_t(r + 6); + if (unsigned(rand.range(12, 16)) < ((p.w364 >> 21) & 0x1F)) rate = uint8_t(rate + 2); + int16_t cap = int16_t(8 - int16_t(rd16w(g.manager_records, k * 0xB0C + 0x8b0)) / 0x113); + if (team == no_team()) cap = 8; + if (cap < int16_t(rate)) rate = uint8_t(cap); + // the player pool of a manager without a club: a low value is drawn afresh + // (game generator) + if (team == no_team() && used < 0x1e) used = uint8_t(game.range(0x18, 0x30)); + used = uint8_t(used - used / rate); + } + } +} + +void train_squad(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand) { + const size_t rec = size_t(manager) * 0xB0C; + uint8_t table[4][9]; + for (int pos = 0; pos < 4; pos++) + for (int a = 0; a < 9; a++) + table[pos][a] = uint8_t(kIntensityValue[int8_t(g.manager_records.at(rec + 0xc5 + pos))] + + kIntensityValue[int8_t(g.manager_records.at(rec + 0xc9 + a))]); + const int team = int16_t(rd16w(g.manager_records, rec + 0x290)); + const SquadRange range = squad_range(team); + const int league = team_league(team); + const int16_t quality = int16_t(rd16w(g.manager_records, rec + 0x8ac)); + uint8_t max_value[9] = {99, 99, 3, 3, 3, 3, 3, 3, 3}; // WeekRuntimeField5 + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t entry = g.squad_slots.at(s); + if (entry == 0x0FFF) continue; + const int player = entry & 0x0FFF; + Player& p = g.players.at(player); + const size_t board = size_t(manager) * 0x840 + (s - range.first) * 0x58; + const uint32_t w364 = p.w364; + const int games = int32_t(w364) >> 26; + const int pos = int(w364 & 3); + int8_t used_delta = 0; // local_48 + int8_t trend = 0; // local_54 + const uint8_t used = g.tactics.at(board + 0xf); + const int intensity = g.tactics.at(board + 0xa) & 3; + int second = 10; // local_4c + int focus = (g.tactics.at(board + 0xa) >> 2) + 1; // local_58 + if (attribute(p, focus < 9 ? focus : 8, false, 0, 0) < 3) { + do { + second = game.range(2, 8); + } while (second == focus); + } else { + focus = 10; + } + for (int a = 0; a < 9; a++) { + // register EDI of the original: a value from an earlier branch may survive + uint32_t edi = uint32_t(pos * 9 + a); + int ebx = table[pos][a] + quality / 110 - 5; + if (rand.range(0, 4) == 0) used_delta = int8_t(used_delta + int8_t(g.manager_records.at(rec + 0xc5 + a)) * 2 - 4); + ebx = (int(uint16_t(ebx)) + kIntensityValue[intensity]) / 3; + uint8_t rest = uint8_t(0xa0 - used); + if (rest > 100) rest = 100; + ebx = (int(uint16_t(ebx)) + rest) / 2 - 0x50; + if (focus == a) ebx += 8; + if (second == a) ebx -= 8; + int sign; + if (uint16_t(ebx) < 20) { + sign = -1; + ebx = 20 - ebx; + } else { + sign = 1; + ebx -= 20; + } + // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +// FocusAreaGetsAtLeastStrengthBelow (supported rule profile): the focus area gets at least strength 5 below + uint32_t reg = uint16_t(ebx); + if (focus == a) reg |= 0x10000; + if (sign == 1) { + edi = 3; + if (g.league_rounds.at(league) / 3 > games) { + reg = 0; // no match practice yet: no progress + } else { + edi = (w364 >> 21) & 0x1F; // age - 16 + if (rand.range(13, 40) < int(edi)) reg = 0; // older players progress less + } + } + if (a > 1) { + edi = uint32_t(a); + if (table[pos][a] < 0x6e && game.range(0, 50) == 0) max_value[a] = 2; + } + if (game.range(0, 8) == 0) { + // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +// Int9 (supported rule profile) + uint32_t dx = reg & 0xFFFF; + if ((reg & 0x10000) && dx < 5) dx = 5; + edi = dx * 15; + reg &= 0xFFFF; + if (int(edi) > game.range(0, 0x96)) attribute(p, a, true, sign, int8_t(max_value[a])); + } + (void)edi; + if (a > 1) max_value[a] = 3; + if (reg & 0xFFFF) trend = int8_t(trend + sign); + } + used_delta = clamp8(used_delta, -15, 15); + g.tactics.at(board + 0xf) = uint8_t(g.tactics.at(board + 0xf) + kFamiliarityStep[intensity] + used_delta); + trend = int8_t(trend / int8_t(game.range(1, 4))); + trend = clamp8(trend, -1, 1); + g.tactics.at(board + 0xe) = uint8_t((g.tactics.at(board + 0xe) & 0x3F) + uint8_t((trend + 1) << 6)); + g.tactics.at(board + 0xf) = uint8_t(clamp8(int8_t(g.tactics.at(board + 0xf)), 0x18, 99)); + } + // the assistant's training plan (training automatic on) + if (g.manager_options.at(size_t(manager) * 5 + 4) & 1) modern::auto_training(g, manager); +} + +void auto_training(ModernState& g, int manager) { + uint8_t& option = g.manager_options.at(size_t(manager) * 5 + 4); // CareerSessionRuntimeField3 + if (!(option & 0x80)) option = 0x9f; + const uint8_t flags = (option & 1) ? option : 0; // local_14 + const size_t rec = size_t(manager) * 0xB0C; + const int team = int16_t(rd16w(g.manager_records, rec + 0x290)); + uint8_t plan[13]; + for (int i = 0; i < 13; i++) plan[i] = g.manager_records.at(rec + 0xc5 + size_t(i)); + // QuoteNationalFriendlyMatch for keepers, defence, midfield, attack and the whole team (WeekRuntimeField6) + static constexpr uint16_t kPositions[5] = {0x1f, 0x2f, 0x4f, 0x8f, 0xff}; + int value[5]; + for (int i = 0; i < 5; i++) value[i] = team_average(g, team, kPositions[i]).value; + int16_t order[7]; + uint32_t key[7]; + if (flags & 2) { + for (int i = 0; i < 4; i++) { + plan[i] = 2; + order[i] = int16_t(i); + key[i] = uint32_t((value[i] * 100) / value[4]); + } + quicksort_by_key(order, key, 4, true); // Games ascending + for (int i = 0; i < 2; i++) + if (key[i] < 0x62) plan[order[i]] = 3, plan[order[3 - i]] = 1; + } + const int condition = team_average(g, team, 0xf1).value, technique = team_average(g, team, 0xf2).value; + if (flags & 4) { + plan[4] = 2, plan[5] = 2; + if (condition - 1 > technique) plan[4] = 1, plan[5] = 3; + if (technique - 1 > condition) plan[4] = 3, plan[5] = 1; + } + for (int i = 0; i < 7; i++) { + if (flags & 4) plan[6 + i] = 2; + order[i] = int16_t(i); + key[i] = 0x32; + } + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t v = g.squad_slots.at(s); + if (v == kEmptySlot) continue; + const Player& p = g.players.at(v & 0x0FFF); + uint8_t* board = &g.tactics.at(size_t(manager) * 0x840 + (s - range.first) * 0x58); + if (flags & 8) { + uint8_t intensity = 2; + if (board[0xf] < 0x1f) intensity = 3; + if (board[0xf] > 0x3c) intensity = 1; + board[10] = uint8_t((board[10] & 0xfc) | intensity); + } + // the skills 6..0 (w368 bits 12..0, Attribute with WeekRuntimeField/WeekRuntimeField2, index 2..8): + // + 1 for a player at 0 (WeekRuntimeField7), - 1 at 3 (WeekRuntimeField8) + bool at_top[8] = {}; // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +// by index k = 7 - skill (the supported rule profile patch's bit pairs) + for (int i = 0; i < 7; i++) { + const int skill = 6 - i; + const int level = int(p.w368 >> (2 * skill) & 3); + at_top[i + 1] = level == 3; + if (level == 0) key[i]++; + if (level == 3) key[i]--; + } + if (flags & 0x10) { + // Position: the skill to train (+0x0a bits 2-4) is kept unless it is at 3; + // else the first of the position's order (nibbles of Week_AutoTraining_ExecutableField3, Week_AutoTraining_ExecutableField4, Week_AutoTraining_ExecutableField2, + // Week_AutoTraining_ExecutableField, low first, each 2 * k) that is not at 3 yet + static constexpr uint32_t kOrder[4] = {::bmh::layout::Week_AutoTraining_ExecutableField3, ::bmh::layout::Week_AutoTraining_ExecutableField4, ::bmh::layout::Week_AutoTraining_ExecutableField2, ::bmh::layout::Week_AutoTraining_ExecutableField}; + const int current = (board[10] >> 2) & 7; + if (current == 0 || at_top[current]) { + for (uint32_t list = kOrder[p.position()]; (list & 0xf) != 0; list >>= 4) { + const int k = int(list & 0xf) / 2; + if (!at_top[k]) { + board[10] = uint8_t((board[10] & 3) | (k << 2)); + break; + } + } + } + } + } + quicksort_by_key(order, key, 7); // Games descending + if (flags & 4) + for (int i = 0; i < 3; i++) + if (key[i] > 0x34) plan[6 + order[i]] = 3, plan[6 + order[6 - i]] = 1; + for (int i = 0; i < 13; i++) g.manager_records.at(rec + 0xc5 + size_t(i)) = plan[i]; +} + +void stock_market(ModernState& g, GameRandom& game) { + auto u32 = [&](size_t o) { + return uint32_t(g.stocks.at(o) | g.stocks.at(o + 1) << 8 | g.stocks.at(o + 2) << 16 | uint32_t(g.stocks.at(o + 3)) << 24); + }; + auto w32 = [&](size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) g.stocks.at(o + i) = uint8_t(x >> (8 * i)); + }; + for (int k = 0; k < 12; k++) w32(size_t(k) * 0x5c, u32(size_t(k) * 0x5c) + u32(size_t(k) * 0x5c) * 3 / 10000); + for (int k = 0; k < 12; k++) { + const size_t s = size_t(k) * 0x5c; + const uint32_t base = u32(s) / 300; + int v = rd16w(g.stocks, s + 0x4e) / 3 + (g.stocks.at(s + 0x58) - 1); + if (v < 10) v = 10; + uint8_t& trend = g.stocks.at(s + 0x58); + uint8_t& left = g.stocks.at(s + 0x59); + if (left != 0) left--; + if (left == 0) { + trend = uint8_t(game.range(0, 1) * 2); + left = uint8_t(game.range(2, (trend != 0) + 8)); + } + if (game.range(0, 400 - k * 25) == 0) { + int dir = game.range(0, 1); + v += game.range(v / 5, v / 2) * (dir * 2 - 1); + if (game.range(0, 3) != 0) { + int d2 = game.range(0, 1); + w32(s, uint32_t(v * 300 + (d2 * 2 - 1) * 3000)); + } + } + if (game.range(0, 0x16 - k) == 0) { + int dir = game.range(0, 1); + v += game.range(2, 10) * (dir * 2 - 1); + if (game.range(0, 3) == 0) { + int d2 = game.range(0, 1); + int m = game.range(2, 10); + w32(s, uint32_t(int32_t(u32(s)) + (d2 * 2 - 1) * m * 300)); + } + } + if (game.range(0, 0x5a) == 0 && (v + 0x14 < int(base) || int(base) < v - 0x14)) { + int dir = game.range(0, 1); + int m = game.range(2, 10); + v = (dir * 2 - 1) * m + int(base); + } + if (game.range(0, 1) != 0) v += game.range(0, 2) - 1; + if (int(base) < v) { + if (trend == 2) v--; + } else if (game.range(0, 1) != 0) { + if (trend == 2) v--; + } + if (v < int(base)) { + if (trend == 0) v++; + } else if (game.range(0, 1) != 0) { + if (trend == 0) v++; + } + std::copy(g.stocks.begin() + s + 0x16, g.stocks.begin() + s + 0x16 + 0x3a, g.stocks.begin() + s + 0x14); + if (v < 10) { + v = 10; + w32(s, 3000); + } + if (v > 2000) { + v = 1000; + w32(s, 300000); + for (int i = 0; i < 4; i++) wr16w(g.stocks, s + 0x50 + i * 2, uint16_t(rd16w(g.stocks, s + 0x50 + i * 2) << 1)); + } + wr16w(g.stocks, s + 0x4e, uint16_t(v * 3)); + } +} + +} // namespace bmh::modern + +namespace bmh::modern { + +int month_code(uint32_t date) { + // DeskState_DeskDate_RuntimeField: days per month (index 1-12; February 29 in leap years) + uint8_t days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int leap = 3; // sVar4: 4 = the current year is a leap year + while (date > uint32_t((leap == 4 ? 1 : 0) + 0x16c)) { + if (leap == 4) { + leap = 0; + date--; + } + date -= 0x16d; + leap++; + } + days[2] = uint8_t((leap == 4 ? 1 : 0) + 0x1c); + int month = 7; + while (date > days[month]) { + date -= days[month]; + month = month == 12 ? 1 : month + 1; + } + if (date + 1 > days[month]) month = month == 12 ? 1 : month + 1; + return month; +} + +} // namespace bmh::modern diff --git a/src/modern/game/week.hpp b/src/modern/game/week.hpp new file mode 100644 index 0000000..fbef275 --- /dev/null +++ b/src/modern/game/week.hpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/week.hpp" +// OpenBMH deviates from the original: uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum. +// Between the matchdays: the day processing (BMH.exe V2.24 + supported rule profile patch). +// +// "Weiter" (DailyInterest) handles the event of the current day (AdvanceTurn, e.g. a +// matchday) and then advances day by day (DaysIntoSeason = day of the season, CalendarDay = +// day counter) until the calendar (block CompetitionCalendar) has the next event. Every day runs +// DayStepRest: +// - date + 1, DailyInterest2(1): interest on every human manager's account +// - training and weekly processing on the Source weekday boundary +// - month_change and the national coach's temporary club handback +// day_step_rest in turn.cpp owns those steps; DailyInterest3 advances shares. + +#include + +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +// DailyInterest2(1): daily interest for the four manager slots. Balance (record +0x314) +// earns 1 % a year, the fixed deposit (+0x318) 2 %; an overdraft costs 12 % a year, beyond +// the credit line (+0x31c) 18 % (booked to +0x89c). Income goes to +0x870. A balance over +// 100 million triggers a random extra booking (WatcomRandom 10000-20000 thousand). +// Every day step starts with it, so it also does what DailyInterest does right before the day +// step: bit 7 of record +0x21f (a training camp visit booked today, BookTrainingCamp) is +// cleared for every manager. +void daily_interest(ModernState& g, WatcomRandom& rand); + +} // namespace bmh::modern + +namespace bmh::modern { + +// DeskDate2 (weekday part): CareerSession_PairingsRuntimeDraw_ExecutableField6 of a day counter. +int weekday_code(uint32_t date); + +// FamiliarityDecay (training days): the players of human managers slowly forget their places +// on the tactics board (slot byte 0x0f), faster when condition < technique and when older. +void familiarity_decay(ModernState& g, GameRandom& game, WatcomRandom& rand); + +// TrainSquad: training of one human manager's squad (on training days). At the end, with +// the training automatic on (option byte 4 bit 0, CareerSessionRuntimeField3), auto_training. +void train_squad(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand); + +// OpenBMH deviates from the original: uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum. +// Initialize (+ the supported rule profile patch Position / WeekOperation): the assistant's training +// plan. Option byte 4 (CareerSessionRuntimeField3) holds what he decides - without bit 7 it becomes 0x9f +// (everything), without bit 0 nothing. The plan (record +0xc5, 13 bytes, 1 light 2 normal +// 3 hard) starts from the manager's own: +// bit 1, bytes 0-3: the team value (QuoteNationalFriendlyMatch 0x1f/0x2f/0x4f/0x8f) of keepers, +// defence, midfield, attack in percent of the whole team (0xff); the two weakest +// below 98 % train hard, the two strongest then light - sorted ascending, +// bit 2, bytes 4-5: condition (0xf1) against technique (0xf2): the weaker one hard when +// they differ by more than one, +// bit 2, bytes 6-12: the skills 6..0 of w368: 50 + players at 0 - players at 3, sorted +// descending; the three most needed (over 52) hard, their opposite numbers light. +// Per player of the squad on the tactics board: +// bit 3, +0x0a bits 0-1: the intensity after the familiarity +0x0f (below 31 hard, above +// 60 light), +// bit 4, +0x0a bits 2-4: the skill to train (supported rule profile): kept unless it is at 3 already, +// else the first not yet at 3 in the order of the position (keeper 7,6,3,4,5; +// defence 3,6,4,7,5; midfield 4,6,5,7,3; attack 5,6,4,7,3 - index k = skill 7 - k). +void auto_training(ModernState& g, int manager); + +// DailyInterest3: the daily moves of the 12 shares (block StockExchange). +void stock_market(ModernState& g, GameRandom& game); + +} // namespace bmh::modern + +namespace bmh::modern { + +// DeskDate2 (month part): CareerSession_PairingsRuntimeDraw_ExecutableField5 (1-12) of a day counter. Day 0 is in July; the +// year has 365 days, every fourth one 366 (February 29). +int month_code(uint32_t date); + +} // namespace bmh::modern diff --git a/src/modern/game/weekly.cpp b/src/modern/game/weekly.cpp new file mode 100644 index 0000000..2c68f71 --- /dev/null +++ b/src/modern/game/weekly.cpp @@ -0,0 +1,2987 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "modern/game/modern_state.hpp" +#include "modern/game/weekly.hpp" +#include "modern/game/club_player_detail.hpp" +#include "game/pending_offer.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/transfer_bid.hpp" + +#include +#include +#include +#include +#include + +#include "game/lineup.hpp" +#include "game/match.hpp" +#include "game/messages.hpp" +#include "modern/game/month.hpp" +#include "modern/game/prediction.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/matchday_setup.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "modern/game/national.hpp" +#include "modern/game/bank_credit.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kRecord = 0xB0C; // manager record +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 entries of 0x58 bytes, one per pool slot +constexpr uint32_t kListEntry = 0x58; + +// Offers and incidents (Bool): 1 in WeeklyRuntimeField[kind] is only possible while the +// league is not in its last rounds. +constexpr uint8_t kOfferLate[16] = {0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0}; // WeeklyRuntimeField +constexpr int kShareFactor[6] = {15, 18, 21, 24, 27, 30}; // MonthRuntimeField10 +// Facilities (30 entries of 5 bytes at layout field): [0] weight in the club rating, +// [2] / [3] the range of the months a renewed facility lasts (x 4 weeks). +constexpr uint8_t kFacility[152] = { + 0x02, 0x2d, 0x0f, 0x1e, 0x00, 0x03, 0x1e, 0x0f, 0x16, 0x00, 0x03, 0x1c, 0x0f, 0x16, 0x00, 0x07, 0x28, 0x16, 0x1e, + 0x00, 0x06, 0x1e, 0x0d, 0x13, 0x00, 0x02, 0x14, 0x0f, 0x16, 0x00, 0x01, 0x06, 0x07, 0x0c, 0x00, 0x01, 0x06, 0x07, + 0x0c, 0x00, 0x01, 0x06, 0x07, 0x0c, 0x00, 0x01, 0x06, 0x07, 0x0c, 0x00, 0x01, 0x05, 0x07, 0x0c, 0x00, 0x01, 0x05, + 0x07, 0x0c, 0x00, 0x01, 0x05, 0x07, 0x0c, 0x00, 0x01, 0x05, 0x07, 0x0c, 0x00, 0x02, 0x0f, 0x0c, 0x10, 0x00, 0x01, + 0x0c, 0x0c, 0x10, 0x00, 0x02, 0x19, 0x12, 0x16, 0x00, 0x01, 0x14, 0x12, 0x16, 0x00, 0x01, 0x04, 0x03, 0x06, 0x00, + 0x02, 0x07, 0x04, 0x07, 0x00, 0x02, 0x09, 0x04, 0x07, 0x00, 0x03, 0x05, 0x05, 0x07, 0x00, 0x00, 0x1e, 0x1e, 0x32, + 0x00, 0x00, 0x25, 0x1e, 0x32, 0x00, 0x00, 0x1e, 0x1e, 0x32, 0x00, 0x00, 0x19, 0x1e, 0x32, 0x00, 0x00, 0x1e, 0x1e, + 0x32, 0x00, 0x00, 0x25, 0x1e, 0x32, 0x00, 0x00, 0x1e, 0x1e, 0x32, 0x00, 0x00, 0x19, 0x1e, 0x32, 0x00, 0x02, 0x06}; +// Season ticket compensation per league (CareerSession_FormatError_RuntimeField5, int; leagues above 4 read on). +constexpr uint8_t kTicketRefund[36] = {0x14, 0, 0, 0, 0x12, 0, 0, 0, 0x10, 0, 0, 0, 0x10, 0, 0, 0, 0x0f, 0, 0, 0, + 0x02, 0x7d, 0xe0, 0xcd, 0x00, 0x8f, 0x00, 0x11, 0x01, 0xc9, 0x00, 0xf3, + 0x00, 0x6d, 0x00, 0x22}; +// Transfer interest: required strength per league (LeagueStrengthRanges, every second byte) and by +// table position (WeeklyRuntimeField2). +constexpr uint8_t kLeagueLevel[20] = {0x47, 0x5d, 0x31, 0x47, 0x1c, 0x31, 0x1c, 0x31, 0x0a, 0x1c, + 0x55, 0x5f, 0x5a, 0x5f, 0x4b, 0x5f, 0x50, 0x5f, 0x5a, 0x00}; +constexpr uint8_t kPositionLevel[24] = {0x17, 0x16, 0x15, 0x13, 0x12, 0x11, 0x10, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, + 0x09, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x00, 0xe6, 0xee, 0xf3, 0xf9}; +// Players a club wants per position (MonthRuntimeField4 big squads, MonthRuntimeField5 small squads). +constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4}; +// Advertising: European cup bonus by EuropeanClub (SeasonRuntimeField11) and cup winners +// (SeasonRuntimeField12 entries of the cup table, bonus SeasonRuntimeField13, premium SeasonRuntimeField14). +constexpr int8_t kEuropeBonus[4] = {0, 1, 3, 2}; +constexpr uint8_t kWinnerEntry[4] = {0x00, 0x0f, 0x13, 0x15}; +constexpr int8_t kWinnerBonus[4] = {0x14, 0x1e, 0x14, 0x0f}; +constexpr int32_t kWinnerPremium[4] = {500000, 1500000, 2500000, 1500000}; +// Statistics: value of the facilities (BalancePlanRuntimeField5, u16 per facility). +constexpr uint16_t kFacilityValue[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600, + 2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000}; + +struct Record { + std::vector& r; + size_t base; + uint8_t& b(size_t o) { return r.at(base + o); } + int16_t i16(size_t o) const { return int16_t(r.at(base + o) | r.at(base + o + 1) << 8); } + uint16_t u16(size_t o) const { return uint16_t(r.at(base + o) | r.at(base + o + 1) << 8); } + int32_t i32(size_t o) const { return int32_t(uint32_t(u16(o)) | uint32_t(u16(o + 2)) << 16); } + uint32_t u32(size_t o) const { return uint32_t(u16(o)) | uint32_t(u16(o + 2)) << 16; } + void set16(size_t o, uint16_t v) { r.at(base + o) = uint8_t(v), r.at(base + o + 1) = uint8_t(v >> 8); } + void set32(size_t o, uint32_t v) { set16(o, uint16_t(v)), set16(o + 2, uint16_t(v >> 16)); } +}; +Record record(ModernState& g, int manager) { return Record{g.manager_records, size_t(manager) * kRecord}; } + +// The special post-desk adapter retains FindManagerForClub's active-count lookup: +// inactive original records1..3 are AI clubs, while the coach's parked club is +// recognized as native record4. Ordinary/legacy callers keep their old lookup. +int pending_native_manager_of(const ModernState& g, int team, bool native_takeover) { + const int active = g.manager_of(team); + if (active >= 0 || !native_takeover || g.manager_teams.size() != 1 || + g.manager_teams[0] != no_team() || 4*kRecord+0x292 > g.manager_records.size()) + return active; + const size_t base = 4*kRecord+0x290; + const int parked = int(g.manager_records[base]) | (int(g.manager_records[base+1])<<8); + return parked == team ? 4 : -1; +} + +// Validate the opt-in against the actual AdvanceTurn/DispatchClubPlayerPendingOffers coordinates. It +// cannot turn an ordinary/day-step/poach request into a national pending sale. +bool source_pending_owner_valid(const ModernState& g,const SourcePendingOwner& owner,int entry,size_t slot) { + const auto& mem=g.memory; + if(entry<40 || entry>=44 || slot!=transfer_list_slot()+size_t(entry) || slot>=g.squad_slots.size() || + g.manager_teams!=std::vector{no_team()} || g.manager_records.size()<5*kRecord || + g.tactics.size()<5*kBoard || !mem.has(::bmh::layout::CoachActive) || !mem.u8(::bmh::layout::CoachActive) || + !mem.has(::bmh::layout::OriginalManagerCount) || mem.u8(::bmh::layout::OriginalManagerCount)<1 || mem.u8(::bmh::layout::OriginalManagerCount)>4 || + !mem.has(::bmh::layout::ManagerCount) || mem.u8(::bmh::layout::ManagerCount)!=1 || !mem.has(::bmh::layout::PendingOffer_PendingOfferOwnerTeam_RuntimeField) || + !mem.has(::bmh::layout::DeskPosition) || mem.u8(::bmh::layout::DeskPosition)!=0 || !mem.has(::bmh::layout::ActiveManager) || + owner.manager<0 || owner.manager>=mem.u8(::bmh::layout::OriginalManagerCount) || + mem.u16(::bmh::layout::NextDeskManager)!=owner.manager || mem.u8(::bmh::layout::ActiveManager)!=owner.manager || + !mem.has(::bmh::layout::OfferSlots+uint32_t(entry-40)*4+3))return false; + const auto team=[&](int manager){const size_t at=size_t(manager)*kRecord+0x290; + return int(g.manager_records[at]) | int(g.manager_records[at+1])<<8;}; + if(team(0)!=no_team() || team(4)<0 || team(4)>=league_clubs() || + team(owner.manager)!=owner.team || + (owner.manager==0 ? owner.team!=no_team() : owner.team<0 || owner.team>=league_clubs()))return false; + const uint32_t list=kTransferList+uint32_t(entry)*kListEntry; + if(!mem.has(list+kListEntry-1) || mem.u16(list+2)!=0xffff || + mem.u16(list+4)!=0xffff || mem.u16(list+6)!=0xffff)return false; + const uint32_t word=mem.u32(::bmh::layout::OfferSlots+uint32_t(entry-40)*4); + return word!=0xffffffffu && int(word&31)==owner.manager && + int((word>>10)&0x0fff)==int(g.squad_slots[slot]&0x0fff); +} + +int league_of(int team) { return team > 0x164 ? 0 : team_league(team); } // TeamLeague2 + +} // namespace + +// Nationality: nationality of a player (w368 bits 27-31, +32 for the flag in *PlayerBonuses). +int nationality(const ModernState& g, int player) { + player &= 0xFFF; + return int(g.players.at(size_t(player)).w368 >> 27) + ((g.player_bonus.at(size_t(player)) & 0x80) >> 2); +} + +// SquadCount(team, flags): players of a club (bit 1: the injured too) plus, with bit 0, +// the players it has bought for later (table Career_RemoveJoinLoans_RuntimeField, 200 entries). +int squad_count(const ModernState& g, int team, int flags) { + const SquadRange range = squad_range(team); + int n = 0; + for (size_t i = 0; i < range.count; i++) { + const int p = g.squad_slots.at(range.first + i) & 0xFFF; + if (p != 0xFFF && ((flags & 2) || ((g.players.at(size_t(p)).w364 >> 16) & 0x1F) == 0)) n++; + } + if (flags & 1) + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && ((e >> 12) & 0x3FF) == uint32_t(team & 0xFFFF)) n++; + } + return n & 0xFF; +} + +// SlotTeam: club of an absolute squad slot (-1 for the pool). +int slot_team(int slot) { + if (slot < german_clubs() * 24) return slot / 24; + if (slot < int(transfer_list_slot())) return (slot - german_clubs() * 24) / 16 + german_clubs(); + return -1; +} + +// Add32 / FacilityRating2: the club's rating of its facilities. +int facility_rating(ModernState& g, int manager, int* second, WatcomRandom* rand) { + Record rec = record(g, manager); + int sum = 0x14, first = 0, closed = 0; + *second = 0; + if (g.memory.u8(::bmh::layout::GameMode) == 1) { + int league = rec.b(0x210); + if (league > 2) league--; + return 0x50 - league * 0x14; + } + for (int i = 0; i < 0x16; i++) { + const uint8_t v = rec.b(size_t(i)); + if (v == 0) continue; + int level; + if (i < 0xe || i == 0x10 || i == 0x11) level = i == 0 ? (v - 1) / 0x55 + 1 : 1; + else level = rec.b(size_t(i) + 0x2e) & 7; + sum += (level & 0xFF) * kFacility[i * 5]; + } + for (int i = 0; i < 8; i++) { + if (rec.b(0x34 + size_t(i)) != 0) { + // a stand under construction costs 10-12 % (only drawn for the attendance) + if (rand) closed += rand->range(10, 12); + continue; + } + if (rec.b(0x44 + size_t(i)) & 1) first += rec.b(0x4c + size_t(i)); + if (rec.b(0x44 + size_t(i)) & 2) *second += rec.b(0x4c + size_t(i)); + } + const int seats = rec.b(0x5c); + if (seats == 0) { + *second = 0; + first = 0; + } else { + first = first * 100 / seats; + *second = *second * 100 / seats; + } + return (((100 - closed) * sum / 100 + first / 4 + (*second >> 4)) * 0x5a) / 0x72 + 0x18; +} + +void manager_offers(ModernState& g, int manager, WatcomRandom& rand, MinuteReport& report) { + if (g.memory.u32(::bmh::layout::CompetitionSelection) == 2) return; + Record rec = record(g, manager); + const bool events_off = false; // OpenBMH deviates from the original: uses the supported weekly-event configuration, with its rule switch disabled. +// WeeklyEventsDisabled (0 in the supported rule profile) + const uint8_t weeks = g.memory.u8(::bmh::layout::CareerDuration); + for (int kind = 0; kind < 16; kind++) { + if ((kind == 11 || kind == 12) && weeks == 1) continue; + if (kind == 7) continue; + if (kind == 9) { + if (rand.range(0, 1) != 0 && !events_off) continue; + if (g.memory.u32(::bmh::layout::Loans + uint32_t(manager) * 0x78) == 0) continue; + } + if ((kind == 13 || kind == 15) && rand.range(0, 1) != 0 && !events_off) continue; + int sum = 0; // ESI (kind 14: dividends) + if (kind == 14) { + for (int k = 0; k < 6; k++) { + const uint32_t held = g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + uint32_t(k) * 0x1c); + const uint32_t value = uint32_t(g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c) * uint32_t(kShareFactor[k])) / 10000; + sum += int(uint32_t(rand.range(10, 20)) * (held * value)); + } + if (sum == 0) continue; + } + if (kind <= 7 && rec.b(0x170 + size_t(kind)) != 0) continue; + if (!events_off && rand.range(0, (0x39 - g.level) * 0xd - kOfferLate[kind] * 0x16c) != 0) continue; + if (kOfferLate[kind] != 0 && g.league_rounds.at(rec.b(0x210)) >= 0x14) continue; + int league = rec.b(0x210); + if (league > 2) league--; + uint8_t value = 0; // local_18 + // the message: the offer's text (pointer table Weekly_ManagerOffers_TextPointer6) plus details + std::string msg = kind < 15 ? message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer6 + uint32_t(kind) * 4) : std::string(); + switch (kind) { + case 0: { + // the main sponsor pays a part of a transfer: text + position + amount limits + const int text = rand.range(0, 3); + msg += message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer) + message_text(g, ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer2 + uint32_t(text) * 4) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer2); + const int a = rand.range(1, 7), b = rand.range(1, 7); + value = uint8_t(text + uint8_t(a << 2) + uint8_t(b << 5)); + break; + } + case 1: + case 2: { + const int a = rand.range(1, 7), b = rand.range(1, 7); + value = uint8_t(uint8_t(a << 2) + uint8_t(b << 5)); + break; + } + case 3: + value = uint8_t(rand.range(10, 20)); + msg += format_number(g, value * (4 - league) * 1000, 0x101) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer3); + break; + case 4: + value = uint8_t(rand.range(4, 20)); + msg += format_number(g, value * 1000, 0x101) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer4); + break; + case 5: { + const int seats = rec.b(0x5c) * 1000; + const int r = rand.range(0x46, 100); + sum = ((0x14 - league * 2) * (seats * r / 100)) / 10000 * 10000; + value = uint8_t(sum / 10000); + break; + } + case 6: + sum = (4 - league) * 50000; + value = uint8_t(rand.range(5, 10)); + msg += format_number(g, sum, 0x101) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer) + format_number(g, value, 1) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer5); + break; + case 8: + value = uint8_t(rand.range(5, (4 - league) * 5 + 10)); + rec.b(0x170 + 8) = value; + break; + case 9: + value = uint8_t(rand.range(1, 3) * 10); + if (!modern::change_bank_credit_interest(g, manager, value)) { + report.fail("weekly offer: unavailable credit factors (ChangeBankCreditInterest)"); + return; + } + break; + default: break; + } + if (kind < 10 && kind != 5 && kind != 8) { + rec.b(0x170 + size_t(kind)) = value; + post_composed(g, manager, msg); // PostMessage + continue; + } + // The other offers ask the manager (PresentManagerDialog with JA/NEIN, a message box only). + // GameState::offer_answer decides (the replays decline unless told otherwise). + if (!g.offer_answer) { + if (kind == 14) { + // declined dividends: with 1 in 2 the payment comes anyway, twice (WeeklyRuntimeField3), + // else WeeklyRuntimeField4 - both message boxes only + if (rand.range(0, 1) == 0) modern::book_money(g, manager, sum * 2, true); + } + continue; + } + switch (kind) { + case 5: rec.b(0x170 + 5) = value; break; + case 8: + rec.b(0x170 + 8) = 0; + modern::book_money(g, manager, int32_t(value) * 10000, true); + break; + case 10: + // insurance for every tactics board slot without one (slot byte 0x43) + for (size_t s = 0; s < 0x18; s++) { + uint8_t& cover = g.tactics.at(size_t(manager) * 0x840 + s * 0x58 + 0x43); + if (cover == 0) cover = 0x4c; + } + break; + case 11: + // the advertising contracts (record +0xa34, 18 of 12 bytes: amount, +5 months + // left) are extended by a year, up to 36 months + for (size_t c = 0; c < 0x12; c++) { + const size_t at = 0xa34 + c * 0xc; + if (rec.i32(at) != 0 && int8_t(rec.b(at + 5)) < 0x24) rec.b(at + 5) = uint8_t(rec.b(at + 5) + 0xc); + } + break; + case 12: + // the advertising contracts are renegotiated: W(50, 150) % each + for (size_t c = 0; c < 0x12; c++) { + const size_t at = 0xa34 + c * 0xc; + if (rec.i32(at) != 0) rec.set32(at, uint32_t(rec.i32(at) * rand.range(0x32, 0x96) / 100)); + } + break; + case 13: modern::book_money(g, manager, 4, true); break; // (4 EU, as in the original) + case 14: modern::book_money(g, manager, sum, true); break; + default: break; + } + } +} + +void season_ticket_compensation_source(ModernState& g, int manager, + const SeasonTicketCompensationNoticeHook& notice) { + Record rec = record(g, manager); + rec.b(0x5c) = 0; + for (int i = 0; i < 8; i++) + if (rec.b(0x34 + size_t(i)) == 0) rec.b(0x5c) = uint8_t(rec.b(0x5c) + rec.b(0x4c + size_t(i))); + int missing = int(rec.u16(0x2ac)) - rec.b(0x5c) * 1000; + if (missing <= 0) return; + const int league = league_of(int16_t(rec.u16(0x290))); + int weeks = 0x11 - g.league_rounds.at(size_t(league)); + if (weeks > 0xf) weeks = 0xf; + const int32_t per = int32_t(kTicketRefund[league * 4] | kTicketRefund[league * 4 + 1] << 8 | + kTicketRefund[league * 4 + 2] << 16 | uint32_t(kTicketRefund[league * 4 + 3]) << 24); + // Source uses 32-bit IMULs, then passes the signed dword to BookMoney2. + // Unsigned intermediates make the wrap explicit without C++ signed UB. + const uint32_t week_rate = uint32_t(weeks) * uint32_t(per); + const int32_t amount = std::bit_cast(uint32_t(missing) * week_rate); + if (notice) notice(g, {manager, missing, int(rec.b(0x5c)) * 1000, weeks, amount}); + modern::book_money(g, manager, amount, true, true); + rec.set16(0x2ac, uint16_t(rec.b(0x5c) * 1000)); +} + +void season_ticket_compensation(ModernState& g, int manager) { + modern::season_ticket_compensation_source(g, manager); +} + +void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + (void)report; + Record rec = record(g, manager); + uint8_t& weeks = g.memory.at(::bmh::layout::Savestate_Layout_ExecutableField); + if (manager == 0) weeks++; + if (weeks == 0xc) weeks = 0; + if (weeks % (rand.range(0, 1) + 3) == 0) g.memory.set32(::bmh::layout::CareerSession_Invalid_RuntimeField2, uint32_t(game.seed())); // the game generator seed is saved + // "Ihr Sparkurs laesst Ihr Stadion langsam verfallen ... BETROFFEN: " for a + // facility that decays (local_c is set once per call and never cleared: after the first + // message every further decay of the call is reported, even one that would not be) + bool message = false; + for (int i = 0; i < 0x1e; i++) { + if (weeks == 0 && rec.b(size_t(i)) != 0 && rec.b(0x1e + size_t(i)) == 0) { + uint8_t& v = rec.b(size_t(i)); + v--; + if ((i == 0 && v % 0x55 == 0) || rec.b(0x1e + size_t(i)) + v == 0) { + if (i < 0xe) { + message = true; + } else if (i < 0x16) { + uint8_t& n = rec.b(0x2e + size_t(i)); + if (n > 1) { + message = true; + if (--n != 0) v = uint8_t(kFacility[i * 5 + 2] << 2); + } + } else { + const size_t k = 0x4c + size_t(i - 0x16); + if (rec.b(0x5c) != 0 && rec.b(k) != 0) { + message = true; + rec.b(k) = uint8_t(rec.b(k) / 3); + if (rec.b(k) != 0) v = uint8_t(kFacility[i * 5 + 2] << 2); + } + } + if (message) post_composed(g, manager, message_text(g, ::bmh::layout::Weekly_FacilityAgeing_TextPointer) + message_text(g, ::bmh::layout::Stadium_RenderPanorama_TextPointer + uint32_t(i) * 4)); + } + } + uint8_t& build = rec.b(0x1e + size_t(i)); + if (build != 0 && --build == 0) { + uint8_t& v = rec.b(size_t(i)); + if (i == 0) v = uint8_t((v == 0 ? 1 : (v - 1) / 0x55 + 2) * 0x55); + else v = uint8_t(rand.range(kFacility[i * 5 + 2], kFacility[i * 5 + 3]) << 2); + if (i > 0xd) { + rec.b(0x2e + size_t(i)) = uint8_t((rec.b(0x2e + size_t(i)) >> 4) & 7); + if (i > 0x15) { + rec.b(0x36 + size_t(i)) = rec.b(0x3e + size_t(i)); + rec.b(0x3e + size_t(i)) = 0; + } + } + } + } + modern::season_ticket_compensation(g, manager); +} + +void facility_damage(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand) { + Record rec = record(g, manager); + bool forced = false; // BH: an announced damage (record +0x178) + const int level = g.level; + if (rec.b(0x178) != 0 && rand.range(0, 0x34) == 0) forced = true; + if (!forced) { + if (!(level > rand.range(0, 0xaf))) return modern::season_ticket_compensation(g, manager); + const int league = rec.b(0x210); + if (!(rand.range(1, 3) > league)) return modern::season_ticket_compensation(g, manager); + } + // The message is composed from pointer tables of TEXTD.BLK: articles Weekly_FacilityDamage_TextPointer2 (the + // index tables WeeklyRuntimeField5/WeeklyRuntimeField6/WeeklyRuntimeField7 pick the right one), facility names Stadium_RenderPanorama_TextPointer, + // causes Weekly_FacilityDamage_TextPointer (0-4 at random, 5 for an announced damage). + static constexpr uint8_t kCauseArticle[6] = {0, 1, 7, 3, 1, 0}; // WeeklyRuntimeField5 + static constexpr uint8_t kCauseArticleBy[6] = {6, 2, 8, 3, 9, 6}; // WeeklyRuntimeField6 + static constexpr uint8_t kFacilityArticle[0x1e] = {0, 5, 4, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 5, // WeeklyRuntimeField7 + 5, 5, 5, 4, 4, 4, 5, 5, 5, 5, 4, 5, 5, 5, 4}; + auto article = [&](int k) { return message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer2 + uint32_t(k) * 4); }; + auto facility = [&](int k) { return message_text(g, ::bmh::layout::Stadium_RenderPanorama_TextPointer + uint32_t(k) * 4); }; + auto cause = [&](int k) { return message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer + uint32_t(k) * 4); }; + std::string text; + int which = game.range(0, 0x1d); + if (forced) which = game.range(1, 0x1d); + if (which == 0) { + for (int k = 0; k < 6; k++) { + const int i = rand.range(8, 0xf); + if (rec.b(0x3c + size_t(i)) & 2) { + rec.b(0x3c + size_t(i)) &= 0xFD; + post_composed(g, manager, message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer4) + message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer3 + uint32_t(i) * 4) + message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer5)); + break; + } + } + return modern::season_ticket_compensation(g, manager); + } + const size_t i = size_t(which); + if (rec.b(i) == 0 || rec.b(0x1e + i) != 0) return modern::season_ticket_compensation(g, manager); + int half = rand.range(0, (which < 0xe) + 1); + if (rec.b(i) < 2) half = 0; + if (forced) rec.b(0x178) = 0; + if (half == 0) { + rec.b(i) = 0; + if (which < 0xe) { + const int c = forced ? 5 : rand.range(0, 4); + text = article(kFacilityArticle[i]) + facility(which) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer) + article(kCauseArticle[c]) + cause(c) + + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer2); + } else if (which < 0x16) { + uint8_t& lvl = rec.b(0x2e + i); + if (lvl > 1 || (lvl == 2 && (which == 0x10 || which == 0x11))) { + if (rand.range(0, 2) == 0) lvl = 1; + else lvl--; + text = article(kFacilityArticle[i]) + facility(which) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer3); + } + } else if (rec.b(0x5c) != 0 && int(rec.b(0x42)) < rand.range(1, 3)) { + int k; + do { + k = rand.range(0, 7); + } while (rec.b(0x4c + size_t(k)) == 0); + text = message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer4) + facility(k + 0x16) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer5); + rec.b(0x4c + size_t(k)) = 0; + } + } else { + rec.b(i) = uint8_t(rec.b(i) >> 1); + const int c = forced ? 5 : rand.range(0, 4); + text = article(kFacilityArticle[i]) + facility(which) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer6) + article(kCauseArticleBy[c]) + cause(c) + + message_text(g, which > 0x11 && which < 0x16 ? ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer7 : ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer8); + } + if (!text.empty()) post_composed(g, manager, text); // PostMessage + modern::season_ticket_compensation(g, manager); +} + +// ClubAttraction(team, 0): the attraction of a club for advertisers (0-100). +int club_attraction(const ModernState& g, int team) { + // EuropeanClub: which European cup the club still plays in + int europe = 0; + const struct { uint32_t list, count; } cups[3] = {{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_EuropeanClub_ExecutableField}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_EuropeanClub_ExecutableField2}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, ::bmh::layout::Career_EuropeanClub_ExecutableField3}}; + for (int c = 0; c < 3 && europe == 0; c++) + for (int k = 0; k < int(int8_t(g.memory.u8(cups[c].count))); k++) + if (g.memory.u16(cups[c].list + uint32_t(k) * 2) == uint16_t(team)) { + europe = c + 1; + break; + } + int8_t bonus = int8_t(kEuropeBonus[europe] * 10 + 10); + if (team == int(g.memory.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6))) bonus = int8_t(bonus + 10); + for (int k = 0; k < 4; k++) + if (g.memory.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField + uint32_t(kWinnerEntry[k]) * 0x28) == uint16_t(team)) bonus = int8_t(bonus + kWinnerBonus[k]); + const int strength = uint16_t(team_average(g, team, 0xff).value); + int position = int8_t(modern::table_position(g, team)); + if (position == -1) position = 10; + int league = int8_t(league_of(team)); + if (league > 2) league--; + const int place = uint16_t((4 - league) * 0x16 + (0x14 - position)); + int v = int16_t(place * 40 / 108 + strength * 2 / 10 + bonus * 4 / 5); + return std::clamp(v, 0, 100); +} + +void advertising_offers(ModernState& g, int manager, WatcomRandom& rand, MinuteReport& report) { + (void)report; + if (g.memory.u8(::bmh::layout::CareerDuration) == 1) return; + Record rec = record(g, manager); + if (manager == 0) { + // "Es gibt neue Werbeangebote!" to every manager with a free advertising slot + uint32_t mask = 0x80000000u; + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (int k = 0; k < 0x10; k++) + if (g.manager_records.at(m * kRecord + 0xa39 + size_t(k) * 0xc) == 0) mask |= 1u << m; + if (mask != 0x80000000u) post_text(g, int64_t(mask), text_id(::bmh::layout::Weekly_AdvertisingOffers_TextPointer)); + } + int score = int16_t(int8_t(modern::club_attraction(g, int16_t(rec.u16(0x290))))); + if (g.memory.u8(::bmh::layout::GameMode) == 3 && g.league_rounds.at(size_t(league_of(int16_t(rec.u16(0x290))))) > 0x11) { + int t = rec.i32(0x320) / 100000; + t = std::clamp(t, -10, 10); + score = std::clamp(int(int16_t(score + t)), 0, 100); + } + const int fans = rec.i16(0x8b4) * 100 / 0x226 - 100; + score = int16_t(score) + fans / 5; + if (int16_t(score) < 0) score = 0; + score = int16_t(score) * 100 / 0x78; + int base = (int16_t(score) * 60000 + 1000000) / 0xc; + base = ((0xb4 - g.level * 5) * base) / 100; + for (int kind = 0; kind < 3; kind++) + for (int k = 0; k < 10; k++) { + const size_t o = 0x8cc + size_t(kind) * 0x78 + size_t(k) * 0xc; + rec.b(o + 7) = uint8_t(k); + const int r = rand.range(0, (k * 2) / 3 + 5 - rec.i16(0x8b4) / 0x14); + if (int16_t(r) != 0) continue; + if ((k >= 5 && kind == 2) || rand.range(0, 0xb) <= k) { + rec.set32(o, 0); + continue; + } + int part, percent = 0; + if (kind == 0) { + part = (base / 2) / 8; + percent = k * 6 + 0x46; + } else { + part = base >> 2; + percent = kind == 1 ? k * 4 + 0x50 : k * 4 + 0x5a; + } + const int v = percent * part / 100; + rec.set32(o, uint32_t(rand.range(v - (v >> 2), v + (v >> 2)))); + if (kind == 0 && rand.range(0, 5) == 0) rec.b(o + 4) = uint8_t(rand.range(2, 3)); + else rec.b(o + 4) = 1; + rec.b(o + 5) = uint8_t(rand.range(1, 2)); + if (rand.range(0, 5) != 0) rec.b(o + 6) = 0; + else rec.b(o + 6) = uint8_t(rand.range(1, 3 - int8_t(rec.b(o + 5))) * 0xc); + rec.b(o + 5) = uint8_t(rec.b(o + 5) * 0xc); + rec.set16(o + 8, uint16_t(score)); + } +} + +void transfer_bid(ModernState& g, int slot, uint32_t list, bool high, int months, GameRandom& game, WatcomRandom& rand, + MinuteReport& report) { + StaticMemory& mem = g.memory; + const int own = modern::slot_team(slot); + int free_bid = 0; // local_14 + if (list != 0) { + while (free_bid < 4 && int16_t(mem.u16(list + uint32_t(free_bid) * 2)) != -1) free_bid++; + if (free_bid == 4) return; + } + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const int nat = modern::nationality(g, player) & 0xFF; + const uint32_t w35c = g.players.at(size_t(player)).w35c; + const int position = g.players.at(size_t(player)).w364 & 3; + const int half = int(((w35c >> 14) & 0x7F) + ((w35c >> 7) & 0x7F)) >> 1; // local_5c + bool first_pass = true; // local_34 + uint8_t foreign_skip = 0; // local_1c + int bonus_need = 0; // local_4c: the value of the last club rated (not of the chosen one) + for (;;) { + std::vector teams; + std::vector keys; + std::vector needs; + int region = 0; // local_20 (not reset between the clubs) + for (int team = 0; team < league_clubs(); team++) { + if (team == own || g.manager_of(team) >= 0) continue; + if (team >= german_clubs()) region = team_region(team) & 0xFF; + if (own >= 0 && g.manager_of(own) >= 0 && list != 0 && (w35c >> 27) != 0 && game.range(0, 0xf) != 0) continue; + if (first_pass && nat < 5 && nat != region && foreign_skip++ % 10 == 0) continue; + const int players = modern::squad_count(g, team, 3); + if (region == 0 && players > 0x15) continue; + if (region != 0 && players > 0xf) continue; + int avg[4]; + int count[4]; + for (int p = 0; p < 4; p++) { + const TeamAverage a = team_average(g, team, uint16_t((1 << (p + 4)) + 3)); + avg[p] = int16_t(a.value); + count[p] = a.players; + } + int score = (region == nat || nat > 4) ? 0x46 : 0; + int16_t strength = 0; + for (int p = 0; p < 4; p++) strength = int16_t(strength + avg[p]); + strength = int16_t(strength >> 2); + const int league = league_of(team); + int need = 0; // local_4c + if (g.league_rounds.at(size_t(league)) > 10) { + const int pos = int8_t(modern::table_position(g, team)); + const int16_t wanted = int16_t(kLeagueLevel[league * 2] + kPositionLevel[pos]); + if (strength < wanted && strength < int16_t(half)) need = wanted - strength; + } + const int diff = std::abs(half - strength); // Abs2 + const int r = rand.range(int16_t(need) + 3, int16_t(need) + 0xd); + if (int16_t(diff) < r) score += int(int16_t(need + 0xe - diff)) * 16 + 100; + else score -= int16_t(diff) * 8; + const int8_t* wanted = team < german_clubs() ? kWantedBig : kWantedSmall; + int16_t d = int16_t(wanted[position] - int8_t(count[position])); + if (d < 0) { + score += int(d) << 8; + } else { + d = int16_t(d + 1); + if (position == 0 && int8_t(count[0]) < 2) d = int16_t(d + (2 - int8_t(count[0])) * 4); + score += int(d) << 6; + if (score > 1) { + if (strength > rand.range(0x5a, 0x62) && int16_t(diff) < rand.range(0, 0x14)) score += rand.range(10, 0x28); + score += ((g.team_flags.at(size_t(team)) >> 14) & 3) << 4; + } + } + int16_t limit = int16_t((region == 0 ? 3 : 0) + 0xe); + int cnt = players; + if (int16_t(cnt) < limit) { + // (a bug of the original: it counts the club among the bidders of entry 40) + int8_t twice = 0; + for (int b = 0; b < 4; b++) + if (mem.u16(kTransferList + 40 * kListEntry + uint32_t(b) * 2) == uint16_t(team)) twice++; + cnt = uint8_t(cnt + twice / 2); + limit = int16_t(limit - cnt); + if (limit > 0 && int16_t(diff) < limit * 5 + 10) score += int(limit) << 7; + } + keys.push_back(uint32_t(score + 100000)); + teams.push_back(int16_t(team)); + needs.push_back(need); + bonus_need = need; + } + int chosen = -1, index = -1; + const int n = int(teams.size()); + if (n != 0) { + // Games sorts both lists; the need of the chosen club is kept separately + std::vector order(static_cast(n)); + for (int i = 0; i < n; i++) order[size_t(i)] = int16_t(i); + std::vector sorted = keys; + quicksort_by_key(order.data(), sorted.data(), n); + for (index = 0; index < n; index++) { + const int team = teams[size_t(order[size_t(index)])]; + int slots = int(squad_range(team).count); + if (list != 0) + for (int b = 0; b < 4; b++) + if (mem.u16(list + uint32_t(b) * 2) == uint16_t(team)) { + slots = 0; + break; + } + const bool reject = g.manager_of(team) >= 0 || (list != 0 && team == (mem.u16(list + 8) & 0x7FFF)) || slots == 0; + if (!reject) { + chosen = team; + break; + } + } + // The key of the chosen club is read with the club id as index (a bug: MOV EAX, + // [ESP + club * 4] at 00017ecd, the key array holds 138 entries). Beyond the + // candidates of this call the slot keeps whatever an earlier call left on the stack; + // it only matters through clamp(key / 0x50, 0, 4) below, and any bid key of an + // earlier call (score + 100000) gives the top level 4. The number of draws is the + // same either way, only the size of the bid could differ. + // (Known gap: the stale slot lies 0x1cc-0x218 bytes below the caller's stack + // pointer and holds whatever the functions DayStepRest3 called before left there. + // Level 4 matches WEEK21->22; in the summer of WEEK42->43 the original had level 0 + // for a bid of day 337, so only the amounts of such bids may differ. Season 2 shows + // level 0 as well (WEEK57, WEEK65: the salary factor gives r = W(90, 95)), so the + // slot then holds no bid key at all - a key would always give level 4 - but data + // of another function at that stack depth; WEEK42/44/59/63 fit neither 0 nor 4. + // A different amount can change which bid wins later (WEEK149, day 1275: another + // club got the player, the line-ups and then the injury rolls went apart).) + if (chosen >= 0) keys[0] = chosen < n ? sorted[size_t(chosen)] : 4 * 0x50; + } + if (chosen < 0) { + if (list != 0) return; + if (first_pass) { + first_pass = false; + continue; + } + report.fail("transfer: no club found (internal error 0x2a)"); + return; + } + if (list == 0) { + // no list entry: the player moves straight to the club (its first empty squad + // slot, FirstFreeSlotSquad), which gets a new line-up (Int2(club, 100)) + const SquadRange r = squad_range(chosen); + int free = -1; + for (size_t s = r.first; s < r.first + r.count && free < 0; s++) + if (g.squad_slots.at(s) == 0x0FFF) free = int(s); + if (free < 0) { + report.fail("transfer: no room in the club's squad (internal error 0x2c)"); + return; + } + g.squad_slots.at(size_t(free)) = uint16_t(player); + try { + auto_lineup(g, chosen, 100); + } catch (const std::exception& ex) { + report.fail(std::string("line-up after a transfer: ") + ex.what()); + } + return; + } + mem.set16(list + uint32_t(free_bid) * 2, uint16_t(chosen)); + if (mem.u16(list + 8) == 0xffe) { + mem.set8(list + 0x34 + uint32_t(free_bid), uint8_t(uint8_t(months) * 0xc)); + } else { + bool loan = rand.range(0, 6) == 4; + if (mem.u16(list + 8) == 0xfff) loan = false; + const int m = rand.range(1, 4 - (loan ? 3 : 0)); + mem.set8(list + 0x34 + uint32_t(free_bid), uint8_t(uint8_t(m * 0xc) | (loan ? 0x80 : 0))); + if (loan && rand.range(0, 10) > 7) mem.set8(list + 0x34 + uint32_t(free_bid), 0x98); + } + // RateTransferBidSource: fee and salary bases of the offer + const uint8_t term = mem.u8(list + 0x34 + uint32_t(free_bid)); + uint32_t fee_base = (mem.u32(list + 0x2c) / 10000) * 0x30d4; + if (term & 0x80) fee_base >>= 2; + const int years = ((term & 0x7F) - 1) / 0xc; + const uint32_t salary_base = ((uint32_t(years * 0x14 + 100) * mem.u32(list + 0x30)) / 10000) * 100; + uint32_t k = keys[0] / 0x50; + int16_t level = int16_t(std::clamp(int(int16_t(k)), 0, 4)); + level = int16_t(level + ((g.team_flags.at(size_t(chosen)) >> 14) & 3)); + const uint32_t r = uint32_t(rand.range(0x5a, level * 5 + 0x5f)); + uint32_t factor = (r * uint32_t(int16_t(bonus_need) + 100)) / 100; + if (high) factor = uint32_t(rand.range(0x78, 0x96)); + mem.set32(list + 0x1c + uint32_t(free_bid) * 4, ((factor * fee_base) / 1000000) * 10000); + mem.set32(list + 0x0c + uint32_t(free_bid) * 4, ((salary_base * r) / 10000) * 100); + for (int i = 0; i < 7; i++) mem.set8(list + 0x38 + uint32_t(free_bid) * 7 + uint32_t(i), 0); + return; + } +} + +namespace { + +// RateTransferBidSource: fee and salary bases of bid `bid` of a list entry (-1: none, a one-year +// term): the fee base is the market value / 10000 * 12500 (a quarter for a loan), the +// salary base the salary * (100 + 20 per extra contract year) / 100. +void offer_bases(const StaticMemory& mem, uint32_t list, int bid, uint32_t& fee_base, uint32_t& salary_base) { + bool loan = false; + uint8_t years = 1; + if (bid != -1) { + const uint8_t term = mem.u8(list + 0x34 + uint32_t(bid)); + loan = (term & 0x80) != 0; + years = uint8_t(((term & 0x7F) - 1) / 0xc); + } + fee_base = (mem.u32(list + 0x2c) / 10000) * 0x30d4; + if (loan) fee_base >>= 2; + salary_base = ((uint32_t(years * 0x14 + 100) * mem.u32(list + 0x30)) / 10000) * 100; +} + +// ProjectTransferOfferList: how good bid `bid` is, as percentages of the bases (fee, salary); a fee +// below W(90, 100) % or a salary below the player's demand (entry +0x55) counts 0. +bool evaluate_bid(ModernState& g, uint32_t list, int bid, uint32_t& fee_pct, uint32_t& salary_pct, WatcomRandom& rand, + MinuteReport& report) { + StaticMemory& mem = g.memory; + uint32_t fee_base = 0, salary_base = 0; + offer_bases(mem, list, bid, fee_base, salary_base); + if (fee_base == 0 || salary_base == 0) { + report.fail("transfer list: bid bases 0 (the original divides by zero)"); + return false; + } + fee_pct = uint32_t(int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)) * 100) / fee_base; + const int32_t salary = int32_t(mem.u32(list + 0x0c + uint32_t(bid) * 4)); + uint64_t expected_salary = uint32_t(salary); + const int bidder = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const int manager = g.manager_of(bidder); + if (manager >= 0) { + const int position = int(g.players.at(size_t(g.squad_slots.at(transfer_list_slot() + size_t(list - kTransferList) / kListEntry) & 0xfff)).w364 & 3); + static constexpr uint8_t goals[4] = {0, 2, 4, 8}; + const uint64_t annual = uint32_t(salary); + expected_salary += annual * mem.u8(list + 0x38 + uint32_t(bid) * 7) * goals[position] / 100 / 12; + expected_salary += annual * mem.u8(list + 0x39 + uint32_t(bid) * 7) * 34 / 100 / 12; + expected_salary += annual * mem.u8(list + 0x3a + uint32_t(bid) * 7) * 25 / 100 / 12; + } + salary_pct = uint32_t(expected_salary * 100 / salary_base); + if (fee_pct < uint32_t(rand.range(0x5a, 100))) fee_pct = 0; + if (salary_pct < mem.u8(list + 0x55)) salary_pct = 0; + return true; +} + +// Pending callers supply their explicit ordinary/special-list-derived Source +// pool index. The shared ProjectTransferOfferList primitive never performs this mapping itself. +bool evaluate_pending_human_bid(ModernState& g, uint32_t list, int bid, + uint32_t& fee_pct, uint32_t& salary_pct, + WatcomRandom& rand, MinuteReport& report, + const SourcePendingOwner* owner = nullptr) { + if (list < kTransferList || (list - kTransferList) % kListEntry != 0 || + (list - kTransferList) / kListEntry >= 44 || bid < 0 || bid >= 4 || + !g.memory.has(list + kListEntry - 1)) { + report.fail("ProjectTransferOfferList: invalid pending caller list/bid coordinates"); + return false; + } + const int entry = int((list - kTransferList) / kListEntry); + const size_t slot = transfer_list_slot() + size_t(entry); + if (slot >= g.squad_slots.size()) { + report.fail("ProjectTransferOfferList: pending caller source slot outside native storage"); + return false; + } + TransferBidRatingRequest request{int(slot), entry, bid, + int(int16_t(g.memory.u16(list + uint32_t(bid) * 2))), + int(g.squad_slots.at(slot) & 0x0fff)}; + if(owner)request.source_pending_owner=*owner; + const auto rating = modern::rate_transfer_bid_source(g, request, rand, report); + fee_pct = rating.fee_pct; + salary_pct = rating.salary_pct; + return rating.supported; +} + +// Foreigners2: players of a club (squad slots start..start+count, plus the ones bought +// for later, table Career_RemoveJoinLoans_RuntimeField) whose nationality differs from `nation`. +int foreigners(const ModernState& g, int team, size_t start, size_t count, int nation) { + int n = 0; + for (size_t s = start; s < start + count; s++) { + const int p = g.squad_slots.at(s) & 0xFFF; + if (p != 0xFFF && (modern::nationality(g, p) & 0xFFFF) != nation) n++; + } + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && ((e >> 12) & 0x3FF) == uint32_t(team) && (modern::nationality(g, int(e & 0xFFF)) & 0xFFFF) != nation) n++; + } + return int8_t(n); +} + +// InterestedManagers(seller, buyer): human managers interested in a transfer: those in the league +// of the seller or the buyer whose club is within 5 table places of one of them (only with +// the option Weekly_InterestedManagers_RuntimeField off and a real seller). +uint32_t interested_managers(const ModernState& g, int seller, int buyer) { + uint32_t mask = 0; + if (g.memory.has(::bmh::layout::Weekly_InterestedManagers_RuntimeField) && g.memory.u8(::bmh::layout::Weekly_InterestedManagers_RuntimeField) != 0) return 0; + for (size_t m = 0; m < g.manager_teams.size(); m++) { + if (seller == 0xFFF) continue; + const int league = g.manager_records.at(m * kRecord + 0x210); + if (league_of(seller) != league && league_of(buyer) != league) continue; + const int own = int8_t(modern::table_position(g, g.manager_teams[m])); + if (std::abs(own - int16_t(modern::table_position(g, seller))) > 5 && std::abs(own - int16_t(modern::table_position(g, buyer))) > 5) + continue; + mask |= 1u << m; + } + return mask; +} + +} // namespace + +TransferBidRating rate_transfer_bid_source(ModernState& g, const TransferBidRatingRequest& request, + WatcomRandom& rand, MinuteReport& report) { + if (report.unsupported) return {}; + const auto fail = [&](const std::string& why) { + report.fail("ProjectTransferOfferList: " + why); + return TransferBidRating{}; + }; + if (request.list_entry < 0 || request.list_entry >= 44 || + request.bid_slot < 0 || request.bid_slot >= 4 || request.source_slot < 0 || + size_t(request.source_slot) >= g.squad_slots.size()) + return fail("invalid explicit source/list/bid coordinates"); + const uint32_t list = kTransferList + uint32_t(request.list_entry) * kListEntry; + if (!g.memory.has(list + kListEntry - 1)) + return fail("missing native transfer list storage"); + const int player = int(g.squad_slots.at(size_t(request.source_slot)) & 0x0fff); + const int bidder = int(int16_t(g.memory.u16(list + uint32_t(request.bid_slot) * 2))); + if (player == 0x0fff || size_t(player) >= g.players.size() || + player != request.expected_player || bidder != request.expected_bidder || + bidder < 0 || bidder >= league_clubs()) + return fail("source player/bidder identity mismatch"); + uint32_t fee_base = 0, salary_base = 0; + offer_bases(g.memory, list, request.bid_slot, fee_base, salary_base); + if (fee_base == 0 || salary_base == 0) + return fail("zero Source denominator (original divide-by-zero boundary)"); + const bool native_takeover=request.source_pending_owner.has_value(); + if(native_takeover && (request.bid_slot!=0 || + !source_pending_owner_valid(g,*request.source_pending_owner,request.list_entry,size_t(request.source_slot)))) + return fail("invalid DispatchClubPlayerPendingOffers native pending owner context"); + const int manager = pending_native_manager_of(g,bidder,native_takeover); + if (manager >= 0) { + const bool parked=manager==4 && native_takeover; + if ((!parked && (manager >= 4 || size_t(manager) >= g.manager_teams.size() || + std::count(g.manager_teams.begin(), g.manager_teams.end(), bidder) != 1)) || + size_t(manager) * kRecord + 0x292 > g.manager_records.size() || + size_t(manager) * kBoard + kBoardSlot > g.tactics.size()) + return fail("unsupported native human bidder record/board"); + const size_t rec = size_t(manager) * kRecord; + const int record_team = int(g.manager_records.at(rec + 0x290)) | + (int(g.manager_records.at(rec + 0x291)) << 8); + if (record_team != bidder) + return fail("bidder manager record and runtime team disagree"); + const auto range = squad_range(bidder); + if (range.count == 0 || range.first + range.count > g.squad_slots.size()) + return fail("bidder fitness squad outside native storage"); + for (size_t slot = range.first; slot < range.first + range.count; ++slot) { + const uint16_t word = g.squad_slots.at(slot); + if (word != 0x0fff && (word & kSlotInLineup) && + size_t(word & 0x0fff) >= g.players.size()) + return fail("bidder lineup references an unavailable fitness player"); + } + } + try { + // Void5 mode4 has real divisions by each recent table's games. + // Keep that native error boundary instead of accepting per_game's + // generic zero fallback on an incomplete controlled/malformed season. + if (manager >= 0) { + const int league = team_league(bidder); + if (league >= kLeagueCount || size_t(league) >= g.league_rounds.size()) + return fail("missing bidder prediction league"); + const int rounds = int(int8_t(g.league_rounds.at(size_t(league)))); + if (rounds >= 2 && rounds < league_matchdays(league)) { + const auto recent = compute_league_table(g, league, std::max(0, rounds - 5), rounds, 3, 0); + for (int club = 0; club < recent.size; ++club) + if (recent.games(club) == 0) + return fail("zero recent games in Source rank prediction"); + } + } + TransferBidRating rating; + rating.fee_pct = (g.memory.u32(list + 0x1c + uint32_t(request.bid_slot) * 4) * 100u) / fee_base; + uint32_t total_salary = g.memory.u32(list + 0x0c + uint32_t(request.bid_slot) * 4); + if (manager >= 0) { + const size_t board = size_t(manager) * kBoard; + std::array saved{}; + std::copy_n(g.tactics.begin() + std::ptrdiff_t(board), kBoardSlot, saved.begin()); + struct RestoreBoard { + ModernState& state; size_t offset; + const std::array& saved; + ~RestoreBoard() { + std::copy(saved.begin(), saved.end(), state.tactics.begin() + std::ptrdiff_t(offset)); + } + } restore{g, board, saved}; + // ProjectTransferOfferList's stack board reads only salary+50 and seven bonuses + // +12. No seller board, actual bidder row, mood or 80% weighting. + for (int b = 0; b < 4; ++b) + g.tactics.at(board + 0x50 + size_t(b)) = uint8_t(total_salary >> (8 * b)); + for (int b = 0; b < 7; ++b) + g.tactics.at(board + 0x12 + size_t(b)) = + g.memory.u8(list + 0x38 + uint32_t(request.bid_slot) * 7 + uint32_t(b)); + total_salary += manager==4 + ? modern::expected_bonus_parked_club_source(g,0xff,0,player,true) + : modern::expected_bonus(g, manager, 0xff, 0, player, true); + } // Restore the full borrowed board before threshold W or any caller. + rating.salary_pct = (total_salary * 100u) / salary_base; + if (rating.fee_pct < uint32_t(rand.range(90, 100))) rating.fee_pct = 0; + if (rating.salary_pct < g.memory.u8(list + 0x55)) rating.salary_pct = 0; + rating.supported = true; + return rating; + } catch (const std::exception& e) { + return fail(e.what()); + } +} + +// Int2(team, 100) for the clubs of a transfer (only clubs with a squad). +static void lineup_after_transfer_impl(ModernState& g, int team, bool native_takeover) { + if (pending_native_manager_of(g,team,native_takeover)==4) + auto_lineup_parked_club_source(g,team,100); + else if (team < league_clubs() || team == no_team()) auto_lineup(g, team, 100); +} + +void lineup_after_transfer(ModernState& g, int team) { lineup_after_transfer_impl(g,team,false); } + +// ReleasePlayer closes the seller's squad and native human board gap. +static bool remove_from_seller_impl(ModernState& g, int seller, int player, MinuteReport& report, + bool native_takeover) { + player &= 0xFFF; + if (seller == 0xFFF || seller == 0xFFFF) { + for (size_t s = transfer_list_slot(); s < pool_end_slot(); s++) // CareerRuntimeField .. LargeSquadClubCount + if ((g.squad_slots[s] & 0xFFF) == player) g.squad_slots[s] = 0xFFF; + return true; + } + const SquadRange range = squad_range(seller); + size_t at = range.first; + while (at < range.first + range.count && (g.squad_slots[at] & 0xFFF) != player) at++; + if (at == range.first + range.count) { + report.fail("transfer: the player is not in the seller's squad (internal error 0x21)"); + return false; + } + for (size_t s = transfer_list_slot(); s < 2972; s++) // CareerRuntimeField .. CareerRuntimeField2 + if ((g.squad_slots[s] & 0xFFF) == player) g.squad_slots[s] = 0xFFF; + for (size_t s = at; s + 1 < range.first + range.count; s++) g.squad_slots[s] = g.squad_slots[s + 1]; + g.squad_slots[range.first + range.count - 1] = 0xFFF; + // a human club's tactics board rows (0x58 bytes each) move up with the squad; the last + // row keeps its old content (a copy of the row above), as in the original + const int manager = pending_native_manager_of(g, seller, native_takeover); + const size_t row = at - range.first; + if (manager >= 0 && row != 0x17) { + const size_t base = size_t(manager) * 0x840; + std::copy(g.tactics.begin() + long(base + (row + 1) * 0x58), g.tactics.begin() + long(base + 0x18 * 0x58), + g.tactics.begin() + long(base + row * 0x58)); + } + lineup_after_transfer_impl(g, seller, native_takeover); + return true; +} + +bool remove_from_seller(ModernState& g, int seller, int player, MinuteReport& report) { + return remove_from_seller_impl(g,seller,player,report,false); +} + +namespace { + +// Fail(seller, pool slot, buyer, list entry, bid): the player moves to a computer +// club (first free squad slot); a loan is recorded in Career_RemoveJoinLoans_RuntimeField / ClubPlayerDetail_InvalidArgument_RuntimeField. +void move_player(ModernState& g, int seller, size_t pool_slot, int buyer, uint32_t list, int bid, WatcomRandom& rand, + MinuteReport& report, TransferAllocatorContext allocator, bool native_takeover = false) { + // The ordinary accepted human-buyer loan route is settled by the shared helper in + // execute_transfer. Keep this fallback guarded for legacy callers without that owner. + (void)allocator; + StaticMemory& mem = g.memory; + const int player = g.squad_slots.at(pool_slot) & 0xFFF; + for (int k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xFFF) == player) { + report.fail("transfer: the player is already bought for later (internal error 0x30)"); + return; + } + } + if (player == 0xFFF) { + report.fail("transfer: no player (internal error 0x31)"); + return; + } + const uint8_t term = mem.u8(list + 0x34 + uint32_t(bid)); + const bool loan = term > 0x7F; + const int buyer_manager = pending_native_manager_of(g, buyer, native_takeover); + const int seller_manager = pending_native_manager_of(g, seller, native_takeover); + // Deliberate Original bug fix (#105): record4 parks club manager0 only. + // Fail uses DeskActions_Unsupported_RuntimeField[4], corrupting graphics pointer bbccc, and saves + // snapshot owner4 which cannot match the club after NationalCoachHandBack handback. + // Preserve the actual board4 below, but persist its real club owner0 in + // the existing four-byte counter/snapshot format. Never invent counter4. + const int loan_owner_manager = native_takeover && seller_manager == 4 ? 0 : seller_manager; + int loan_slot = -1; + int owner_snapshot_slot = -1; + int owner_squad_row = -1; + std::array owner_board_snapshot{}; + if (loan) { + if (buyer_manager >= 0) { + report.fail("transfer: loans to a human manager are not supported yet"); + return; + } + // EntryLoanLedgerMustHaveSlotBefore's 200-entry loan ledger must have a slot before any squad/account + // mutation. Keep the existing AI-only path's layout and draw order unchanged. + for (int k = 0; k < 200; ++k) { + if (mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4) == 0) { loan_slot = k; break; } + } + if (loan_slot < 0) { + report.fail("transfer: loan table full (internal error 0x36)"); + return; + } + if (seller_manager >= 0) { + // Fail allows a human owner to lend to a computer club only while + // below the three-loan limit and with a free Source snapshot record. + if (loan_owner_manager >= 4 || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) || + mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) >= 3 || + !mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || + !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b)) { + report.fail("transfer: no available human-owner loan record"); + return; + } + for (int k = 0; k < 12; ++k) { + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(k) * 2) == uint16_t(player)) { + report.fail("transfer: player already has a human-owner loan record"); + return; + } + if (owner_snapshot_slot < 0 && mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(k) * 2) == 0x0fff) + owner_snapshot_slot = k; + } + if (owner_snapshot_slot < 0) { + report.fail("transfer: human-owner loan snapshots full (internal error 0x34)"); + return; + } + const SquadRange owner_range = squad_range(seller); + for (size_t row = 0; row < owner_range.count; ++row) { + if ((g.squad_slots.at(owner_range.first + row) & 0x0fff) == player) { + owner_squad_row = int(row); + break; + } + } + const size_t board = size_t(seller_manager) * 0x840 + + size_t(std::max(owner_squad_row, 0)) * 0x58; + if (owner_squad_row < 0 || board + owner_board_snapshot.size() > g.tactics.size()) { + report.fail("transfer: human-owner loan player has no board row"); + return; + } + std::copy_n(g.tactics.begin() + std::ptrdiff_t(board), owner_board_snapshot.size(), + owner_board_snapshot.begin()); + } + } + // FirstFreeSlotSquad: first free slot of the buyer's squad + const SquadRange range = squad_range(buyer); + size_t slot = range.first; + while (slot < range.first + range.count && g.squad_slots[slot] != 0xFFF) slot++; + if (slot == range.first + range.count) return; // squad full (message box PendingOffer_FormatError_ExecutableField) + g.squad_slots[slot] = uint16_t(player); + if (buyer_manager >= 0) { + const size_t row = slot - range.first; + modern::new_board_entry(g, buyer_manager, int(row), int(slot), rand); + const size_t board = size_t(buyer_manager) * 0x840 + row * 0x58; + const uint32_t salary = mem.u32(list + 0x0c + uint32_t(bid) * 4); + for (int b = 0; b < 4; ++b) g.tactics.at(board + 0x50 + size_t(b)) = uint8_t(salary >> (b * 8)); + g.tactics.at(board + 0x0c) = uint8_t((term & 0x7f) == 0 ? 0x18 : (term & 0x7f)); + // Fail (human buyer): the market salary for the term (AddToSquad at 100 %, + // the term in months as its year count, as the original passes it) ... + uint32_t reference_fee = 0, reference_salary = 0; + modern::market_value(g, int(pool_slot), 0, 100, reference_fee, reference_salary, int(term & 0x7f), 0, rand); + for (int b = 0; b < 7; ++b) g.tactics.at(board + 0x12 + size_t(b)) = mem.u8(list + 0x38 + uint32_t(bid) * 7 + uint32_t(b)); + // ... and his mood (+0x0d): what the contract is worth against it, salary plus 80 % of + // the expected bonus (ContractOffer), 0-255 (ClampInteger). The port left it out, so a + // player bought this way kept the 0 of the new board row and asked for nothing at his + // renewal (#40: HENDERSON 60.900 -> 0, later 8.580). +0x54 is the price paid. + const uint32_t bonus = modern::expected_bonus(g, buyer_manager, 0xff, int(row), player, true); + const int32_t worth = int32_t(salary) + int32_t(bonus * 0x50u) / 100; + const int32_t ratio = reference_salary == 0 ? 0xff : int32_t(uint32_t(worth) * 100u / reference_salary); + g.tactics.at(board + 0x0d) = uint8_t(std::clamp(ratio, 0, 0xff)); + const uint32_t price = mem.u32(list + 0x1c + uint32_t(bid) * 4); + for (int b = 0; b < 4; ++b) g.tactics.at(board + 0x54 + size_t(b)) = uint8_t(price >> (b * 8)); + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[move_player mood player %d: salary %u bonus %u reference %u -> %d]\n", player, salary, bonus, + reference_salary, int(g.tactics.at(board + 0x0d))); + modern::book_money(g, buyer_manager, int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)), true, true); + } + if (!remove_from_seller_impl(g, seller, player, report, native_takeover)) return; + lineup_after_transfer_impl(g, seller, native_takeover); + lineup_after_transfer_impl(g, buyer, native_takeover); + if (loan) { + // Fail stores the owner's original manager-board row before loaning + // a human-owned player to an AI club. Snapshot bytes and manager mapping stay + // intact after return; Source only frees the player-ID slot and decrements count. + if (seller_manager >= 0) { + const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(owner_snapshot_slot) * 0x58; + for (size_t b = 0; b < owner_board_snapshot.size(); ++b) + mem.set8(snapshot + uint32_t(b), owner_board_snapshot[b]); + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(owner_snapshot_slot) * 2, uint16_t(player)); + mem.set8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(owner_snapshot_slot), uint8_t(loan_owner_manager)); + mem.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager), uint8_t(mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) + 1)); + } + // EntryLoanLedgerMustHaveSlotBefore: the player returns to the seller after `term & 0x7f` months. + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan_slot), uint8_t(term & 0x7F)); + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan_slot) * 4, uint32_t(player + seller * 0x1000 + buyer * 0x400000)); + } +} + +// Validate the extra state needed by Fail before execute_transfer emits news or +// books the human owner's fee. move_player repeats the checks immediately before its +// mutations; the caller invokes this first so an unavailable Source loan record cannot +// produce a half-completed transfer. +bool preflight_human_owner_loan(const ModernState& g, int seller, size_t pool_slot, int buyer, + MinuteReport& report, bool require_squad_room = true, bool native_takeover = false) { + const int owner_manager = pending_native_manager_of(g, seller, native_takeover); + // Match move_player's explicit #105 correction: board4 belongs to the + // persistent club manager0; bbccc is a graphics pointer, never a counter. + const int loan_owner_manager = native_takeover && owner_manager == 4 ? 0 : owner_manager; + const auto& mem = g.memory; + const int player = g.squad_slots.at(pool_slot) & 0x0fff; + if (seller == 0x0fff) { + report.fail("transfer: Source free-agent loan return destination is not represented"); + return false; + } + if (buyer < 0 || buyer >= league_clubs()) { + report.fail("transfer: loan buyer has no squad"); + return false; + } + if (!mem.has(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + 199u * 4u + 3u)) { + report.fail("transfer: loan ledger storage is truncated"); + return false; + } + if (owner_manager >= (native_takeover ? 5 : 4) || (owner_manager >= 0 && (!mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) || + mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) >= 3 || !mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || + !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b)))) { + report.fail("transfer: no available human-owner loan record"); + return false; + } + int snapshot_slot = -1; + int loan_slot = -1; + for (int i = 0; i < 200; ++i) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(i) * 4); + if (e == 0 && loan_slot < 0) loan_slot = i; + else if (e != 0 && int(e & 0x0fff) == player) { + report.fail("transfer: the player is already bought for later (internal error 0x30)"); + return false; + } + } + if (loan_slot < 0) { + report.fail("transfer: loan table full (internal error 0x36)"); + return false; + } + if (owner_manager >= 0) for (int i = 0; i < 12; ++i) { + const uint16_t id = mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2); + if (id == uint16_t(player)) { + report.fail("transfer: player already has a human-owner loan record"); + return false; + } + if (snapshot_slot < 0 && id == 0x0fff) snapshot_slot = i; + } + if (owner_manager >= 0 && snapshot_slot < 0) { + report.fail("transfer: human-owner loan snapshots full (internal error 0x34)"); + return false; + } + const SquadRange seller_range = squad_range(seller); + bool owner_has_player = false; + for (size_t i = 0; i < seller_range.count; ++i) + if ((g.squad_slots.at(seller_range.first + i) & 0x0fff) == player) owner_has_player = true; + if (!owner_has_player) { + report.fail("transfer: the player is not in the seller's squad (internal error 0x21)"); + return false; + } + const size_t board = owner_manager >= 0 ? size_t(owner_manager) * 0x840 : 0; + if (owner_manager >= 0 && (g.tactics.size() < board + 0x18 * 0x58 || !seller_range.count)) { + report.fail("transfer: human-owner loan player has no board row"); + return false; + } + const SquadRange buyer_range = squad_range(buyer); + bool room = false; + for (size_t i = 0; i < buyer_range.count; ++i) + if (g.squad_slots.at(buyer_range.first + i) == 0x0fff) { room = true; break; } + if (require_squad_room && !room) { + report.fail("transfer: buyer squad is full"); + return false; + } + return true; +} + +// The weekly transfer itself (Void2): news for the interested human +// managers (all of them with the option Weekly_ExecuteTransfer_RuntimeField off), then the move. +void execute_transfer(ModernState& g, int k, uint32_t list, int bid, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + const int seller = mem.u16(list + 8) & 0x7FFF; // Canonical free-player seller is 0x0fff; FFFF is not its alias. + const int buyer = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const uint8_t term = mem.u8(list + 0x34 + uint32_t(bid)); + const int buyer_manager = g.manager_of(buyer); + // SettleHumanBuyerSale books fees for human managers through the shared settlement. + uint32_t mask = 0x80000000u; + if (!(mem.has(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) && mem.u8(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) != 0)) mask = 0xFFFFFFFFu; + const uint32_t interested = interested_managers(g, seller, buyer); + const size_t pool_slot = transfer_list_slot() + size_t(k); + if (term > 0x7f && + !preflight_human_owner_loan(g, seller, pool_slot, buyer, report, buyer_manager < 0)) return; + // SettleHumanBuyerSale/Fail owns ordinary purchases and loans for human 24-slot buyers. + // Require the explicit runtime allocator observation for either contract; + // AI buyers retain the original legacy path. + if (buyer_manager >= 0) { + HumanBuyerSaleHooks hooks; + switch (allocator) { + case TransferAllocatorContext::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case TransferAllocatorContext::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: + report.fail("PendingOfferAnswer: general weekly human-buyer sale has no observed allocator gate"); + return; + } + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + hooks.notice = [&](const GameState&, const HumanBuyerSaleNotice& notice) { + post_composed(g, notice.manager, notice.original_message); + }; + hooks.after_paid_accounts = [&](GameState& base, const HumanBuyerSalePaid& paid) { + auto& state = static_cast(base); + uint32_t message_mask = 0x80000000u; + if (paid.seller_manager >= 0) message_mask |= 1u << paid.seller_manager; + if (!(state.memory.has(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) && state.memory.u8(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) != 0)) + message_mask = 0xffffffffu; + else + message_mask |= 1u << paid.buyer_manager; + const uint32_t interested = interested_managers(state, paid.seller, paid.buyer); + if ((message_mask | interested) == 0x80000000u) return; + const std::string message = message_text(state, ::bmh::layout::Month_SearchProfileNews_TextPointer) + state.player_name(paid.player) + + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer) + state.club_name(paid.seller) + + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer2) + format_number(state, int32_t(paid.raw_fee), 0x101) + + message_text(state, ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7) + state.club_name(paid.buyer) + + message_text(state, (paid.term & 0x80) ? ::bmh::layout::Weekly_ExecuteTransfer_TextPointer3 : ::bmh::layout::Weekly_ExecuteTransfer_TextPointer4); + post_composed(state, int64_t(message_mask | interested), message); + }; + HumanBuyerSaleRequest request; + request.list_entry = k; + request.bid_slot = bid; + request.list_address = list; + request.source_pool_slot = pool_slot; + request.expected_seller = seller; + request.expected_buyer = buyer; + request.expected_active_manager = mem.has(::bmh::layout::ActiveManager) ? int(mem.u8(::bmh::layout::ActiveManager)) : -1; + request.day_step = true; // (a bid of manager 1 may be decided on manager 2's turn) + const auto settled = modern::settle_human_buyer_sale(g, request, hooks, rand, report); + (void)settled; // Void2 clears the completed list for refused/blocked outcomes too. + return; + } + if ((mask | interested) != 0x80000000u) { + const int32_t fee = int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)); + std::string msg = message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(g.squad_slots.at(pool_slot)) + message_text(g, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer) + + g.club_name(seller) + message_text(g, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer2) + format_number(g, fee, 0x101) + + message_text(g, ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7) + g.club_name(buyer) + + message_text(g, term > 0x7F ? ::bmh::layout::Weekly_ExecuteTransfer_TextPointer3 : ::bmh::layout::Weekly_ExecuteTransfer_TextPointer4); + post_composed(g, int64_t(mask | interested), msg); + } + move_player(g, seller, pool_slot, buyer, list, bid, rand, report, allocator); + const int seller_manager = g.manager_of(seller); + if (seller_manager >= 0) + modern::book_money(g, seller_manager, -int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)), true, true); +} + +// The bids of an expiring list entry (TransferListCountdown when the countdown reaches 0): every bid +// is rated (fee and salary percentages plus G(0, 10) each, the salary also by the bidder's +// table position), the best one the buyer can afford and has room for gets the player if +// W(90, 110) is below its rating. Returns false when a path is not ported. +bool decide_bids(ModernState& g, int k, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + bool preserve_entry = false; + const uint32_t list = kTransferList + uint32_t(k) * kListEntry; + const int player = g.squad_slots.at(transfer_list_slot() + size_t(k)) & 0xFFF; // local_34 + const int seller = mem.u16(list + 8) & 0x7FFF; + const int seller_manager = g.manager_of(seller); // local_24 / local_1c + int16_t order[4]; + uint32_t score[4]; + int n = 0; + for (; n < 4; n++) { + order[n] = int16_t(n); + if (int16_t(mem.u16(list + uint32_t(n) * 2)) == -1) break; + uint32_t fee = 0, salary = 0; + if (!evaluate_bid(g, list, n, fee, salary, rand, report)) return false; + if (fee == 0 || salary == 0) { + score[n] = 0; + } else { + const int position = int8_t(modern::table_position(g, int16_t(mem.u16(list + uint32_t(n) * 2)))); + salary += uint32_t(game.range(0, 10) + (0x14 - position) / 2); + fee += uint32_t(game.range(0, 10)); + if (fee > 5) fee -= 5; + if (salary > 5) salary -= 5; + score[n] = fee + salary; + } + } + quicksort_by_key(order, score, n); + int c = 0; + for (; c < n; c++) { + const int bid = order[c]; + const int bidder = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const int bidder_manager = g.manager_of(bidder); + if (bidder_manager >= 0) { + const int32_t fee = int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)); + const size_t rec = size_t(bidder_manager) * 0xb0c; + const int32_t balance = int32_t(uint32_t(g.manager_records.at(rec + 0x314)) | + uint32_t(g.manager_records.at(rec + 0x315)) << 8 | uint32_t(g.manager_records.at(rec + 0x316)) << 16 | + uint32_t(g.manager_records.at(rec + 0x317)) << 24); + const int32_t credit = int32_t(uint32_t(g.manager_records.at(rec + 0x31c)) | + uint32_t(g.manager_records.at(rec + 0x31d)) << 8 | uint32_t(g.manager_records.at(rec + 0x31e)) << 16 | + uint32_t(g.manager_records.at(rec + 0x31f)) << 24); + if (int64_t(balance) + credit < fee) { + // the board forbids further talks for financial reasons (Weekly_DecideBids_TextPointer / Weekly_DecideBids_TextPointer2) + post_composed(g, bidder_manager, message_text(g, ::bmh::layout::Weekly_DecideBids_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_DecideBids_TextPointer2)); + continue; + } + } + const SquadRange range = squad_range(bidder); + const int nation = team_region(bidder) & 0xFF; // Foreigners + const int others = foreigners(g, bidder, range.first, range.count, nation); + // The foreigner limit of a computer seller's list (more than three foreigners in the + // bidder's squad, a player of another nation) only stops computer bidders: a human + // bidder goes on to the squad check (TransferListCountdown, `local_28 != 0xff`). + if (seller_manager < 0 && others > 3 && (modern::nationality(g, player) & 0xFFFF) != nation && bidder_manager < 0) continue; + if (modern::squad_count(g, bidder, 3) < int(range.count) - 1) break; // room in the squad + // a full squad: a human bidder hears that the board approves no more transfers (DeskActions_Unsupported_ExecutableField) + if (bidder_manager >= 0) post_text(g, bidder_manager, text_id(::bmh::layout::DeskActions_Unsupported_ExecutableField)); + } + if (c == n) { + // TransferListCountdown sends the expiry notice to the seller and every human bidder. + uint32_t audience = 0x80000000u; + if (seller_manager >= 0) audience |= 1u << seller_manager; + for (int i = 0; i < n; ++i) { + const int manager = g.manager_of(int16_t(mem.u16(list + uint32_t(i) * 2))); + if (manager >= 0) audience |= 1u << manager; + } + if (audience != 0x80000000u) { + const std::string msg = message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_DecideBids_TextPointer3); + post_composed(g, int64_t(audience), msg); + } + } else { + const int bid = order[c]; + const int bidder = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const uint32_t r = uint32_t(rand.range(0x5a, 0x6e)); + bool accept = r < score[c]; + if (seller_manager >= 0) { + if (g.transfer_offer_selector) { + TransferOfferListView view = modern::project_transfer_offer_list(g, k); + if (allocator == TransferAllocatorContext::zero || allocator == TransferAllocatorContext::blocked) + for (auto& offer : view.offers) + if (offer.present && offer.loan && offer.buyer_manager >= 0) + offer.transaction_supported = true; + view.preferred_bid_index = bid; + view.preferred_bid_passed_random_check = accept; + auto refresh_quote = [&]() { + const SquadRange seller_range = squad_range(seller); + size_t seller_slot = seller_range.first; + while (seller_slot < seller_range.first + seller_range.count && + (g.squad_slots.at(seller_slot) & 0x0fff) != player) ++seller_slot; + if (seller_slot >= seller_range.first + seller_range.count || seller_manager < 0 || + size_t(seller_manager) * kBoard + (seller_slot - seller_range.first) * kBoardSlot + 0x0c >= + g.tactics.size()) return false; + const size_t board = size_t(seller_manager) * kBoard + + (seller_slot - seller_range.first) * kBoardSlot; + const int months = g.tactics[board + 0x0c]; + int years = months > 0 ? (months - 1) / 12 + 1 : 1; + if (years > 4) years = 4; + view.quoted_years = uint8_t(years); + const int percent = game.range(0x5c, 0x6c); // OpenTransferEditor: GameRandom + view.quoted_fee = 0; + view.quoted_monthly_salary = 0; + modern::market_value(g, int(transfer_list_slot() + size_t(k)), 0, percent, + view.quoted_fee, view.quoted_monthly_salary, years, 0, rand); + // OpenTransferEditor passes the seller's own bid slot to RateTransferBidSource + // when one exists, otherwise -1 for the generic asking reference. + int own_bid = -1; + for (int row = 0; row < 4; ++row) { + const int buyer_id = int16_t(mem.u16(list + uint32_t(row) * 2)); + if (buyer_id == -1) break; + if (buyer_id == seller) { own_bid = row; break; } + } + offer_bases(mem, list, own_bid, view.asking_fee, view.asking_monthly_salary); + return true; + }; + if (!refresh_quote()) { + report.fail("transfer offer: seller player has no source quote row"); + return false; + } + int malformed_responses = 0; + while (view.offer_count > 0) { + const int selected = g.transfer_offer_selector(g, view); + if (selected == -1) { + accept = false; + if (g.transfer_decision_observer && !g.transfer_notice_suppressed) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::confirmation; + event.offers = view; + event.selected_bid_index = -1; + event.accepted = false; + event.viewer_manager = seller_manager; + event.result_text_address = ::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField; // IncomingTransferScreen explicit right-click decline + g.transfer_decision_observer(event); + } + break; + } + if (selected < 0 || selected >= 4 || !view.offers[size_t(selected)].present) { + // The original mouse loop rejects an empty row without a game + // action. The current port cannot complete a human-involved loan + // lifecycle; keep that row unavailable rather than enter a known + // failing transfer/return path. Bound only malformed replies. + view.notice_text_address = 0; + if (++malformed_responses >= 8) { + preserve_entry = true; + break; + } + continue; + } + const TransferOfferCandidateView& chosen = view.offers[size_t(selected)]; + if (chosen.loan && !chosen.loan_permitted) { + // IncomingTransferScreen refuses a loan when DeskActions_Unsupported_RuntimeField[seller] is >= 3, + // displays PendingOffer_PendingOfferNoticeDialog_ExecutableField2, and returns to the same choice screen. + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField2; + if (!refresh_quote()) return false; + continue; + } + if (chosen.loan && chosen.buyer_manager >= 0 && + (allocator == TransferAllocatorContext::zero || + allocator == TransferAllocatorContext::blocked)) + view.offers[size_t(selected)].transaction_supported = true; + if (!view.offers[size_t(selected)].transaction_supported) { + // A human-involved loan passes the original DeskActions_Unsupported_RuntimeField limit check, + // but this port lacks the board-snapshot/return path. Refuse it + // inertly instead of reaching move_player's known report.fail. + if (++malformed_responses >= 8) { + preserve_entry = true; + break; + } + continue; + } + if (!chosen.affordable) { + // OpenTransferEditor shows DeskActions_SubmitTransferOfferEditorSource_RuntimeField and lets the seller choose again. + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField; + if (!refresh_quote()) return false; + continue; + } + if (!chosen.has_squad_room || !chosen.passes_foreign_limit) { + // Fail reports PendingOffer_FormatError_ExecutableField when the buyer has no free + // place. The foreign-player guard is only reached for a free-agent + // seller; retain it as a defensive boundary here. + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::PendingOffer_FormatError_ExecutableField; + if (!refresh_quote()) return false; + continue; + } + const uint32_t salary_at = list + 0x0c + uint32_t(selected) * 4; + const uint32_t salary_before = mem.u32(salary_at); + mem.set32(salary_at, (salary_before * 10u) >> 3); // temporary 125% for ProjectTransferOfferList + uint32_t fee_pct = 0, salary_pct = 0; + const bool rated = evaluate_bid(g, list, selected, fee_pct, salary_pct, rand, report); + mem.set32(salary_at, salary_before); // Source restores +0x0c before any outcome + if (!rated || report.unsupported) return false; + if ((seller_manager >= 0 && salary_pct != 0) || + (seller_manager < 0 && fee_pct != 0 && salary_pct != 0)) { + const bool moved = modern::accept_transfer_bid_immediately(g, k, selected, rand, report, allocator); + if (!moved && !report.unsupported) + report.fail("transfer offer: selected bid could not be completed"); + if (report.unsupported) return false; + if (moved && seller_manager >= 0 && g.transfer_decision_observer) { + bool buyer_has_player = false; + const SquadRange buyer_range = squad_range(chosen.buyer); + for (size_t row = buyer_range.first; row < buyer_range.first + buyer_range.count; ++row) { + if ((g.squad_slots.at(row) & 0x0fff) == player) { + buyer_has_player = true; + break; + } + } + if (buyer_has_player) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::confirmation; + event.offers = view; // owned snapshot before helper clears the offer rows + event.selected_bid_index = selected; + event.accepted = true; + event.viewer_manager = seller_manager; + event.result_text_address = ::bmh::layout::PendingOffer_FormatError_ExecutableField2; // Void2 prefers the human seller + g.transfer_decision_observer(event); + } + } + accept = false; // immediate helper has already settled the list/player + break; + } + // IncomingTransferScreen clears just the rejected bidder slot and retries the + // same selector while other rows remain. + mem.set16(list + uint32_t(selected) * 2, 0xffff); + view.offers[size_t(selected)].present = false; + view.offers[size_t(selected)].eligible = false; + if (view.preferred_bid_index == selected) { + view.preferred_bid_index = -1; + view.preferred_bid_passed_random_check = false; + } + --view.offer_count; + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField3; + if (view.offer_count <= 0) { + // IncomingTransferScreen displays the final refusal, then returns when + // param_9 reaches zero. It does not redraw OpenTransferEditor. + view.preferred_bid_index = -1; + view.preferred_bid_passed_random_check = false; + (void)g.transfer_offer_selector(g, view); // terminal notice; response ignored + accept = false; + break; + } + if (!refresh_quote()) return false; + } + if (view.offer_count <= 0 || malformed_responses >= 8) accept = false; + // A successful selected-bid transfer was finalized above; prevent the + // legacy top-bid path from executing a second transfer. + if (accept) execute_transfer(g, k, list, bid, rand, report, allocator); + } else { + accept = g.transfer_decision && g.transfer_decision(g, seller_manager, player, bidder, + int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)), + int32_t(mem.u32(list + 0x0c + uint32_t(bid) * 4))); + if (accept) execute_transfer(g, k, list, order[c], rand, report, allocator); + } + } else { + // Original IncomingTransferScreen enters the incoming-offer presentation when + // at least one raw bidder is human, even though the seller is AI. + // OpenTransferEditor computes its one-year reference quote before the + // accept/reject animation. Compute it on both observed and silent + // runs so installing a read-only observer does not alter RNG order. + TransferOfferListView decision_view; + int viewer_manager = -1; + bool human_bidder_present = false; + for (int raw = 0; raw < 4; ++raw) { + const int raw_buyer = int16_t(mem.u16(list + uint32_t(raw) * 2)); + if (raw_buyer == -1) break; + const int manager = g.manager_of(raw_buyer); + if (manager >= 0) { + human_bidder_present = true; + if (viewer_manager < 0) viewer_manager = manager; + } + } + if (human_bidder_present) { + decision_view = modern::project_transfer_offer_list(g, k); + decision_view.preferred_bid_index = bid; + decision_view.preferred_bid_passed_random_check = accept; + decision_view.quoted_years = 1; // OpenTransferEditor uses one year for a computer seller + const int quote_percent = game.range(0x5c, 0x6c); // GameRandom in OpenTransferEditor + modern::market_value(g, int(transfer_list_slot() + size_t(k)), 0, quote_percent, + decision_view.quoted_fee, decision_view.quoted_monthly_salary, 1, 0, rand); + offer_bases(mem, list, -1, decision_view.asking_fee, + decision_view.asking_monthly_salary); // RateTransferBidSource(..., -1) + if (mem.has(::bmh::layout::ActiveManager)) viewer_manager = int(mem.u8(::bmh::layout::ActiveManager)); // ActiveManager + if (g.transfer_decision_observer) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::evaluation; + event.offers = decision_view; + event.selected_bid_index = bid; + event.accepted = accept; + event.viewer_manager = viewer_manager; + event.result_text_address = accept ? ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer3 : ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer4; + g.transfer_decision_observer(event); + } + } + if (accept) { + execute_transfer(g, k, list, order[c], rand, report, allocator); + if (human_bidder_present && !report.unsupported && + g.manager_of(bidder) >= 0 && g.transfer_decision_observer) { + bool buyer_has_player = false; + const SquadRange buyer_range = squad_range(bidder); + for (size_t row = buyer_range.first; row < buyer_range.first + buyer_range.count; ++row) { + if ((g.squad_slots.at(row) & 0x0fff) == player) { + buyer_has_player = true; + break; + } + } + if (buyer_has_player) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::confirmation; + event.offers = decision_view; + event.selected_bid_index = bid; + event.accepted = true; + event.viewer_manager = g.manager_of(bidder); + event.result_text_address = ::bmh::layout::PendingOffer_FormatError_ExecutableField2; // Void2 + g.transfer_decision_observer(event); + } + } + } + } + if (report.unsupported) return false; + } + if (preserve_entry) return true; + for (int b = 0; b < 4; b++) mem.set16(list + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(transfer_list_slot() + size_t(k)) = 0x0FFF; + return true; +} + +} // namespace + +static TransferOfferListView project_transfer_offer_list_impl(const ModernState& g, int entry, bool pending) { + TransferOfferListView view; + if (entry < 0 || entry >= (pending ? 44 : 40) || (pending && entry < 40)) return view; + const uint32_t list = kTransferList + uint32_t(entry) * kListEntry; + if (!g.memory.has(list + kListEntry - 1) || + transfer_list_slot() + size_t(entry) >= g.squad_slots.size()) return view; + const int player = g.squad_slots[transfer_list_slot() + size_t(entry)] & 0x0fff; + if (player == 0x0fff || size_t(player) >= g.players.size()) return view; + + view.valid = true; + view.list_entry = entry; + view.player = player; + view.seller = g.memory.u16(list + 8) & 0x7fff; + view.seller_manager = g.manager_of(view.seller); + for (int bid = 0; bid < 4; ++bid) view.offers[size_t(bid)].bid_index = bid; + if (view.seller_manager >= 0 && g.memory.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(view.seller_manager))) + view.seller_loan_count = g.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(view.seller_manager)); + for (int bid = 0; bid < 4; ++bid) { + const int buyer = int16_t(g.memory.u16(list + uint32_t(bid) * 2)); + // TransferListCountdown stops at the first empty slot; later bytes are not offers. + if (buyer == -1) break; + TransferOfferCandidateView& offer = view.offers[size_t(bid)]; + offer.present = true; + offer.buyer = buyer; + offer.buyer_manager = g.manager_of(buyer); + offer.fee = g.memory.u32(list + 0x1c + uint32_t(bid) * 4); + offer.monthly_salary = g.memory.u32(list + 0x0c + uint32_t(bid) * 4); + const uint8_t term = g.memory.u8(list + 0x34 + uint32_t(bid)); + offer.contract_months = term & 0x7f; + offer.loan = (term & 0x80) != 0; + offer_bases(g.memory, list, bid, offer.fee_reference, offer.salary_reference); + for (int bonus = 0; bonus < 7; ++bonus) + offer.bonuses[size_t(bonus)] = g.memory.u8(list + 0x38 + uint32_t(bid) * 7 + uint32_t(bonus)); + + // These are the non-random preselection guards in TransferListCountdown. The + // projection deliberately leaves ranking and the later ProjectTransferOfferList + // salary/fee recheck to the eventual synchronous selector. + offer.affordable = true; + if (offer.buyer_manager >= 0) { + const size_t rec = size_t(offer.buyer_manager) * kRecord; + if (rec + 0x31f >= g.manager_records.size()) { + offer.affordable = false; + } else { + const auto i32 = [&](size_t at) { + return int32_t(uint32_t(g.manager_records[at]) | + uint32_t(g.manager_records[at + 1]) << 8 | + uint32_t(g.manager_records[at + 2]) << 16 | + uint32_t(g.manager_records[at + 3]) << 24); + }; + offer.affordable = int64_t(i32(rec + 0x314)) + i32(rec + 0x31c) >= offer.fee; + } + } + // Only club IDs have a squad range in the source transfer path. Keep + // malformed IDs visible for diagnosis but never use them as indexes. + const SquadRange range = buyer >= 0 && buyer < league_clubs() ? squad_range(buyer) : SquadRange{}; + offer.has_squad_room = range.count != 0 && modern::squad_count(g, buyer, 3) < int(range.count) - 1; + offer.passes_foreign_limit = range.count != 0; + if (view.seller_manager < 0 && range.count != 0) { + const int nation = team_region(buyer) & 0xff; + const int others = foreigners(g, buyer, range.first, range.count, nation); + if (others > 3 && (modern::nationality(g, player) & 0xffff) != nation) + offer.passes_foreign_limit = false; + } + if (offer.loan) offer.loan_permitted = view.seller_loan_count >= 0 && view.seller_loan_count < 3; + // The human-owner -> AI-borrower route has its Source snapshot and return path; + // loans to a human borrower still require the separate Source consent flow. + // The generic weekly expiry/selector path has no owner for the explicit + // PendingOfferAnswer runtime allocator observation. The special DispatchClubPlayerPendingOffers pending + // caller opts in below, where its typed hooks own that observation. + offer.transaction_supported = !(offer.loan && offer.buyer_manager >= 0); + offer.eligible = offer.affordable && offer.has_squad_room && offer.passes_foreign_limit; + ++view.offer_count; + } + return view; +} + +TransferOfferListView project_transfer_offer_list(const ModernState& g, int entry) { + return project_transfer_offer_list_impl(g, entry, false); +} + +namespace { + +void pending_notice(const ModernState& g, const PendingOfferHooks& hooks, int manager, + int raw, uint32_t address, const std::string& composed = {}) { + if (hooks.notice) hooks.notice(g, {manager, raw, address, + composed.empty() ? message_text(g, address) : composed}); +} + +// Only the DispatchClubPlayerPendingOffers adapter admits entries40..43; legacy entry bounds stay40. +struct PendingOwnerContext { + int manager = -1; + int team = -1; // AdvanceTurn reads the raw record, including retained records1..3. + bool native_takeover = false; +}; + +TransferOfferListView pending_view(const ModernState& g, int raw, int player, MinuteReport& report, + const PendingOwnerContext* owner) { + auto view = project_transfer_offer_list_impl(g, raw + 40, true); + if (owner && view.valid) { + // IncomingTransferScreen receives param8 directly from the offer owner. FindManagerForClub + // is only used for the buyer and later movement, not this seller context. + view.seller_manager = owner->manager; + if (g.memory.has(::bmh::layout::DeskActions_Unsupported_RuntimeField+uint32_t(owner->manager))) + view.seller_loan_count = g.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField+uint32_t(owner->manager)); + for (auto& offer : view.offers) if (offer.present) { + if (offer.loan) offer.loan_permitted = view.seller_loan_count >= 0 && view.seller_loan_count < 3; + if (pending_native_manager_of(g,offer.buyer,owner->native_takeover)==4) { + offer.buyer_manager=4; + const size_t rec=4*kRecord; + const auto i32=[&](size_t at) { + uint32_t n=0; + for(int i=0;i<4;++i)n|=uint32_t(g.manager_records.at(at+size_t(i)))<<(8*i); + return int32_t(n); + }; + offer.affordable=int64_t(i32(rec+0x314))+i32(rec+0x31c)>=offer.fee; + offer.eligible=offer.affordable && offer.has_squad_room && offer.passes_foreign_limit; + } + } + } + if (!view.valid || view.player != player || !view.offers[0].present || + view.seller_manager < 0 || view.offer_count != 1 || + g.memory.u16(kTransferList+uint32_t(raw+40)*kListEntry+4)!=0xffff || + g.memory.u16(kTransferList+uint32_t(raw+40)*kListEntry+6)!=0xffff) { + report.fail("DispatchClubPlayerPendingOffers: malformed special transfer entry (expected one actual bid)"); + return {}; + } + // DispatchClubPlayerPendingOffers is the only caller whose staged human-buyer settlement owns + // the observed allocator gate and payer notices for this loan route. + if (view.offers[0].loan && view.offers[0].buyer_manager >= 0) + view.offers[0].transaction_supported = true; + return view; +} + +void record_transfer_history_source(ModernState& g, int manager, int other_team, int player, + uint32_t fee, bool loan, bool buyer_direction = false) { + // PoolString is explicitly inert for parked owner4, even when Fail + // recognizes that owner and calls it. Only ordinary owners0..3 have history. + if(manager<0 || manager>=4)return; + // The manager's two30-entry transfer-history blocks, newest first. + auto rec = record(g, manager); + for (int i = 29; i > 0; --i) { + rec.set32(0x760 + size_t(i)*4, uint32_t(rec.i32(0x760 + size_t(i-1)*4))); + rec.set32(0x7d8 + size_t(i)*4, uint32_t(rec.i32(0x7d8 + size_t(i-1)*4))); + } + rec.set32(0x760, uint32_t(loan)*2 + g.date*4 + uint32_t(buyer_direction) + (fee/10000)*0x80000); + const uint32_t other_club = other_team == 0x0fff ? 0xffffu + : uint32_t(g.club_ids.at(size_t(other_team))); + rec.set32(0x7d8, uint32_t(g.player_name_offsets.at(size_t(player))) + other_club*0x10000); + if (rec.b(0x21d) < 25) ++rec.b(0x21d); +} + +enum class PendingSettleOutcome { + not_moved, + buyer_funds_refused, + buyer_allocator_blocked, + buyer_no_room, + moved, + unsupported +}; + +PendingSettleOutcome pending_settle_human_buyer(ModernState& g, int raw, int bid, + bool force, const PendingOfferHooks& hooks, WatcomRandom& rand, + MinuteReport& report, int seller, int buyer, uint32_t severance, + const PendingOwnerContext* owner) { + HumanBuyerSaleHooks shared; + switch (hooks.human_buyer_allocator_gate) { + case PendingOfferAllocatorGate::zero: shared.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: shared.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: shared.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + if (hooks.notice) shared.notice = [&](const GameState& base, const HumanBuyerSaleNotice& notice) { + const auto& state = static_cast(base); + if (hooks.notice) hooks.notice(state, {notice.manager, notice.raw_offer_slot, + notice.source_text_address, notice.original_message}); + }; + shared.after_paid_accounts = [&](GameState& base, const HumanBuyerSalePaid& paid) { + auto& state = static_cast(base); + auto& mem = state.memory; + // Void2 caller-only work remains between SettleHumanBuyerSale and Fail. + if (severance != 0) { + if (mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 1); + modern::book_money(state, paid.seller_manager, int32_t(severance), true, true); + if (state.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + } + if (!force && hooks.notice) + hooks.notice(state, {paid.buyer_manager, paid.raw_offer_slot, ::bmh::layout::PendingOffer_FormatError_ExecutableField2, + message_text(state, ::bmh::layout::PendingOffer_FormatError_ExecutableField2)}); + state.transfer_notice_suppressed = false; + if (mem.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2)) mem.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2, 0); + uint32_t mask = 0x80000000u | (1u << paid.seller_manager); + if (!(mem.has(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) && mem.u8(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) != 0)) mask = 0xffffffffu; + else mask |= 1u << paid.buyer_manager; + const uint32_t interested = interested_managers(state, paid.seller, paid.buyer); + if ((mask | interested) != 0x80000000u) { + const std::string message = message_text(state, ::bmh::layout::Month_SearchProfileNews_TextPointer) + state.player_name(paid.player) + + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer) + state.club_name(paid.seller) + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer2) + + format_amount(state, int32_t(paid.raw_fee)) + message_text(state, ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7) + + state.club_name(paid.buyer) + message_text(state, (paid.term & 0x80) ? ::bmh::layout::Weekly_ExecuteTransfer_TextPointer3 : ::bmh::layout::Weekly_ExecuteTransfer_TextPointer4); + post_composed(state, int64_t(mask | interested), message); + } + }; + + HumanBuyerSaleRequest request; + request.list_entry = raw + 40; + request.bid_slot = bid; + request.list_address = kTransferList + uint32_t(request.list_entry) * kListEntry; + request.source_pool_slot = transfer_list_slot() + size_t(request.list_entry); + request.expected_seller = seller; + request.expected_buyer = buyer; + request.expected_active_manager = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + request.raw_offer_slot = raw; + if(owner && owner->native_takeover) + request.source_pending_owner=SourcePendingOwner{owner->manager,owner->team}; + const auto settled = modern::settle_human_buyer_sale(g, request, shared, rand, report); + switch (settled.status) { + case HumanBuyerSaleStatus::funds_refused: + return PendingSettleOutcome::buyer_funds_refused; + case HumanBuyerSaleStatus::allocator_blocked: + if (g.memory.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField)) g.memory.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField, 1); + return PendingSettleOutcome::buyer_allocator_blocked; + case HumanBuyerSaleStatus::no_room: + if (g.memory.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField)) g.memory.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField, 1); + return PendingSettleOutcome::buyer_no_room; + case HumanBuyerSaleStatus::moved: + if (g.memory.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField)) g.memory.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField, 1); + return PendingSettleOutcome::moved; + case HumanBuyerSaleStatus::unsupported: + default: + return PendingSettleOutcome::unsupported; + } +} + +PendingSettleOutcome pending_settle(ModernState& g, int raw, int player, int bid, int clicked_player, + int clicked_slot, bool force, const PendingOfferHooks& hooks, + WatcomRandom& rand, MinuteReport& report, const PendingOwnerContext* owner) { + auto& mem = g.memory; + const uint32_t list = kTransferList + uint32_t(raw+40)*kListEntry; + const int seller = mem.u16(list+8)&0x7fff; + const int seller_manager = owner ? owner->manager : g.manager_of(seller); + const bool native_takeover = owner && owner->native_takeover; + const int movement_seller = pending_native_manager_of(g, seller, native_takeover); + const int buyer = int16_t(mem.u16(list+uint32_t(bid)*2)); + const int buyer_manager = pending_native_manager_of(g, buyer, native_takeover); + if (seller_manager < 0 || seller_manager >= 4 || buyer < 0 || buyer >= league_clubs()) { + report.fail("DispatchClubPlayerPendingOffers: invalid seller/buyer for Void2"); return PendingSettleOutcome::unsupported; + } + const uint8_t term = mem.u8(list+0x34+uint32_t(bid)); + const bool loan = term > 0x7f; + if (buyer_manager >= 0 && (buyer_manager >= (native_takeover?5:4) || buyer == seller || + (hooks.human_buyer_allocator_gate != PendingOfferAllocatorGate::zero && + hooks.human_buyer_allocator_gate != PendingOfferAllocatorGate::blocked))) { + report.fail("DispatchClubPlayerPendingOffers: human-buyer loan/same-club/unknown allocator route is unsupported"); + return PendingSettleOutcome::unsupported; + } + if (buyer_manager >= 0) { + const auto buyer_range = buyer >= 0 && buyer < league_clubs() ? squad_range(buyer) : SquadRange{}; + if (buyer_range.count != 24) { + report.fail("DispatchClubPlayerPendingOffers: human buyer uses unsupported non-24-slot squad layout"); + return PendingSettleOutcome::unsupported; + } + for (int k = 0; k < 200; ++k) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xfff) == player) { + report.fail("Fail: existing return-loan record (error30) is unsupported for human buyer"); + return PendingSettleOutcome::unsupported; + } + } + } + // Fail reports a full AI squad only after settlement accounting/news, + // including loans. Keep the legacy preflight's earlier room guard unchanged. + if (loan && !preflight_human_owner_loan(g,seller,transfer_list_slot()+size_t(raw+40),buyer,report,false,native_takeover)) + return PendingSettleOutcome::unsupported; + const auto range = squad_range(seller); + size_t owner_slot = range.first; + while (owner_slot < range.first+range.count && (g.squad_slots.at(owner_slot)&0xfff) != player) + ++owner_slot; + if (owner_slot == range.first+range.count) { + report.fail("DispatchClubPlayerPendingOffers: IncomingTransferScreen seller player missing (internal error0x1e)"); return PendingSettleOutcome::unsupported; + } + const size_t board = size_t(seller_manager)*kBoard+(owner_slot-range.first)*kBoardSlot; + if (board+kBoardSlot > g.tactics.size()) { + report.fail("DispatchClubPlayerPendingOffers: missing seller salary board"); return PendingSettleOutcome::unsupported; + } + uint32_t old_salary = 0; + for (int i=0;i<4;++i) old_salary |= uint32_t(g.tactics[board+0x50+size_t(i)])<<(8*i); + const uint32_t months = loan ? term&0x7f : g.tactics[board+0x0c]; + const uint32_t old_total = old_salary*months; + const uint32_t new_total = mem.u32(list+0x0c+uint32_t(bid)*4)*months; + // Void2 draws this W even if no salary decrease follows. + const uint32_t threshold = old_total*uint32_t(rand.range(90,100)); + uint32_t severance = 0; + if (new_total*100u < threshold) { + severance = std::max(((old_total-new_total)/1000)*1000,1000u); + PendingOfferQuestion question; + question.kind=PendingOfferQuestionKind::severance; + question.manager=seller_manager;question.raw_offer_slot=raw;question.offered_player=player; + question.clicked_player=clicked_player;question.clicked_source_slot=clicked_slot; + question.current_clicked_name=g.player_name(g.squad_slots.at(size_t(clicked_slot))&0xfff); + question.amount=severance;question.source_flags=0x305; + question.original_message=message_text(g,::bmh::layout::Weekly_PendingSettle_TextPointer)+format_amount(g,int32_t(severance))+"."; + if (!hooks.answer) { + report.fail("DispatchClubPlayerPendingOffers: missing manual severance answer"); return PendingSettleOutcome::unsupported; + } + const auto answer=hooks.answer(g,question); + if(answer==PendingOfferAnswer::unsupported) { + report.fail("DispatchClubPlayerPendingOffers: unsupported manual severance answer"); return PendingSettleOutcome::unsupported; + } + if(answer==PendingOfferAnswer::no) { + mem.set8(::bmh::layout::ActiveManager,uint8_t(seller_manager)); + pending_notice(g,hooks,seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField4); + return PendingSettleOutcome::not_moved; + } + } + const uint32_t fee=mem.u32(list+0x1c+uint32_t(bid)*4); + if (buyer_manager >= 0) + return pending_settle_human_buyer(g,raw,bid,force,hooks,rand,report,seller,buyer,severance,owner); + // SettleHumanBuyerSale: this scoped adapter has an AI buyer (no buyer debit/subsidy). + // BookMoney2(...,-fee,1), transfer ledger, then severance debit. + if(mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,1); + modern::book_money(g,seller_manager,-int32_t(fee),true,true); + if(g.level!=0 && mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,0); + auto rec=record(g,seller_manager); + rec.set32(0x330,uint32_t(rec.i32(0x330))-fee); + if(severance) { + if(mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,1); + modern::book_money(g,seller_manager,int32_t(severance),true,true); + if(g.level!=0 && mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,0); + } + if(!force)pending_notice(g,hooks,seller_manager,raw,::bmh::layout::PendingOffer_FormatError_ExecutableField2); // Source param10 suppresses forced-sale ACK + g.transfer_notice_suppressed=false; + if(mem.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2))mem.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2,0); + uint32_t mask=0x80000000u|(1u<=0) record_transfer_history_source(g,movement_seller,buyer,player,fee,loan); + move_player(g,seller,transfer_list_slot()+size_t(raw+40),buyer,list,bid,rand,report, + TransferAllocatorContext::unsupported,native_takeover); + if(mem.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField))mem.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField,1); + return report.unsupported ? PendingSettleOutcome::unsupported : PendingSettleOutcome::moved; +} + +PendingSettleOutcome pending_negotiate(ModernState& g, int raw, int player, bool force, int clicked_player, + int clicked_slot, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report, const PendingOwnerContext* owner) { + auto view=pending_view(g,raw,player,report,owner); + if(report.unsupported)return PendingSettleOutcome::unsupported; + if(force) return pending_settle(g,raw,player,0,clicked_player,clicked_slot,true,hooks,rand,report,owner); + if(!hooks.select_transfer) { + report.fail("DispatchClubPlayerPendingOffers: missing manual transfer-row chooser"); return PendingSettleOutcome::unsupported; + } + const uint32_t list=kTransferList+uint32_t(raw+40)*kListEntry; + const auto range=squad_range(view.seller); + size_t owner_slot=range.first; + while(owner_slot PlayerCardMarketValue -> 422f4, distinct from salary-JA's raw42307. + view.quoted_fee=((view.quoted_fee+(view.quoted_fee>>2))/10000)*10000; + view.quoted_monthly_salary=(view.quoted_monthly_salary/100)*100; + // OpenTransferEditor prepares its first empty offer row even in presentation mode. + g.memory.set32(list+0x0c+4,0);g.memory.set32(list+0x1c+4,0); + g.memory.set8(list+0x34+1,24); + offer_bases(g.memory,list,1,view.asking_fee,view.asking_monthly_salary); + const auto choice=hooks.select_transfer(g,view); + if(choice.kind==PendingOfferTransferChoiceKind::unsupported) { + report.fail("DispatchClubPlayerPendingOffers: unsupported manual transfer choice");return PendingSettleOutcome::unsupported; + } + if(choice.kind==PendingOfferTransferChoiceKind::decline) { + if(!g.transfer_notice_suppressed && + !(g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2) && g.memory.u8(::bmh::layout::DeskActions_EditorFail_RuntimeField2)!=0)) + pending_notice(g,hooks,view.seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField); + return PendingSettleOutcome::not_moved; + } + if(choice.raw_bid_slot!=0) { + report.fail("DispatchClubPlayerPendingOffers: invalid special-entry raw bid slot");return PendingSettleOutcome::unsupported; + } + if(view.offers[0].loan && !view.offers[0].loan_permitted) { + pending_notice(g,hooks,view.seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField2); + view.rejected_bid_index=0;view.notice_text_address=::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField2; + continue; + } + const uint32_t before=g.memory.u32(list+0x0c); + g.memory.set32(list+0x0c,(before*10u)>>3); + uint32_t fee_pct=0,salary_pct=0; + const bool native_takeover=owner && owner->native_takeover; + const SourcePendingOwner native_owner{owner?owner->manager:-1,owner?owner->team:-1}; + const bool human_buyer = pending_native_manager_of(g,view.offers[0].buyer,native_takeover)>=0; + const bool rated = human_buyer + ? evaluate_pending_human_bid(g,list,0,fee_pct,salary_pct,rand,report,native_takeover?&native_owner:nullptr) + : evaluate_bid(g,list,0,fee_pct,salary_pct,rand,report); + g.memory.set32(list+0x0c,before); + if(!rated||report.unsupported)return PendingSettleOutcome::unsupported; + if(salary_pct!=0) + return pending_settle(g,raw,player,0,clicked_player,clicked_slot,false,hooks,rand,report,owner); + pending_notice(g,hooks,view.seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField3); + g.memory.set16(list,0xffff); // param9==1: final rejection, no extra redraw. + return PendingSettleOutcome::not_moved; + } +} + +} // namespace + +HumanBuyerSaleResult settle_human_buyer_sale(ModernState& g, const HumanBuyerSaleRequest& request, + const HumanBuyerSaleHooks& hooks, WatcomRandom& rand, MinuteReport& report) { + HumanBuyerSaleResult result; + if (report.unsupported) return result; + auto& mem = g.memory; + const auto fail = [&](const char* why) { + report.fail(why); + result.status = HumanBuyerSaleStatus::unsupported; + return result; + }; + + // Validate the exact caller-owned source coordinates. Ordinary and pending + // offers share the transaction but never share or synthesize their indices. + if (request.list_entry < 0 || request.list_entry >= 44 || request.bid_slot < 0 || request.bid_slot >= 4 || + request.list_address != kTransferList + uint32_t(request.list_entry) * kListEntry || + request.source_pool_slot != transfer_list_slot() + size_t(request.list_entry) || + !mem.has(request.list_address + kListEntry - 1) || + request.source_pool_slot >= g.squad_slots.size()) + return fail("SettleHumanBuyerSale/Fail: invalid explicit source list/pool/bid coordinates"); + if (request.raw_offer_slot == -1) { + const bool return_entry = request.loan_return_entry && !request.poach && + request.list_entry >= 40 && request.list_entry < 44 && + mem.has(::bmh::layout::OfferSlots + uint32_t(request.list_entry - 40) * 4 + 3) && + mem.u32(::bmh::layout::OfferSlots + uint32_t(request.list_entry - 40) * 4) == + uint32_t(request.source_pool_slot < g.squad_slots.size() + ? (g.squad_slots[request.source_pool_slot] & 0x0fff) : 0x0fff) * 0x400u + + uint32_t(request.expected_active_manager); + if ((request.list_entry >= 40 && !request.poach && !return_entry) || + (request.loan_return_entry && !return_entry) || + (request.list_entry < 40 && (request.poach || request.loan_return_entry))) + return fail("SettleHumanBuyerSale/Fail: ordinary sale requires list entry 0..39"); + } else if (request.raw_offer_slot < 0 || request.raw_offer_slot >= 4 || + request.list_entry != 40 + request.raw_offer_slot || request.loan_return_entry) { + return fail("SettleHumanBuyerSale/Fail: pending raw slot does not identify its explicit list entry"); + } + const bool native_takeover=request.source_pending_owner.has_value(); + if(native_takeover && (request.raw_offer_slot<0 || request.bid_slot!=0 || request.day_step || request.poach || request.loan_return_entry || + !source_pending_owner_valid(g,*request.source_pending_owner,request.list_entry,request.source_pool_slot))) + return fail("SettleHumanBuyerSale/Fail: invalid DispatchClubPlayerPendingOffers native pending owner context"); + if (!request.day_step && (!mem.has(::bmh::layout::ActiveManager) || request.expected_active_manager < 0 || + (!native_takeover && size_t(request.expected_active_manager) >= g.manager_teams.size()) || + mem.u8(::bmh::layout::ActiveManager) != request.expected_active_manager)) + return fail("SettleHumanBuyerSale/Fail: active manager does not match caller context"); + if (hooks.allocator_gate != HumanBuyerSaleAllocatorGate::zero && + hooks.allocator_gate != HumanBuyerSaleAllocatorGate::blocked) + return fail("PendingOfferAnswer: human-buyer allocator gate was not observed by the runtime owner"); + if (!hooks.notice) + return fail("SettleHumanBuyerSale/Fail: Source notice presenter is unavailable"); + + const uint32_t list = request.list_address; + const int player = int(g.squad_slots.at(request.source_pool_slot) & 0x0fff); + const int seller = int(mem.u16(list + 8) & 0x7fff); + const int buyer = int16_t(mem.u16(list + uint32_t(request.bid_slot) * 2)); + const bool free_agent = seller == 0x0fff; + if (player == 0x0fff || size_t(player) >= g.players.size() || + seller != request.expected_seller || buyer != request.expected_buyer || + (!free_agent && (seller < 0 || seller >= league_clubs())) || + buyer < 0 || buyer >= league_clubs() || seller == buyer) + return fail("SettleHumanBuyerSale/Fail: source player/seller/buyer identity mismatch"); + // SettleHumanBuyerSale uses param8 for the seller's accounts; Fail separately + // resolves actual movement ownership through FindManagerForClub. + const int seller_manager=pending_native_manager_of(g,seller,native_takeover); + const int account_seller=native_takeover?request.source_pending_owner->manager:seller_manager; + const int buyer_manager=pending_native_manager_of(g,buyer,native_takeover); + const bool parked_buyer=native_takeover && buyer_manager==4; + if (buyer_manager < 0 || buyer_manager >= (native_takeover?5:4) || + (!parked_buyer && (size_t(buyer_manager)>=g.manager_teams.size() || g.manager_teams[size_t(buyer_manager)]!=buyer)) || + (free_agent && seller_manager >= 0) || + (seller_manager >= 0 && (seller_manager >= (native_takeover?5:4) || seller_manager == buyer_manager))) + return fail("SettleHumanBuyerSale/Fail: unsupported buyer/seller manager identity"); + if(native_takeover) { + const int expected=request.source_pending_owner->team==no_team() + ? int(g.manager_records[4*kRecord+0x290]) | int(g.manager_records[4*kRecord+0x291])<<8 + : request.source_pending_owner->team; + if(seller!=expected)return fail("SettleHumanBuyerSale/Fail: invalid native pending seller provenance"); + } + if (!request.day_step && request.expected_active_manager != buyer_manager && request.expected_active_manager != account_seller) + return fail("SettleHumanBuyerSale/Fail: active manager is neither the direct buyer nor pending seller context"); + + const uint8_t term = mem.u8(list + 0x34 + uint32_t(request.bid_slot)); + const bool loan = term > 0x7f; + if (loan && free_agent) + return fail("Fail/DayStepRest2: free-agent loan return destination is not represented"); + const auto buyer_range = squad_range(buyer); + if (buyer_range.count != 24) + return fail("PendingOfferAnswer: human buyer uses unsupported non-24-slot squad layout"); + if (!mem.has(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + 199 * 4 + 3)) + return fail("Fail: missing return-loan storage (error30/31 boundary)"); + int loan_slot = -1; + for (int k = 0; k < 200; ++k) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e == 0 && loan_slot < 0) loan_slot = k; + else if (e != 0 && int(e & 0x0fff) == player) + return fail("Fail: existing return-loan record (error30) is unsupported for human buyer"); + } + if (loan && loan_slot < 0) + return fail("Fail: return-loan ledger full (error36)"); + + size_t seller_board = 0; + if (free_agent) { + // ReleasePlayer's canonical 0FFF seller scans the entire free-player pool, + // not a fictitious seller squad. FFFF is not an alias for this seller. + if (g.squad_slots.size() < pool_end_slot()) + return fail("ReleasePlayer: free-agent pool is outside native squad storage"); + } else { + const auto seller_range = squad_range(seller); + if (seller_range.count == 0 || seller_range.first + seller_range.count > g.squad_slots.size()) + return fail("Fail: seller squad (error32) is outside native squad storage"); + size_t seller_slot = seller_range.first; + while (seller_slot < seller_range.first + seller_range.count && + (g.squad_slots.at(seller_slot) & 0x0fff) != player) ++seller_slot; + if (seller_slot == seller_range.first + seller_range.count || seller_slot >= g.squad_slots.size()) + return fail("Fail: seller does not own source player (error32)"); + if (seller_manager >= 0) + seller_board = size_t(seller_manager) * kBoard + (seller_slot - seller_range.first) * kBoardSlot; + } + if (seller_manager >= 0 && seller_board + kBoardSlot > g.tactics.size()) + return fail("Fail: seller board row (error32) is outside native tactics storage"); + if (buyer_range.first + buyer_range.count > g.squad_slots.size() || + size_t(buyer_manager) * kBoard + 24 * kBoardSlot > g.tactics.size()) + return fail("Fail: unsupported human buyer squad/board layout"); + + int owner_snapshot_slot = -1; + std::array owner_board_snapshot{}; + if (loan && seller_manager >= 0) { + if (seller_manager >= (native_takeover?5:4) || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager)) || + mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager)) >= 3 || + !mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b)) + return fail("Fail: human owner loan count/snapshot storage unavailable"); + for (int i = 0; i < 12; ++i) { + const uint16_t id = mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2); + if (id == uint16_t(player)) + return fail("Fail: duplicate human-owner loan snapshot"); + if (owner_snapshot_slot < 0 && id == 0x0fff) owner_snapshot_slot = i; + } + if (owner_snapshot_slot < 0) + return fail("Fail: human-owner loan snapshots full (error34)"); + std::copy_n(g.tactics.begin() + std::ptrdiff_t(seller_board), kBoardSlot, + owner_board_snapshot.begin()); + } + + const uint32_t fee = mem.u32(list + 0x1c + uint32_t(request.bid_slot) * 4); + const uint32_t salary = mem.u32(list + 0x0c + uint32_t(request.bid_slot) * 4); + if (hooks.before_accounts) hooks.before_accounts(g, request); + auto buyer_record = record(g, buyer_manager); + const uint8_t subsidy = buyer_record.b(0x170); + uint32_t adjusted_fee = fee; + const int position = int(g.players.at(size_t(player)).w364 & 3); + if (fee <= buyer_record.u32(0x314) && subsidy != 0 && (subsidy & 3) == position) { + int league = buyer_record.b(0x210); + if (league > 2) --league; + const uint32_t threshold = (((uint32_t(subsidy) >> 2) & 7u) * 50000u + 150000u) * + uint32_t(4 - league); + if (fee < threshold) { + const uint32_t discount = (((uint32_t(subsidy) >> 5) + 3u) * fee * 10u) / 100u; + const std::string message = message_text(g, ::bmh::layout::PendingOffer_ConstructionNoticeDialog_TextPointer) + + format_amount(g, int32_t(discount)) + message_text(g, ::bmh::layout::Weekly_Fail_TextPointer) + + format_amount(g, int32_t(fee)) + ")."; // EXE literal at a12ca, not a TEXTD pointer. + hooks.notice(g, {buyer_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::PendingOffer_ConstructionNoticeDialog_TextPointer, message}); + adjusted_fee = fee - discount; + } else { + hooks.notice(g, {buyer_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::PendingOffer_FormatError_ExecutableField3, message_text(g, ::bmh::layout::PendingOffer_FormatError_ExecutableField3)}); + } + // Both qualifying Source branches consume the subsidy even if payment fails. + record(g, buyer_manager).b(0x170) = 0; + } + + const uint8_t old_active = mem.u8(::bmh::layout::ActiveManager); + if (mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 1); + const bool buyer_paid = modern::book_money(g, buyer_manager, int32_t(adjusted_fee), false, true); + if (!buyer_paid) { + mem.set8(::bmh::layout::ActiveManager, uint8_t(buyer_manager)); + hooks.notice(g, {buyer_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::Advertising_FormatError_TextPointer18, message_text(g, ::bmh::layout::Advertising_FormatError_TextPointer18)}); + if (g.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + mem.set8(::bmh::layout::ActiveManager, old_active); + result.status = HumanBuyerSaleStatus::funds_refused; + result.player = player; result.seller = seller; result.buyer = buyer; + result.seller_manager = account_seller; result.buyer_manager = buyer_manager; + result.raw_fee = fee; result.adjusted_fee = adjusted_fee; + return result; + } + if (g.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + record(g, buyer_manager).set32(0x330, uint32_t(record(g, buyer_manager).i32(0x330)) + adjusted_fee); + if (account_seller >= 0) { + if (mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 1); + modern::book_money(g, account_seller, int32_t(0u - adjusted_fee), true, true); + if (g.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + auto seller_record = record(g, account_seller); + seller_record.set32(0x330, uint32_t(seller_record.i32(0x330)) - adjusted_fee); + } + + HumanBuyerSalePaid paid; + paid.list_entry = request.list_entry; paid.bid_slot = request.bid_slot; + paid.raw_offer_slot = request.raw_offer_slot; paid.player = player; + paid.seller = seller; paid.buyer = buyer; + paid.seller_manager = account_seller; paid.buyer_manager = buyer_manager; + paid.raw_fee = fee; paid.adjusted_fee = adjusted_fee; paid.salary = salary; paid.term = term; + if (hooks.after_paid_accounts) hooks.after_paid_accounts(g, paid); + + result.player = player; result.seller = seller; result.buyer = buyer; + result.seller_manager = account_seller; result.buyer_manager = buyer_manager; + result.raw_fee = fee; result.adjusted_fee = adjusted_fee; + if (hooks.allocator_gate == HumanBuyerSaleAllocatorGate::blocked) { + result.status = HumanBuyerSaleStatus::allocator_blocked; + return result; + } + + size_t buyer_slot = buyer_range.first; + while (buyer_slot < buyer_range.first + buyer_range.count && + g.squad_slots.at(buyer_slot) != 0x0fff) ++buyer_slot; + if (buyer_slot == buyer_range.first + buyer_range.count) { + const int current_manager = int(mem.u8(::bmh::layout::ActiveManager)); + hooks.notice(g, {current_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::PendingOffer_FormatError_ExecutableField, message_text(g, ::bmh::layout::PendingOffer_FormatError_ExecutableField)}); + result.status = HumanBuyerSaleStatus::no_room; + return result; + } + + const uint16_t source_word = g.squad_slots.at(request.source_pool_slot); + g.squad_slots.at(buyer_slot) = source_word; + const size_t buyer_board = size_t(buyer_manager) * kBoard + + (buyer_slot - buyer_range.first) * kBoardSlot; + modern::new_board_entry(g, buyer_manager, int(buyer_slot - buyer_range.first), int(buyer_slot), rand); + if (seller_manager >= 0) + std::copy_n(g.tactics.begin() + std::ptrdiff_t(seller_board), kBoardSlot, + g.tactics.begin() + std::ptrdiff_t(buyer_board)); + for (int b = 0; b < 4; ++b) + g.tactics.at(buyer_board + 0x50 + size_t(b)) = uint8_t(salary >> (b * 8)); + uint32_t reference_fee = 0, reference_salary = 0; + modern::market_value(g, int(request.source_pool_slot), 0, 100, reference_fee, reference_salary, + int(term & 0x7f), 0, rand); + if (reference_salary == 0) + return fail("Fail: zero reference salary is an unsupported divide-by-zero boundary"); + for (int b = 0; b < 7; ++b) + g.tactics.at(buyer_board + 0x12 + size_t(b)) = + mem.u8(list + 0x38 + uint32_t(request.bid_slot) * 7 + uint32_t(b)); + const uint32_t bonus = parked_buyer + ? modern::expected_bonus_parked_club_source(g,0xff,int(buyer_slot-buyer_range.first),player,true) + : modern::expected_bonus(g,buyer_manager,0xff,int(buyer_slot-buyer_range.first),player,true); + const uint32_t bonus_product = bonus * 0x50u; + const int32_t signed_bonus_product = int32_t(bonus_product); + const int32_t expected_bonus_component = signed_bonus_product / 100; + const uint32_t source_total = salary + uint32_t(expected_bonus_component); + const uint32_t source_numerator = source_total * 100u; + const uint32_t unsigned_ratio = source_numerator / reference_salary; + const int32_t signed_ratio = int32_t(unsigned_ratio); + const uint32_t ratio = uint32_t(std::clamp(signed_ratio, 0, 0xff)); + g.tactics.at(buyer_board + 0x0d) = uint8_t(ratio); + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[purchase mood player %d: salary %u bonus %u (x0.8 = %d) reference %u (term %d) -> ratio %u]\n", player, + salary, bonus, expected_bonus_component, reference_salary, int(term & 0x7f), ratio); + for (int b = 0; b < 4; ++b) + g.tactics.at(buyer_board + 0x54 + size_t(b)) = uint8_t(fee >> (b * 8)); + g.tactics.at(buyer_board + 0x0c) = loan ? uint8_t(0xff) : term; + + if (loan) { + if (seller_manager >= 0) { + const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(owner_snapshot_slot) * uint32_t(kBoardSlot); + for (size_t b = 0; b < kBoardSlot; ++b) + mem.set8(snapshot + uint32_t(b), owner_board_snapshot[b]); + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(owner_snapshot_slot) * 2, uint16_t(player)); + mem.set8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(owner_snapshot_slot), uint8_t(seller_manager)); + mem.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager), uint8_t(mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager)) + 1)); + } + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan_slot), uint8_t(term & 0x7f)); + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan_slot) * 4, + uint32_t(player + seller * 0x1000 + buyer * 0x400000)); + } + + if (seller_manager >= 0) + record_transfer_history_source(g, seller_manager, buyer, player, fee, loan, false); + record_transfer_history_source(g, buyer_manager, seller, player, fee, loan, true); + if (!remove_from_seller_impl(g,seller,player,report,native_takeover)) { + result.status = HumanBuyerSaleStatus::unsupported; + return result; + } + lineup_after_transfer_impl(g,seller,native_takeover); + lineup_after_transfer_impl(g,buyer,native_takeover); + result.status = HumanBuyerSaleStatus::moved; + return result; +} + +namespace { +PendingOfferResult process_pending_batch(ModernState& g, int clicked_player, int clicked_slot, + int clicked_manager, int physical_row, bool human_loan, int human_loan_index, + GameRandom& game, WatcomRandom& rand, const PendingOfferHooks& hooks, MinuteReport& report, + const PendingOwnerContext* owner = nullptr) { + PendingOfferResult result; + if(report.unsupported)return result; + if(!g.texts || !g.memory.has(::bmh::layout::ActiveManager) || !g.memory.has(::bmh::layout::OfferSlots+15) || + !g.memory.has(::bmh::layout::CareerSession_Invalid_RuntimeField2+3) || transfer_list_slot()+44>g.squad_slots.size()) { + report.fail("DispatchClubPlayerPendingOffers: missing native offer state or Original TEXTD");return result; + } + // Owned board storage, not a copied board or a remapped offered-player row. + const size_t board=human_loan ? 0 : size_t(clicked_manager)*kBoard+ + size_t(physical_row)*kBoardSlot; + const uint32_t loan_board=::bmh::layout::ClubInfo_FormatError_RuntimeField+uint32_t(std::max(human_loan_index,0))*kBoardSlot; + const auto board_byte=[&](size_t offset) { + return human_loan ? g.memory.u8(loan_board+uint32_t(offset)) : g.tactics.at(board+offset); + }; + const auto write_board=[&](size_t offset,uint8_t value) { + if(human_loan)g.memory.set8(loan_board+uint32_t(offset),value); + else g.tactics.at(board+offset)=value; + }; + bool sticky=false; + for(int raw=0;raw<4;++raw) { + const uint32_t at=::bmh::layout::OfferSlots+uint32_t(raw)*4; + const uint32_t offer=g.memory.u32(at); + const int active=g.memory.u8(::bmh::layout::ActiveManager); + if(offer==0xffffffffu || int(offer&31)!=active)continue; + if(active<0 || (owner ? active!=owner->manager : size_t(active)>=g.manager_teams.size())) { + report.fail("DispatchClubPlayerPendingOffers: invalid active owner");return result; + } + const int player=int((offer>>10)&0xfff); + const auto range=squad_range(owner ? owner->team : g.manager_teams[size_t(active)]); + size_t offered_slot=range.first; + while(offered_slotteam==no_team() + ? int(g.manager_records.at(4*kRecord+0x290)) | + (int(g.manager_records.at(4*kRecord+0x291))<<8) : owner->team; + if(seller<0 || seller>=league_clubs() || seller!=expected_seller || + (g.squad_slots.at(transfer_list_slot()+size_t(raw+40))&0x0fff)!=player) { + report.fail("DispatchClubPlayerPendingOffers: invalid special offer seller/pool provenance (PreMatchOffer requires a club seller)"); + return result; + } + } + if(offer&0x80000000u) { + PendingOfferQuestion question; + question.manager=active;question.raw_offer_slot=raw;question.offered_player=player; + question.clicked_player=clicked_player;question.clicked_source_slot=clicked_slot; + question.current_clicked_name=g.player_name(g.squad_slots.at(size_t(clicked_slot))&0xfff); + question.amount=g.memory.u32(list+0x0c); + question.original_message=question.current_clicked_name+message_text(g,::bmh::layout::Weekly_ProcessPendingBatch_TextPointer)+ + format_amount(g,int32_t(question.amount))+message_text(g,::bmh::layout::Weekly_ProcessPendingBatch_TextPointer2); + if(!hooks.answer) { + report.fail("DispatchClubPlayerPendingOffers: missing manual salary answer");return result; + } + const auto answer=hooks.answer(g,question); + if(answer==PendingOfferAnswer::unsupported) { + report.fail("DispatchClubPlayerPendingOffers: unsupported manual salary answer");return result; + } + if(answer==PendingOfferAnswer::yes) { + if(!(offer&0x20)) { + uint32_t fee=0,salary=0; + modern::market_value(g,clicked_slot,0,98,fee,salary,(board_byte(0x0c)+6)/12,0,rand); + if(salary==0) { + report.fail("DispatchClubPlayerPendingOffers: salary reference zero (Source division by zero)");return result; + } + for(int byte=0;byte<4;++byte)write_board(0x50+size_t(byte),uint8_t(question.amount>>(8*byte))); + write_board(0x0d,uint8_t(question.amount*100u/salary)); + } + ++result.salary_accepted;negotiate=false; + } else sticky=true; + } + if(negotiate) { + const auto outcome=pending_negotiate(g,raw,player,sticky,clicked_player,clicked_slot, + game,rand,hooks,report,owner); + switch(outcome) { + case PendingSettleOutcome::moved: ++result.transferred; break; + case PendingSettleOutcome::buyer_funds_refused: ++result.buyer_funds_refused; break; + case PendingSettleOutcome::buyer_allocator_blocked: ++result.buyer_allocator_blocked; break; + case PendingSettleOutcome::buyer_no_room: ++result.buyer_no_room; break; + case PendingSettleOutcome::unsupported: + return result; + case PendingSettleOutcome::not_moved: + break; + } + } + if(report.unsupported)return result; + } + // Cleanup applies to owned offers even when the offered player disappeared. + g.squad_slots.at(transfer_list_slot()+size_t(raw+40))=0x0fff; + g.memory.set32(at,0xffffffffu); + ++result.processed;result.forced_acceptance=sticky; + } + result.completed=true; + return result; +} +} // namespace + +PendingOfferResult process_player_card_pending_offers(ModernState& g, + const ClubPlayerDetailSelection& selection, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report) { + PendingOfferResult result; + if(report.unsupported)return result; + const auto clicked=modern::club_player_detail_context(g,selection); + if(clicked.national_mode!=0 || !clicked.board || clicked.active_offer<0) { + report.fail("DispatchClubPlayerPendingOffers: clicked card has no ordinary pending action/board");return result; + } + return process_pending_batch(g,selection.player_id,clicked.source_slot,clicked.source_manager, + selection.physical_row,clicked.human_loan,selection.human_loan_index,game,rand,hooks,report); +} + +PendingOfferResult process_natural_pending_offers_after_desk(ModernState& g, + const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report) { + PendingOfferResult result; + if (report.unsupported) return result; + const auto fail = [&](const char* why) -> PendingOfferResult { + report.fail(why); return result; + }; + if (request.runtime_mode != PendingOfferDeskRuntimeMode::normal_interactive) + return fail("AdvanceTurn: unsupported or unspecified transient desk runtime mode"); + constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount, kOrder = ::bmh::layout::NextDeskManager, kDeskPosition = ::bmh::layout::DeskPosition; + constexpr uint32_t kActiveManager = ::bmh::layout::ActiveManager, kOffers = ::bmh::layout::OfferSlots; + if (!g.memory.has(kManagerCount) || !g.memory.has(kOrder + 7) || + !g.memory.has(kDeskPosition) || !g.memory.has(kActiveManager) || + !g.memory.has(kOffers + 15) || transfer_list_slot() + 44 > g.squad_slots.size()) + return fail("AdvanceTurn: missing native manager/order/offer state"); + const int count = g.memory.u8(kManagerCount); + if (count < 1 || count > 4 || request.manager_count != count || + size_t(count) != g.manager_teams.size()) + return fail("AdvanceTurn: manager count does not match native manager loop"); + if (request.manager_position < 0 || request.manager_position >= count || + int(g.memory.u8(kDeskPosition)) != request.manager_position) + return fail("AdvanceTurn: desk position does not match native bdb77"); + // While a Bundestrainer has taken the national team over (CoachActive), SwapManagerSlots2 has + // cut ManagerCount to one but left the order NextDeskManager of the full game (OriginalManagerCount + // managers): PrepareEvent shuffles only a one-entry prefix, the desk is slot 0 + // (ActiveManager = DeskPosition while the count is one) and the offer owner afterwards is NextDeskManager[0], + // which may be a manager who sits this day out. + const bool takeover = g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0 && g.memory.has(::bmh::layout::OriginalManagerCount); + if (takeover && (count!=1 || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + g.manager_teams[0]!=no_team() || 5*kRecord>g.manager_records.size() || 5*kBoard>g.tactics.size())) + return fail("AdvanceTurn: invalid reduced-count national takeover record context"); + const int limit = takeover ? int(g.memory.u8(::bmh::layout::OriginalManagerCount)) : count; + std::array seen{}; + for (int i=0;i=limit || seen[size_t(manager)]) + return fail("AdvanceTurn: invalid native manager order permutation"); + seen[size_t(manager)]=true; + } + const int manager=g.memory.u16(kOrder+uint32_t(request.manager_position)*2); + if (manager<0 || manager>=limit || (manager=g.manager_teams.size())) + return fail("AdvanceTurn: invalid current ordered manager"); + if (takeover && size_t(manager)*kRecord+0x292>g.manager_records.size()) + return fail("AdvanceTurn: missing current ordered manager record"); + const size_t owner_record=size_t(manager)*kRecord+0x290; + const int native_team=takeover ? int(g.manager_records[owner_record]) | + (int(g.manager_records[owner_record+1])<<8) : g.manager_teams[size_t(manager)]; + const PendingOwnerContext owner{manager,native_team,takeover}; + // Records1..3 survive the count-one national takeover. AdvanceTurn reads + // these records directly even while their clubs have no current desk. + if ((takeover && manager=league_clubs())) || + (native_team==no_team() && (!takeover || manager!=0))) + return fail("AdvanceTurn: invalid native ordered owner team"); + const auto inactive_club_offer = [&](int raw, int player) { + // Deliberate OpenBMH improvement: AdvanceTurn reports error58 when a + // retained club offer is looked up in the temporary national squad. + // Qualify the old club in spare record4 and the offer's pool identity; + // preserve Source's cleanup, without presenting this context mismatch. + if (!takeover || count!=1 || manager!=0 || + g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + 4*kRecord+0x292>g.manager_records.size() || + player<0 || size_t(player)>=g.players.size() || + (g.squad_slots.at(transfer_list_slot()+size_t(raw+40))&0x0fff)!=player) + return false; + const auto record_team = [&](size_t base) { + return int(g.manager_records[base+0x290]) | + (int(g.manager_records[base+0x291])<<8); + }; + if (record_team(0)!=no_team()) return false; + const int club=record_team(4*kRecord); + if (club<0 || club>=league_clubs()) return false; + const auto squad=squad_range(club); + if (squad.first+squad.count>g.squad_slots.size()) return false; + for (size_t i=squad.first;i=league_clubs() && !national_owner)) + return fail("AdvanceTurn: national or unknown owner is unsupported for normal-club offers"); + // AdvanceTurn scans raw offer words until the first owned player resolves in + // an ordinary squad. A missing earlier player requires PresentLoanReturn's error + // presentation; later words belong to DispatchClubPlayerPendingOffers's own batch scan. + const auto range=squad_range(team); + if (range.first+range.count>g.squad_slots.size()) + return fail("AdvanceTurn: truncated ordinary owner squad"); + const int player=int((offer>>10)&0xfff); + size_t slot=range.first; + while(slot=0) { + const auto range=squad_range(native_team); + const int physical_row=anchor_slot-int(range.first); + result=process_pending_batch(g,anchor_player,anchor_slot,manager,physical_row,false,-1, + game,rand,hooks,report,takeover?&owner:nullptr); + if(report.unsupported || !result.completed)return result; + } else { + result.completed=true; // Source still reaches the end-of-loop cleanup. + } + if(request.manager_position==count-1) { + for(int raw=0;raw<4;++raw) { + g.squad_slots.at(transfer_list_slot()+size_t(raw+40))=0x0fff; + g.memory.set32(kOffers+uint32_t(raw)*4,0xffffffffu); + } + g.memory.set8(kDeskPosition,uint8_t(count)); + } + return result; +} + +PendingOfferResult process_national_nomination_pending_after_desk(ModernState& g, + const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report) { + PendingOfferResult result; + if (report.unsupported) return result; + const auto fail = [&](const char* why) -> PendingOfferResult { + report.fail(why); + return result; + }; + if (request.runtime_mode != PendingOfferDeskRuntimeMode::normal_interactive) + return fail("AdvanceTurn: unsupported or unspecified national desk runtime mode"); + + constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar, kCompetition = ::bmh::layout::SavedCompetition; + constexpr uint32_t kCoachActive = ::bmh::layout::CoachActive, kOriginalCount = ::bmh::layout::OriginalManagerCount; + constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount, kOrder = ::bmh::layout::NextDeskManager; + constexpr uint32_t kPosition = ::bmh::layout::DeskPosition, kActive = ::bmh::layout::ActiveManager, kOffers = ::bmh::layout::OfferSlots; + if (!g.memory.has(kCalendar + uint32_t(g.season_day()) * 2 + 1) || + !g.memory.has(kCompetition + 3) || !g.memory.has(kCoachActive) || + !g.memory.has(kOriginalCount) || !g.memory.has(kManagerCount) || + !g.memory.has(kOrder + 1) || !g.memory.has(kPosition) || !g.memory.has(kActive) || + !g.memory.has(kOffers + 15) || transfer_list_slot() + 44 > g.squad_slots.size()) + return fail("AdvanceTurn: missing native national desk state"); + + const uint16_t calendar_entry = g.memory.u16(kCalendar + uint32_t(g.season_day()) * 2); + const int original_count = g.memory.u8(kOriginalCount); + const int restored_owner = g.memory.u16(kOrder); + if (request.manager_count != 1 || request.manager_position != 0 || + g.memory.u8(kManagerCount) != 1 || g.manager_teams.size() != 1 || + g.manager_teams[0] != no_team() || g.memory.u8(kCoachActive) == 0 || + g.memory.u32(kCompetition) != 0 || calendar_entry != 0x4006 || + modern::day_competitions(g, calendar_entry) != 0x800000 || + original_count < 1 || original_count > 4 || restored_owner >= original_count || + g.memory.u8(kPosition) != 0 || g.memory.u8(kActive) != 0) + return fail("AdvanceTurn: national nomination desk does not match the saved Source context"); + + // Nomination uses the same post-return AdvanceTurn/DispatchClubPlayerPendingOffers sequence. Its + // calendar/competition identity is checked above before the shared scan can + // claim ActiveManager, invoke a presenter or consume either generator. + return modern::process_natural_pending_offers_after_desk(g,request,game,rand,hooks,report); +} + +bool accept_transfer_bid_immediately(ModernState& g, int entry, int bid, WatcomRandom& rand, + MinuteReport& report, TransferAllocatorContext allocator) { + if (entry < 0 || entry >= 40 || bid < 0 || bid >= 4) return false; + const uint32_t list = kTransferList + uint32_t(entry) * kListEntry; + if ((g.squad_slots.at(transfer_list_slot() + size_t(entry)) & 0xfff) == 0xfff || + g.memory.u16(list + uint32_t(bid) * 2) == 0xffff) return false; + execute_transfer(g, entry, list, bid, rand, report, allocator); + if (report.unsupported) return false; + for (int b = 0; b < 4; ++b) g.memory.set16(list + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(transfer_list_slot() + size_t(entry)) = 0x0fff; + return true; +} + +void transfer_list_countdown(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, bool all, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + for (int k = 0; k < 40; k++) { + const int player = g.squad_slots.at(transfer_list_slot() + size_t(k)) & 0xFFF; + if (player == 0xFFF) continue; + const uint32_t e = kTransferList + uint32_t(k) * kListEntry; + const uint8_t left = mem.u8(e + 0x56); + if (left == 0 || left > 9) { + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(transfer_list_slot() + size_t(k)) = 0x0FFF; + continue; + } + mem.set8(e + 0x56, uint8_t(left - 1)); + const int seller = mem.u16(e + 8) & 0x7FFF; // club of the player (0xFFF: none) + if (all) { + mem.set8(e + 0x56, 0); // TransferListCountdown(1) at the season end: every list is settled now + } else { + if (left - 1 == 1) { + // TransferListCountdown's one-week notice is a system modal (SystemIdentity(4)) + // only when a human seller or any human bidder participates. + // It observes the countdown and raw offer rows; it consumes no RNG + // and cannot change the later expiry decision. + const auto human_participant = [&](int club) { + // FindManagerForClub also recognizes the coach's temporarily saved + // club as owner 4 while manager 0 runs the national team. + return g.manager_of(club) >= 0 || (!g.manager_teams.empty() && + g.manager_teams[0] == no_team() && mem.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField) && + int(mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)) == club); + }; + bool human_involved = human_participant(seller); + for (int bid = 0; bid < 4 && !human_involved; ++bid) { + const int buyer = int16_t(mem.u16(e + uint32_t(bid) * 2)); + if (buyer != -1) human_involved = human_participant(buyer); + } + if (human_involved && g.transfer_decision_observer) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::last_week; + event.offers = modern::project_transfer_offer_list(g, k); + event.viewer_manager = -1; // Source SystemIdentity(4), system identity + event.result_text_address = ::bmh::layout::PendingOffer_TransferLastWeekDialog_ExecutableField; + g.transfer_decision_observer(event); + } + continue; + } + if (left - 1 != 0) continue; + } + if (int16_t(mem.u16(e)) == -1) { + // no bid at all: the player leaves the list, a human seller is told + if (const int m = g.manager_of(seller); m >= 0) + post_composed(g, m, message_text(g, ::bmh::layout::Weekly_TransferListCountdown_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_TransferListCountdown_TextPointer2)); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(transfer_list_slot() + size_t(k)) = 0x0FFF; + continue; + } + if (!decide_bids(g, k, game, rand, report, allocator)) return; + } +} + +void weekly_statistics(ModernState& g, int manager) { + Record rec = record(g, manager); + uint8_t week = rec.b(0x285); + auto shift = [&](size_t to, size_t from, size_t n) { + // Int16T: memmove from -> to + std::vector tmp(g.manager_records.begin() + rec.base + from, g.manager_records.begin() + rec.base + from + n); + std::copy(tmp.begin(), tmp.end(), g.manager_records.begin() + rec.base + to); + }; + if (week < 0x34) { + rec.b(0x285) = uint8_t(week + 1); + } else { + shift(0x3d8, 0x3dc, 0xcc); + shift(0x17a, 0x17b, 0x33); + shift(0x648, 0x64c, 0xcc); + shift(0x4a8, 0x4ac, 0xcc); + shift(0x578, 0x57c, 0xcc); + week = 0x33; + } + // HighscoreScore(0x1e, 0, 0xff): account, deposits, shares and bonds + int32_t assets = rec.i32(0x318); + for (int k = 0; k < 6; k++) + assets += int32_t(g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + uint32_t(k) * 0x1c) * + g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c)); + for (int k = 0; k < 12; k++) + assets += int32_t(uint32_t(g.stocks.at(size_t(k) * 0x5c + 0x50 + size_t(manager) * 2) | g.stocks.at(size_t(k) * 0x5c + 0x51 + size_t(manager) * 2) << 8) * + uint32_t(g.stocks.at(size_t(k) * 0x5c + 0x4e) | g.stocks.at(size_t(k) * 0x5c + 0x4f) << 8)); // shares (block StockExchange) + for (int b = 0; b < 5; b++) assets -= int32_t(g.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(manager) * 0x78 + uint32_t(b) * 0x18)); // credits + rec.set32(0x3d8 + size_t(week) * 4, uint32_t(assets)); + int second = 0; + rec.b(0x17a + week) = uint8_t(modern::facility_rating(g, manager, &second) * 2); + int value = 0; // BMHExeXa + for (int i = 0; i < 0xe; i++) value += kFacilityValue[i]; + for (int i = 0xe; i < 0x16; i++) value += (rec.b(0x2e + size_t(i)) & 7) * kFacilityValue[i]; + rec.set32(0x648 + size_t(week) * 4, uint32_t(value)); + int32_t sum = 0; + for (int i = 0; i < 0x11; i++) sum += rec.i32(0xa34 + size_t(i) * 0xc); + rec.set32(0x4a8 + size_t(week) * 4, uint32_t(sum)); + rec.set32(0x578 + size_t(week) * 4, uint32_t(rec.i32(0x314))); +} + +void weekly_processing(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator) { + const int managers = int(g.manager_teams.size()); + // (BMH_WEEKLY: the draw counts after each step, for comparing with a recording) + auto tr = [&](const char* what) { + if (std::getenv("BMH_WEEKLY")) std::printf(" [weekly %s: game %llu, Watcom %llu]\n", what, (unsigned long long)game.calls(), (unsigned long long)rand.calls()); + }; + tr("start"); + for (int m = 0; m < managers && !report.unsupported; m++) { + modern::manager_offers(g, m, rand, report); + tr("offers"); + if (report.unsupported) return; + modern::facility_ageing(g, m, game, rand, report); + tr("ageing"); + modern::facility_damage(g, m, game, rand); + tr("damage"); + if (g.memory.u8(::bmh::layout::Savestate_Layout_ExecutableField) % 3 == 0) modern::advertising_offers(g, m, rand, report); + tr("advertising"); + } + modern::transfer_list_countdown(g, game, rand, report, false, allocator); + tr("list countdown"); + if (report.unsupported) return; + // new bids for listed players + for (int k = 0; k < 40; k++) { + if (rand.range(0, 1) != 0) continue; + const uint32_t e = kTransferList + uint32_t(k) * kListEntry; + const size_t slot = transfer_list_slot() + size_t(k); + if (g.squad_slots.at(slot) == 0x0FFF || int16_t(g.memory.u16(e + 6)) != -1) continue; + if (rand.range(0, 1) == 0) continue; + do { + modern::transfer_bid(g, int(slot), e, false, -1, game, rand, report); + if (report.unsupported) return; + } while (rand.range(0, 2) == 0); + } + tr("bids"); + // every player: injuries in training, players out coming back + const bool quiet = g.memory.u8(::bmh::layout::GameMode) == 1; + for (size_t slot = 0; slot < transfer_list_slot(); slot++) { + const int player = g.squad_slots.at(slot) & 0x0FFF; + if (player == 0x0FFF) continue; + Player& p = g.players.at(size_t(player)); + const uint32_t out = p.w35c >> 27; + const uint32_t w364 = p.w364; + int injury = int((w364 >> 16) & 0x1F); + if (!quiet && game.range(0, 0xb4 - g.level * 2) == 0 && injury == 0 && out == 0) { + if (slot >= 0x870 && rand.range(0, 1) == 0) continue; + int type = rand.range(0, 0x1e); + const int team = modern::slot_team(int(slot)); + const int manager = g.manager_of(team); + type = injure_player(g, int(slot), type, false, manager, rand); // (unless MatchEventsDisabled, off) + if (manager >= 0) { + // "Ihr Spieler X faellt ... aus. Der Grund: ." + post_composed(g, manager, message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer2) + g.player_name(player) + + message_text(g, type < 6 ? ::bmh::layout::Weekly_WeeklyProcessing_TextPointer3 : ::bmh::layout::Weekly_WeeklyProcessing_TextPointer4) + message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer5) + + message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer + uint32_t(type) * 4) + "."); + } + continue; + } + if (out == 0 || out == 0x1F) continue; + if (injury > 0x18 && rand.range(0, 0x25) == 0) { + // the career is over + p.w35c = (p.w35c & 0x07FFFFFFu) | 0xF8000000u; + p.w364 |= 0x1Fu << 16; + if (const int m = g.manager_of(modern::slot_team(int(slot))); m >= 0) + post_composed(g, m, message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer2) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer6) + "."); + continue; + } + const bool last = injury == 1; + const int team = modern::slot_team(int(slot)); + const int manager = g.manager_of(team); + int odds = 4; + if (manager >= 0) odds = 6 - record(g, manager).i16(0x8ae) / 0x113; + if (injury != 0 && injury != 0x1F) { + if (injury < 4 && rand.range(0, int16_t(odds)) == 0) injury = 1; + p.w364 = (w364 & 0xFFE0FFFFu) | uint32_t(injury - 1) << 16; + } + if (last || (rand.range(0, int16_t(odds)) == 0 && injury == 0)) { + p.w35c &= 0x07FFFFFFu; + // Int2(team, 100); human teams: the assistant's line-up (option byte 0) + try { + auto_lineup(g, team, 100); + } catch (const std::exception& ex) { + report.fail(std::string("line-up after an injury: ") + ex.what()); + return; + } + } + } + tr("injuries and line-ups"); + // per human manager + for (int m = 0; m < managers; m++) { + Record rec = record(g, m); + const int debt = rec.b(0x174); + if (debt != 0) modern::book_money(g, m, -debt * 1000, true); + const SquadRange range = squad_range(int16_t(rec.u16(0x290))); + if (rec.b(0x287) != 0 && --rec.b(0x287) == 0) { + // the bill of the training camp + int16_t mood = 0; + for (int i = 0; i < 10; i++) mood = int16_t(mood + (g.manager_ratings.at(size_t(m) * 0x3c + size_t(i)) - 100)); + mood = int16_t(mood / 10 + 0x46); + const int a = rand.range(0, 8); + const int b = rand.range(0, 8); + mood = int16_t(std::clamp(int(int16_t(mood + a - b)), 0x14, 0xb4)); + int32_t tmp = mood; + for (int i = 10; i < 0xe; i++) + if (rec.b(size_t(i)) != 0) tmp += rand.range(5, 0xc); + const uint32_t bill = uint32_t(int16_t(tmp) * rec.i32(0x850)) / 100; + modern::book_money(g, m, -int32_t(bill), true); + rec.set32(0x850, 0); + } + for (int s = 0; s < 24; s++) { + const size_t at = size_t(m) * kBoard + size_t(s) * kBoardSlot; + if (g.squad_slots.at(range.first + size_t(s)) == 0x0FFF) continue; + if ((g.tactics.at(at + 0x4f) & 0x80) && rand.range(0, 6) == 0) g.tactics.at(at + 0x4f) &= 0x7F; + if (g.tactics.at(at + 0xc) == 2) g.tactics.at(at + 0xb) &= 0x3F; + // SalaryInjuredPlayerOnBoardPaidOn: the salary of an injured player on the board is paid on + const int player = g.squad_slots.at(range.first + size_t(s)) & 0x0FFF; + if ((g.players.at(size_t(player)).w35c >> 27) != 0 && g.tactics.at(at + 0x43) != 0) { + const int32_t base = int32_t(g.tactics.at(at + 0x50) | g.tactics.at(at + 0x51) << 8 | + g.tactics.at(at + 0x52) << 16 | uint32_t(g.tactics.at(at + 0x53)) << 24); + const uint32_t pay = uint32_t(base * int32_t(((int8_t(g.tactics.at(at + 0x43)) >> 6) & 3) * 0x32 + 0x32)) / 100; + modern::book_money(g, m, -int32_t(pay), true); + } + const uint8_t mood = g.tactics.at(at + 0xc); + if (mood % 0xc <= 7 && !(g.tactics.at(at + 0xb) & 0x20) && mood % 0xc != 0 && mood <= 0xf && + !(g.tactics.at(at + 0x4f) & 0x80) && !quiet) { + const int16_t rating = int16_t(rec.i16(0x8aa) + (rec.i16(0x8ac) >> 2)); + if (rand.range(0, 500 - (rating - 0x2a8) / 2) == 0) { + // InstallDefaultHooks(slot | 0x40): the player asks to talk about his contract. + // Before the contracts screen opens he names the term he wants, + // WatcomRandom(years left, 4), one more if that is no change (below 4), + // and the request is shown (SystemIdentity). The negotiation itself is UI: + // ported is a manager who leaves the screen without an offer, which + // changes nothing else. + const int years = mood / 0xc; + int wanted = rand.range(years, 4); + if (wanted == years && wanted < 4) wanted++; + (void)wanted; + } + } + } + modern::weekly_statistics(g, m); + } +} + +} // namespace bmh::modern + +namespace bmh::modern { + +bool pre_match_offer(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + if (mem.u32(::bmh::layout::CompetitionSelection) == 2 || mem.u8(::bmh::layout::GameMode) == 1) return false; + Record rec = record(g, manager); + const int chance = rand.range(0, 0x46 - rec.i16(0x8aa) / 0x32); + if (std::getenv("BMH_TRACE_OFFER")) + std::printf(" [pre-match offer, manager %d: W(0, %d) = %d, slots %08x %08x %08x %08x]\n", manager, + 0x46 - rec.i16(0x8aa) / 0x32, chance, mem.u32(::bmh::layout::OfferSlots), mem.u32(::bmh::layout::Weekly_PreMatchOffer_RuntimeField), mem.u32(::bmh::layout::Weekly_PreMatchOffer_RuntimeField2), mem.u32(::bmh::layout::Weekly_PreMatchOffer_RuntimeField3)); + if (chance != 0) return false; // (unless WeeklyRuntimeField8) + const int team = int16_t(rec.u16(0x290)); + if (team == no_team()) return false; + // RowWhose: a free offer slot k (OfferSlots, 4 entries of -1 when free); the + // offer uses the special transfer list entry 40 + k + int k = 0; + while (k < 4 && mem.u32(::bmh::layout::OfferSlots + uint32_t(k) * 4) != 0xFFFFFFFFu) k++; + if (k == 4) return false; + const uint32_t e = kTransferList + uint32_t(0x28 + k) * kListEntry; + const SquadRange range = squad_range(team); + // a random fit player of the squad who is not bought for later (up to 100 draws hit an + // empty slot; after that the empty slot is taken, as in the original) + int slot = 0, player = 0, empty = 0; + for (;;) { + slot = rand.range(int(range.first), int(range.first + range.count) - 1); + const uint16_t v = g.squad_slots.at(size_t(slot)); + if (v == 0x0FFF && empty++ < 100) continue; + // Deliberate deviation: after 100 empty draws the original goes on with the empty + // slot and reads "player 0xFFF" beyond its player table. That happens only with a + // squad that is nearly empty (a club whose contracts all ran out); there is no + // player to make an offer for, so no offer comes (the draws so far stay as they were). + if (v == 0x0FFF) return false; + player = v & 0x0FFF; + if ((g.players.at(size_t(player)).w35c >> 27) != 0) continue; + bool bought = false; + for (int b = 0; b < 200 && !bought; b++) { + const uint32_t x = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(b) * 4); + bought = x != 0 && int(x & 0xFFF) == player; + } + if (!bought) break; + } + // Range2(slot, 0, W(90, 130), 100, 1, k): the list entry of the offer - the club, + // no bids, asking/demand percentages, market value and salary, the player in pool slot + // 0x28 + k + const int percent = rand.range(0x5a, 0x82); + mem.set16(e + 8, uint16_t(modern::slot_team(slot))); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF); + mem.set8(e + 0x54, uint8_t(percent)); + mem.set8(e + 0x55, 100); + uint32_t fee = 0, salary = 0; + modern::market_value(g, slot, 0, percent, fee, salary, 1, 0, rand); + mem.set32(e + 0x2c, fee); + mem.set32(e + 0x30, salary); + g.squad_slots.at(transfer_list_slot() + 0x28 + size_t(k)) = uint16_t(player); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF); + // half of the offers are about the salary only (a club tries to lure him away) + const bool lure = rand.range(0, 1) != 0; + if (lure) mem.set16(e + 8, 0xffe); + const int board_slot = slot - int(range.first); + const size_t board = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot; + const uint32_t saved_mailbox_recipient_mask = mem.has(::bmh::layout::MailboxRecipientMask) ? mem.u32(::bmh::layout::MailboxRecipientMask) : 0; // (restored below) + modern::transfer_bid(g, slot, e, true, g.tactics.at(board + 0xc) / 0xc + 1, game, rand, report); + if (report.unsupported || mem.u16(e) == 0xFFFF) return false; + const int bidder = mem.u16(e); + std::string text; + bool warned = false; + if (lure) { + // what he earns now: the salary on the board plus the bonus he can expect + // (ContractOffer with the fitness correction) + const uint32_t earns = modern::expected_bonus(g, manager, 0xff, board_slot, player, true) + + uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16 | uint32_t(g.tactics.at(board + 0x53)) << 24); + const uint32_t r = uint32_t(rand.range(0x62, 0x78)); + if (r * earns / 100 < mem.u32(e + 0xc)) { + warned = true; + // "VORSICHT! bietet ein Gehalt von X EU. (momentan Y EU). Abloesesumme: Z EU." + text = message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer) + g.club_name(bidder) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer2) + + g.player_name(g.squad_slots.at(size_t(slot)) & 0xFFF) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer3) + + format_amount(g, int32_t(mem.u32(e + 0xc))) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer4) + + format_amount(g, int32_t(uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16 | + uint32_t(g.tactics.at(board + 0x53)) << 24))) + + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer5) + format_amount(g, int32_t(mem.u32(e + 0x1c))) + "."; // (WeeklyRuntimeField9) + } + } + if (!warned) { + // (ClubName2 with 0x4000 empties the buffer: the text WeeklyRuntimeField10 is lost) + const std::string verb = message_text(g, mem.u8(e + 0x34) > 0x7f ? ::bmh::layout::Weekly_PreMatchOffer_TextPointer8 : ::bmh::layout::Weekly_PreMatchOffer_TextPointer9); + const std::string amount = format_amount(g, int32_t(mem.u32(e + 0x1c))); + text = g.club_name(bidder) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer6) + g.player_name(g.squad_slots.at(size_t(slot)) & 0xFFF) + + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer7) + + // German: " KAUFEN" (with WeeklyRuntimeField11 " "); the English MessageText puts + // the verb first: "BUY him for " + (kEnglishCompetitions ? verb + amount : amount + " " + verb) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer10); + } + // SystemIdentity shows it, PostMessage posts it + post_composed(g, manager, text); + if (mem.has(::bmh::layout::MailboxRecipientMask)) mem.set32(::bmh::layout::MailboxRecipientMask, saved_mailbox_recipient_mask); + mem.set16(e + 8, uint16_t(team | 0x8000)); + mem.set32(::bmh::layout::OfferSlots + uint32_t(k) * 4, uint32_t(player) * 0x400 + uint32_t(manager) | (warned ? 0x80000000u : 0)); + return true; +} + +} // namespace bmh::modern diff --git a/src/modern/game/weekly.hpp b/src/modern/game/weekly.hpp new file mode 100644 index 0000000..f22c53b --- /dev/null +++ b/src/modern/game/weekly.hpp @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/weekly.hpp" +// OpenBMH deviates from the original: uses the supported weekly processing and transfer rule profile. +// The weekly processing (DayStepRest3, BMH.exe V2.24 + supported rule profile patch). +// +// DayStepRest runs it on the day after a training day when that day has weekday code 3 +// (in games with the full economy, CompetitionSelection bit 0). In order: +// 1. per human manager: offers and incidents (Bool), the ageing of the club's +// facilities (FacilityDamage) and random damage to them (SeasonTicketCompensation), each followed +// by the season ticket compensation (Void3); every third week new advertising +// offers (TransferListCountdown2) +// 2. the transfer list (TransferListCountdown(0)): the days left of every listed player count +// down; at 0 the highest-rated eligible bid wins unless a human-seller selector is set +// 3. new bids for listed players (TransferBid) +// 4. every player in a squad: injuries in training, players out (w35c bits 27-31) come +// back or retire +// 5. per human manager: debts, the training camp bill, player bonuses, the weekly +// statistics (FacilityRating) +// Messages to the managers (PostMessage / SystemIdentity) are not produced; dialogs that +// wait for a decision of the player are reported as unsupported. + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "modern/game/modern_state.hpp" +#include "game/transfer_allocator.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/pending_offer.hpp" +#include "game/transfer_bid.hpp" +#include "game/transfer_offer_view.hpp" + +#include +#include +#include + +namespace bmh::modern { + +// Projects the current live rows without mutation or RNG. The selector caller +// performs the Source-ranked selection and ProjectTransferOfferList post-selection check. +TransferOfferListView project_transfer_offer_list(const ModernState& g, int list_entry); + +void weekly_processing(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +// The single steps, public for tests. +void manager_offers(ModernState& g, int manager, WatcomRandom& rand, MinuteReport& report); // Bool +void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report); // FacilityDamage +void facility_damage(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand); // SeasonTicketCompensation +void season_ticket_compensation(ModernState& g, int manager); // Void3 +// Source-visible compensation path: the notice receives the state after the +// usable-capacity calculation, but before the forced/statistical money booking. +void season_ticket_compensation_source(ModernState& g, int manager, + const SeasonTicketCompensationNoticeHook& notice = {}); +void advertising_offers(ModernState& g, int manager, WatcomRandom& rand, MinuteReport& report); // TransferListCountdown2 +// TransferListCountdown(all): the days left of every listed player count down; at 0 the best bid wins +// (with `all`, at the season end, every list is settled at once) +void transfer_list_countdown(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, bool all = false, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); +// TransferBid(slot, list entry, 0, -1): a new bid of some club for the player in the +// absolute squad slot (a listed player), or with list_entry 0 a move of the player to a +// club that wants him. +void transfer_bid(ModernState& g, int slot, uint32_t list_entry, bool high, int months, GameRandom& game, + WatcomRandom& rand, MinuteReport& report); +void weekly_statistics(ModernState& g, int manager); // FacilityRating + +// FacilityRating2(manager, with_rand, &second): rating of a human club's stadium facilities +// (about 24-100). *second receives the covered share of the stands in percent. With `rand` +// (the attendance calculation) every stand under construction costs 10-12 % of the +// facility sum, drawn per stand. +int facility_rating(ModernState& g, int manager, int* second, WatcomRandom* rand = nullptr); + +// Squad helpers shared with the month change (month.cpp): +// Nationality: nationality of a player (w368 bits 27-31, +32 with the flag in *PlayerBonuses). +int nationality(const ModernState& g, int player); +// SquadCount(team, flags): players of a club (bit 1: the injured too; bit 0: plus the +// players bought for later, table Career_RemoveJoinLoans_RuntimeField). +int squad_count(const ModernState& g, int team, int flags); +// SlotTeam: club of an absolute squad slot, -1 for the transfer pool. +int slot_team(int slot); +// Int2(team, 100) after a transfer (only clubs with a squad). +void lineup_after_transfer(ModernState& g, int team); +// ReleasePlayer(seller, player): the player leaves the club (0xFFF: the pool). +bool remove_from_seller(ModernState& g, int seller, int player, MinuteReport& report); +// Finalize a high-confidence manager offer immediately after the seller/player accepts it. +bool accept_transfer_bid_immediately(ModernState& g, int list_entry, int bid, WatcomRandom& rand, + MinuteReport& report, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +} // namespace bmh::modern + +namespace bmh::modern { + +// PreMatchOffer, before a human manager's matchday: now and then a club makes an offer for +// one of his players (1 in 71 - manager rating / 50). +// Returns whether an offer was shown (its message box waits for a click before the desk). +bool pre_match_offer(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ClubAttraction(team, 0): how attractive a club is for advertisers (0-100): its European +// campaign, its league and table position (weekly.cpp). +int club_attraction(const ModernState& g, int team); + +// Modern versions of functions that transfer_bid.hpp, human_buyer_sale.hpp and +// pending_offer.hpp declare for Classic; all are implemented in weekly.cpp. +TransferBidRating rate_transfer_bid_source(ModernState&, const TransferBidRatingRequest&, + WatcomRandom&, MinuteReport&); +HumanBuyerSaleResult settle_human_buyer_sale(ModernState&, const HumanBuyerSaleRequest&, + const HumanBuyerSaleHooks&, WatcomRandom&, MinuteReport&); +PendingOfferResult process_player_card_pending_offers(ModernState& g, + const ClubPlayerDetailSelection& selection, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report); +PendingOfferResult process_natural_pending_offers_after_desk(ModernState& g, + const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report); +PendingOfferResult process_national_nomination_pending_after_desk(ModernState& g, + const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report); + +} // namespace bmh::modern diff --git a/tests/modern_season_sim.cpp b/tests/modern_season_sim.cpp new file mode 100644 index 0000000..ea38819 --- /dev/null +++ b/tests/modern_season_sim.cpp @@ -0,0 +1,358 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +// modern_season_sim - the Modern fork of season_sim (docs/new_engine); plays a new career headless through the turn driver and checks that the +// results stay plausible (the documented simulation metrics). +// +// A career is started like the UI does it (CareerSession: options, one manager, first +// desk); then the manager presses "Anstoss" at every desk until the given number of turns +// is played, the season ends or the engine reports a gap. After every turn the state is +// checked against simple invariants; violations and engine gaps are listed at the end. +// +// Usage: season_sim [turns=60] [master club=0] [watcom seed=1] [strength=2] +// Exit code: 0 no violation, 1 violations found, 2 the run stopped early (engine gap). +#include +#include +#include +#include +#include +#include +#include + +#include "modern/app/modern_session.hpp" +#include "modern/game/desk_actions.hpp" +#include "game/lineup.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/month.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "ui/desktop.hpp" + +using namespace bmh; + +namespace { + +struct Checks { + std::map counts; // violation kind -> how often + std::map first; // violation kind -> first occurrence + void fail(const std::string& kind, const std::string& where) { + if (counts[kind]++ == 0) first[kind] = where; + } +}; + +int32_t money(const modern::ModernState& g, int m) { + const size_t at = size_t(m) * 0xb0c + 0x314; + return int32_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8 | g.manager_records.at(at + 2) << 16 | + uint32_t(g.manager_records.at(at + 3)) << 24); +} + +// The invariants of PROJEKTZIEL.md that can be read from the state alone. +void check_state(const modern::ModernState& g, const std::string& when, Checks& c) { + // players: plausible ages and values, nobody in two squad slots + std::set seen; + // (only the clubs' squads up to format field = 0xb70: the national squad and the other + // lists behind them hold club players a second time) + for (size_t s = 0; s < g.squad_slots.size() && s < 0xb70; s++) { + const int id = g.squad_slots[s] & 0xfff; + if (id == 0xfff) continue; + if (!seen.insert(id).second) c.fail("player in two squad slots", when + " player " + std::to_string(id)); + const Player& p = g.players.at(size_t(id)); + if (p.age() < 16 || p.age() > 40) c.fail("age outside 16-40", when + " player " + std::to_string(id) + " age " + std::to_string(p.age())); + if (p.technique() > 99 || p.condition() > 99) c.fail("technique/condition above 99", when + " player " + std::to_string(id)); + } + // the human managers: money within a sane range, a squad with at least 11 players + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const int32_t cash = money(g, int(m)); + if (cash < -50000000 || cash > 500000000) c.fail("manager money out of range", when + " " + std::to_string(cash)); + const SquadRange r = squad_range(g.manager_teams[m]); + int n = 0; + for (size_t s = r.first; s < r.first + r.count; s++) + if ((g.squad_slots.at(s) & 0xfff) != 0xfff) n++; + if (n < 11) c.fail("human squad below 11 players", when + " " + std::to_string(n)); + } +} + +// The matchday just played. Cup phase 2 stores the shoot-out goals added to the +// match score (legacy routine). The total-12 plausibility check cannot apply to that +// combined display score: Original week40_capture.jsonl:241 records 11:10. +// Keep high ordinary scores fatal; retain shoot-out outliers as visible diagnostics. +// Evidence: external reference input +int g_high_scores = 0; // matches with 13-15 goals (outside shoot-outs) +// the human club against all clubs, league matches only (learning session: human clubs +// scored about 0.7 goals per match, the computer clubs about 1.25) +int g_human_team = -1, g_human_for = 0, g_human_against = 0, g_human_matches = 0; +int g_league_goals = 0, g_league_matches = 0; + +// Read only the current season's first-league results. A complete German Bundesliga +// season has 34 rounds x 9 fixtures = 306 matches. Unlike the historical snapshot +// counters, this includes background fixtures played while seeking the next desk. +void print_first_league_results(const modern::ModernState& g, const char* checkpoint) { + int goals = 0, matches = 0; + for (int round = 1; round <= league_matchdays(0); ++round) + for (int match = 0; match < kLeagueSizes[0] / 2; ++match) { + const Result r = decode_result(g.results.at(result_index(0, round, match))); + if (!r.played) continue; + goals += r.home_goals + r.away_goals; + ++matches; + } + std::printf("league 0 raw current-season results (%s, day %u): %d matches, %d goals, %.3f goals per match\n", + checkpoint, g.date, matches, goals, matches ? double(goals) / matches : 0.0); +} + +void check_results(const TurnResultSnapshot& r, const std::string& when, Checks& c, int& goals, int& matches) { + if (!r.valid) return; + for (const MatchGroup& grp : r.groups) + for (int m = 0; m < grp.matches(); m++) { + int home = 0, away = 0; + if (!grp.results.empty()) home = grp.results.at(size_t(m)) >> 4, away = grp.results.at(size_t(m)) & 0xf; + else if (grp.cup_results.size() == size_t(grp.matches())) + home = grp.cup_results[size_t(m)] >> 5 & 0x1f, away = grp.cup_results[size_t(m)] & 0x1f; + // (0xc on a side marks a match not played yet or postponed) + if (home >= 0xc || away >= 0xc) continue; + if (home + away > 12) { + const bool shootout = grp.results.empty() && grp.cup_results.size() == size_t(grp.matches()) && + (grp.flags() & 8) != 0 && (grp.cup_results[size_t(m)] >> 10) == 2; + const std::string score = when + " " + std::to_string(home) + ":" + std::to_string(away) + " type " + + std::to_string(grp.desc.at(0)) + " teams " + std::to_string(grp.fixtures.at(size_t(m) * 2)) + "-" + + std::to_string(grp.fixtures.at(size_t(m) * 2 + 1)); + // The original engine has no goal cap (#46: no limit of twelve in the source); + // a much stronger side wins 9:4 now and then (#57: ratings 78-87 against 55-63, + // the match replays minute by minute). A single high score is a note; what + // fails is a score no match should reach, or high scores becoming frequent + // (checked at the end of the run). + if (shootout) { + std::printf("SCORE NOTE includes shoot-out goals: %s\n", score.c_str()); + } else if (home + away > 15) { + c.fail("more than 15 goals, group type " + std::to_string(grp.desc.at(0)), score); + } else { + std::printf("SCORE NOTE more than 12 goals: %s\n", score.c_str()); + ++g_high_scores; + } + } + if (!grp.results.empty()) { + g_league_goals += home + away, ++g_league_matches; + const int a = grp.fixtures.at(size_t(m) * 2), b = grp.fixtures.at(size_t(m) * 2 + 1); + if (a == g_human_team) g_human_for += home, g_human_against += away, ++g_human_matches; + if (b == g_human_team) g_human_for += away, g_human_against += home, ++g_human_matches; + } + goals += home + away; + matches++; + } +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::printf("usage: season_sim [turns] [master club] [watcom seed] [strength]\n"); + return 2; + } + const int turns = argc > 2 ? std::atoi(argv[2]) : 60; + Checks checks; + std::string gap; + int played = 0, goals = 0, matches = 0, seasons = 0; + try { + modern::app::ModernSession session(argv[1], argc > 4 ? uint32_t(std::stoul(argv[4])) : 1u); + ui::SetupOptions options; // 5 seasons, level 2, one manager, mode III, league and world + ui::ManagerChoice choice; + choice.name = "SIM"; + choice.master_club = argc > 3 ? std::atoi(argv[3]) : 0; + choice.strength = argc > 5 ? std::atoi(argv[5]) : 2; + std::string error; + if (!session.confirm_manager(options, choice, error)) throw std::runtime_error("manager: " + error); + ui::CareerInitializationResult init; + if (!session.finish(init, error)) throw std::runtime_error("career start: " + error); + uint64_t revision = init.desktop.revision; + int contract_expiry_decisions = 0; + int contract_expiry_renewals = 0; + int contract_expiry_rejections = 0; + int contract_expiry_declines = 0; + int contract_expiry_errors = 0; + // The removed assistant default fabricated a salary, a 24-month term, and + // an unrelated Watcom stream. Keep long simulator runs useful only when + // explicitly requested: model a manager who checks real demands using + // Session W and offers exactly the demand for two years when available, + // otherwise the first valid term within the UI's 200000 salary limit. + // The real Source offer formula decides acceptance; refusal releases (0). + // No board fields are written by this policy. Without SIM_CONTRACTS=1 the + // simulator installs no presenter; an unhandled expiry remains a real gap. + const char* sim_contracts_env = std::getenv("SIM_CONTRACTS"); + if (sim_contracts_env && std::string(sim_contracts_env) == "1") { + session.set_contract_expiry_presenter([&](modern::ModernState& state, WatcomRandom& random, + int manager, int row) -> int { + ++contract_expiry_decisions; + try { + const auto demands = modern::contract_demands(state, manager, row, false, random); + const auto valid_term = [&](int i) { + const uint32_t demand = demands[size_t(i)]; + return demand != 0 && demand != UINT32_MAX && demand <= 200000; + }; + int term = valid_term(1) ? 1 : -1; // original two-year column, when admissible + if (term < 0) + for (int i = 0; i < int(demands.size()); ++i) + if (valid_term(i)) { term = i; break; } + if (term < 0) { + ++contract_expiry_declines; + std::printf("contract expiry policy: manager=%d row=%d no valid demand; release=0\n", + manager, row); + return 0; // no valid Source demand: deliberately release + } + const uint32_t demand = demands[size_t(term)]; + const uint32_t offer = demand; + const bool accepted = modern::contract_offer(state, manager, row, term, offer, + demand, false, true, random, nullptr); + std::printf("contract expiry policy: manager=%d row=%d term=%d demand=%u offer=%u accepted=%d\n", + manager, row, term + 1, demand, offer, accepted ? 1 : 0); + if (accepted) { + ++contract_expiry_renewals; + return 1; + } + ++contract_expiry_rejections; + return 0; // legacy routine's explicit refusal/release answer + } catch (const std::exception&) { + ++contract_expiry_errors; + return -2; // Preserve the genuine unsupported/abort path. + } + }); + } + // SIM_INTERVENE=1: in every match of the human club the manager substitutes once at + // minute 30 (the last field player for the first bench player) and the side is rated + // again, as after the line-up screen opened from the match + int interventions = 0; + if (std::getenv("SIM_INTERVENE")) + session.set_live_minute([&](int minute, MatchEngine& engine, std::vector& groups, GameState& gs) { + static int calls = 0; + if (std::getenv("SIM_DEBUG") && calls++ < 3) std::fprintf(stderr, "live_minute %d\n", minute); + if (minute != 30) return; + const int team = gs.manager_teams.at(0); + for (const MatchGroup& grp : groups) + for (int m = 0; m < grp.matches(); m++) + if (grp.fixtures.at(size_t(m) * 2) == team || grp.fixtures.at(size_t(m) * 2 + 1) == team) { + if (!manual_substitution(gs, team, 10, 11)) { + if (std::getenv("SIM_DEBUG")) { + const SquadRange sr = squad_range(team); + std::fprintf(stderr, "substitution refused: slot10 %04x slot11 %04x flags %04x\n", gs.squad_slots.at(sr.first + 10), + gs.squad_slots.at(sr.first + 11), gs.team_flags.at(team)); + } + return; + } + MinuteReport rr; + engine.rerate_team(team, rr); + if (rr.unsupported) checks.fail("intervention: " + rr.reason, "minute 30"); + interventions++; + return; + } + }); + // The simulator is the engine-side automation harness; the app exposes this + // read-only, so this test borrows the non-const underlying state for desk actions. + modern::ModernState& g = const_cast(session.state()); + std::printf("career started: team %d, date %u, money %d\n", g.manager_teams.at(0), g.date, money(g, 0)); + check_state(g, "start", checks); + bool listed_for_sale = false; + int ad_contracts = 0; // SIM_ADVERTISING: contracts accepted + for (; played < turns; played++) { + // SIM_ADVERTISING=1: the manager keeps his advertising places filled, as every + // player does (the largest income besides the gate): an expired contract is renewed + // when the sponsor offers it (legacy routine), a free place takes the best acceptable + // offer (TV, shirt, then the boards). Without it a long run lives on gate money + // alone and its debts grow without bound (issue #95). + if (const char* ads = std::getenv("SIM_ADVERTISING"); ads && std::string(ads) == "1") { + for (int slot = 15; slot >= 0; --slot) { + AdvertisingOfferList list = modern::advertising_offers(g, 0, slot); + if (list.status == AdvertisingOfferStatus::unsupported_extension) { + const auto renewal = modern::check_advertising_renewal(g, 0, slot, session.rand()); + if (renewal.status == AdvertisingRenewal::Status::offered) + modern::answer_advertising_renewal(g, 0, renewal.contract_slot, true); + list = modern::advertising_offers(g, 0, slot); + } + if (list.status != AdvertisingOfferStatus::available) continue; + const AdvertisingOfferCandidate* best = nullptr; + for (const auto& o : list.offers) + if (o.can_accept && (!best || o.monthly_amount > best->monthly_amount)) best = &o; + if (!best) continue; + AdvertisingOfferRequest request; + request.manager = 0; + request.display_slot = slot; + request.contract_slot = list.contract_slot; + request.expected_contract = list.contract_bytes; + request.raw_slot = best->raw_slot; + request.expected_offer = best->bytes; + if (modern::accept_advertising_offer(g, request).status == AdvertisingOfferStatus::accepted) ++ad_contracts; + } + } + if (std::getenv("SIM_TRANSFERS")) { + MinuteReport transfer_report; + WatcomRandom& transfer_rand = session.rand(); + if (!listed_for_sale) { + const SquadRange squad = squad_range(g.manager_teams.at(0)); + for (int row = int(squad.count) - 1; row >= 11; --row) { + if ((g.squad_slots.at(squad.first + size_t(row)) & 0xfff) == 0xfff) continue; + const auto result = modern::list_manager_player(g, 0, row, transfer_rand, transfer_report); + if (result.status == TransferActionStatus::accepted) listed_for_sale = true; + break; + } + if (transfer_report.unsupported) checks.fail("transfer listing", transfer_report.reason); + } + for (int entry = 0; entry < 40; ++entry) { + const int player = g.squad_slots.at(0xb70u + size_t(entry)) & 0xfff; + const uint32_t at = ::bmh::layout::EditorListUnsigned + uint32_t(entry) * 0x58; + if (player == 0xfff || int16_t(g.memory.u16(at)) != -1) continue; + const uint32_t fee = g.memory.u32(at + 0x2c), salary = g.memory.u32(at + 0x30); + if (fee == 0 || salary == 0) continue; + TransferBidRequest bid; + bid.manager = 0; bid.list_entry = entry; bid.player = player; bid.fee = int32_t(uint64_t(fee) * 130 / 100); + bid.annual_salary = int32_t(uint64_t(salary) * 120 / 100); bid.contract_years = 2; + const auto offer = modern::submit_transfer_bid(g, bid, transfer_rand); + if (offer.status == TransferActionStatus::pending || offer.status == TransferActionStatus::accepted) break; + } + } + ui::DeskRequest kickoff; + kickoff.kind = ui::DeskRequestKind::advance_turn; + kickoff.manager_slot = int(g.memory.u8(::bmh::layout::ActiveManager)); + kickoff.revision = revision; + const TurnAdvanceResult r = session.dispatch_kickoff(kickoff, revision, error); + if (r.kind == TurnDeskKind::Failed || r.kind == TurnDeskKind::WaitingAtDesk) { + gap = r.reason.empty() ? error : r.reason; + break; + } + if (r.kind == TurnDeskKind::CareerComplete) { + ++played; + std::printf("turn %d (day %u): career complete\n", played, r.date); + break; + } + const std::string when = "turn " + std::to_string(played + 1) + " (day " + std::to_string(r.date) + ")"; + g_human_team = g.manager_teams.at(0); + check_results(session.last_turn_results(), when, checks, goals, matches); + check_state(g, when, checks); + std::printf("%s: %s, place %d, money %d\n", when.c_str(), r.kind == TurnDeskKind::SeasonEndDesk ? "season end desk" : "desk", + modern::table_position(g, g.manager_teams.at(0)), money(g, 0)); + if (r.kind == TurnDeskKind::SeasonEndDesk) { + print_first_league_results(g, "season end"); + ++seasons; + } // (the next kickoff runs the season change) + } + print_first_league_results(g, "run end"); + if (std::getenv("SIM_ADVERTISING")) std::printf("%d advertising contracts accepted (SIM_ADVERTISING=1)\n", ad_contracts); + if (std::getenv("SIM_INTERVENE")) std::printf("%d interventions (substitution at minute 30, re-rated)\n", interventions); + if (sim_contracts_env && std::string(sim_contracts_env) == "1") + std::printf("contract expiry policy: %d decisions, %d renewals, %d rejected offers/releases, %d no-demand releases, %d errors (SIM_CONTRACTS=1)\n", + contract_expiry_decisions, contract_expiry_renewals, contract_expiry_rejections, contract_expiry_declines, + contract_expiry_errors); + } catch (const std::exception& ex) { + gap = std::string("exception: ") + ex.what(); + } + std::printf("\n%d turns, %d season ends; recorded matchday snapshots (all competitions; shoot-outs included): %d matches, %.2f goals per match\n", played, seasons, matches, + matches ? double(goals) / matches : 0.0); + if (g_human_matches && g_league_matches) + std::printf("recorded league snapshots: human club %.2f goals for, %.2f against per match (%d matches); all clubs %.2f per club and match\n", + double(g_human_for) / g_human_matches, double(g_human_against) / g_human_matches, g_human_matches, + double(g_league_goals) / (2.0 * g_league_matches)); + // the goal gates of the whole run (#57): high scores stay rare (at most one per 2000 + // matches, at least one allowed) and the average stays in a football range + if (g_high_scores > std::max(1, matches / 2000)) + checks.fail("too many matches with more than 12 goals", std::to_string(g_high_scores) + " of " + std::to_string(matches)); + if (matches >= 500 && (double(goals) / matches < 2.0 || double(goals) / matches > 4.0)) + checks.fail("goals per match outside 2.0-4.0", std::to_string(double(goals) / matches)); + for (const auto& [kind, n] : checks.counts) std::printf("VIOLATION %-32s %4d x, first: %s\n", kind.c_str(), n, checks.first[kind].c_str()); + if (!gap.empty()) std::printf("STOPPED: %s\n", gap.c_str()); + return !gap.empty() ? 2 : checks.counts.empty() ? 0 : 1; +} diff --git a/tests/world_layout_tests.cpp b/tests/world_layout_tests.cpp new file mode 100644 index 0000000..4f0b8b0 --- /dev/null +++ b/tests/world_layout_tests.cpp @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-only +// WorldLayout: the Classic layout reproduces the original squad table and team ranges; +// set_world_layout accepts a consistent Modern-shaped layout and rejects broken ones. +#include +#include +#include + +#include "game/state.hpp" +#include "game/world_layout.hpp" + +using namespace bmh; + +namespace { +int failures = 0; +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } +} +bool rejects(WorldLayout w) { + try { + set_world_layout(std::move(w)); + } catch (const std::invalid_argument&) { + return true; + } + return false; +} +// A layout with `league` clubs of 24 slots each, the pools behind them. +WorldLayout uniform(int league, int german) { + WorldLayout w; + w.league_teams = league; + w.german_teams = german; + w.squad_start.clear(); + w.squad_size.clear(); + for (int t = 0; t < league; ++t) { + w.squad_start.push_back(uint32_t(t) * 24); + w.squad_size.push_back(24); + } + w.transfer_list = uint32_t(league) * 24; + w.free_agents = w.transfer_list + 44; + w.foreign_offers = w.free_agents + 80; + w.pool_end = w.foreign_offers + 20; + w.total_slots = w.pool_end + 24 + 54; + return w; +} +} // namespace + +int main() { + // Classic: the original numbers (V2.24). + const WorldLayout c = classic_world_layout(); + check(world_layout().league_teams == 138, "default layout is Classic"); + check(c.no_team() == kNoTeam && no_team() == kNoTeam, "Classic no_team is 0x165"); + check(c.first_foreign_cup() == 168 && c.total_teams() == 419, "Classic team ranges"); + check(squad_range(0).first == 0 && squad_range(0).count == 24, "German club squad"); + check(squad_range(89).first == 89 * 24 && squad_range(89).count == 24, "last German club squad"); + check(squad_range(90).first == 90 * 24 && squad_range(90).count == 16, "first international club squad"); + check(squad_range(137).first == 137 * 16 + 720 && squad_range(137).count == 16, "last international club squad"); + check(squad_range(137).first + 16 == c.transfer_list && c.transfer_list == 0xB70, "pools follow the squads"); + check(squad_range(kNoTeam).first == 3072 && squad_range(kNoTeam).count == 24, "no-club squad at 3072"); + check(squad_range(138).count == 0 && squad_range(200).count == 0, "squadless clubs"); + check(!rejects(classic_world_layout()), "Classic layout is accepted"); + + // Modern shape: 168 league clubs with 24 slots each. + WorldLayout m = uniform(168, 90); + check(!rejects(m), "Modern layout is accepted"); + check(world_layout().first_foreign_cup() == 198 && no_team() == 387 && world_layout().total_teams() == 449, + "Modern team ranges"); + check(squad_range(150).first == 150 * 24 && squad_range(150).count == 24, "Modern international squad"); + check(squad_range(no_team()).first == world_layout().pool_end, "Modern no-club squad"); + + // Inconsistent layouts are rejected and leave the running layout unchanged. + WorldLayout gap = uniform(168, 90); + gap.squad_start[5] += 1; + check(rejects(gap), "squads with a gap are rejected"); + WorldLayout pools = uniform(168, 90); + pools.free_agents += 1; + check(rejects(pools), "misplaced pools are rejected"); + WorldLayout too_many = uniform(168, 90); + too_many.national_teams = 700; + check(rejects(too_many), "more than 1023 teams are rejected"); + check(world_layout().league_teams == 168, "a rejected layout leaves the previous one"); + + set_world_layout(classic_world_layout()); + if (failures) return 1; + std::puts("world layout checks passed"); + return 0; +} diff --git a/tools/modern/check_fork_calls.sh b/tools/modern/check_fork_calls.sh new file mode 100644 index 0000000..e77e3b6 --- /dev/null +++ b/tools/modern/check_fork_calls.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-3.0-only +# check_fork_calls.sh BUILD_DIR - fails if a Modern library (LIBRARY, default bmh_season_modern) +# calls a Classic season +# function. Modern season code must call its own fork (namespace bmh::modern); a call that +# resolves to a function defined in one of the forked Classic sources means a Modern +# declaration is missing (see docs/new_engine). Windows/MSVC builds only (uses dumpbin). +# +# tools/modern/check_fork_calls.sh build +set -euo pipefail +build=${1:-build} +config=${CONFIG:-Release} +library=${LIBRARY:-bmh_season_modern} +dumpbin=${DUMPBIN:-$(ls -d "/c/Program Files/Microsoft Visual Studio/"*/*/VC/Tools/MSVC/*/bin/Hostx64/x64/dumpbin.exe 2>/dev/null | tail -1)} +[ -x "$dumpbin" ] || { echo "dumpbin not found (set DUMPBIN)" >&2; exit 2; } +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +symbols() { MSYS_NO_PATHCONV=1 "$dumpbin" /symbols "$1"; } +# Undefined external symbols of the Modern library. +symbols "$build/$config/$library.lib" | + awk '/External/ && /UNDEF/ { i = index($0, "| "); s = substr($0, i + 2); sub(/ \(.*/, "", s); print s }' | + sort -u > "$work/undef" +# Externals defined by the Classic objects that were forked (the Modern sources' names). +: > "$work/defs" +for source in src/modern/game/*.cpp; do + name=$(basename "$source" .cpp) + obj="$build/bmhcore.dir/$config/$name.obj" + [ -f "$obj" ] || continue + symbols "$obj" | + awk -v f="$name" '/External/ && !/UNDEF/ { i = index($0, "| "); s = substr($0, i + 2); d = s; sub(/ \(.*/, "", s); print s "\t" f "\t" d }' >> "$work/defs" +done +sort -t$'\t' -k1,1 -u "$work/defs" > "$work/defs.sorted" +join -t$'\t' "$work/undef" "$work/defs.sorted" > "$work/hits" || true +if [ -s "$work/hits" ]; then + echo "Modern season code calls Classic season functions:" + cut -f2,3 "$work/hits" | sed 's/^\([a-z_]*\)\t/\1: /' + exit 1 +fi +echo "OK: $library calls no Classic season function."