diff --git a/CMakeLists.txt b/CMakeLists.txt index 82ced6e..881b9ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -132,9 +132,21 @@ endif() # string literals. (Until 1.0.12 the MSVC build compiled these sources again for every # consumer, which cost most of the build time; controller.cpp then got /utf-8 only from # targets that set it.) -add_library(bmh_app_session OBJECT src/app/career_session.cpp src/app/window_actions.cpp src/app/desktop_actions.cpp) +# The career session is defined by topic in career_session*.cpp (the class: src/app/career_session.hpp). +set(BMH_APP_SESSION_SOURCES + src/app/career_session.cpp + src/app/career_session_club.cpp + src/app/career_session_league.cpp + src/app/career_session_statistics.cpp + src/app/career_session_transfer.cpp + src/app/career_session_desk.cpp + src/app/career_session_match.cpp + src/app/career_session_management.cpp + src/app/window_actions.cpp + src/app/desktop_actions.cpp) +add_library(bmh_app_session OBJECT ${BMH_APP_SESSION_SOURCES}) target_link_libraries(bmh_app_session PRIVATE bmhui) -add_library(bmh_app_session_sdl OBJECT src/app/career_session.cpp src/app/window_actions.cpp src/app/desktop_actions.cpp) +add_library(bmh_app_session_sdl OBJECT ${BMH_APP_SESSION_SOURCES}) target_link_libraries(bmh_app_session_sdl PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) add_library(bmh_app_controller_sdl OBJECT src/app/controller.cpp) target_link_libraries(bmh_app_controller_sdl PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) diff --git a/docs/DIFFERENCES.md b/docs/DIFFERENCES.md index 4a39803..70b3647 100644 --- a/docs/DIFFERENCES.md +++ b/docs/DIFFERENCES.md @@ -6,7 +6,7 @@ See [Compatibility decisions](COMPATIBILITY.md) for the overall policy. These en describe deliberate changes; they are not a list of every known compatibility limit. - [src/app/app_run.cpp](../src/app/app_run.cpp): display the repository-owned title at its native resolution until a complete left/right click, without loading balls. -- [src/app/career_session.cpp](../src/app/career_session.cpp): supports designated set-piece record initialization and validation. +- [src/app/career_session_match.cpp](../src/app/career_session_match.cpp): supports designated set-piece record initialization and validation. - [src/app/quit_confirmation.hpp](../src/app/quit_confirmation.hpp): confirms application exit with a localized native dialog, with cancellation selected by default. - [src/game/career.cpp](../src/game/career.cpp): skips reserved calendar positions when assigning a joining manager to a club. - [src/game/career.hpp](../src/game/career.hpp): uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. diff --git a/src/app/career_session.cpp b/src/app/career_session.cpp index be1d853..7c46742 100644 --- a/src/app/career_session.cpp +++ b/src/app/career_session.cpp @@ -11,124 +11,28 @@ // notices flow the other way: the session calls presenter hooks synchronously and waits. // This file also contains the checkpoint/restore code used by those rollbacks, the career // start (options, manager join), save/load through the .FBM container and autosave. -#include "formats/native_save_version.hpp" -#include "formats/badge_policy.hpp" -#include "game/calendar.hpp" -#include "formats/executable_layout.hpp" -#include "app/career_session.hpp" -#include "formats/league_visibility.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "formats/binary.hpp" -#include "formats/fbm.hpp" -#include "formats/savestate.hpp" -#include "game/career.hpp" -#include "game/cup.hpp" -#include "game/driver.hpp" -#include "game/desk.hpp" -#include "game/desk_actions.hpp" -#include "game/match.hpp" -#include "game/messages.hpp" -#include "game/prediction.hpp" -#include "game/schedule.hpp" -#include "game/bank_credit.hpp" -#include "game/matchday_setup.hpp" -#include "game/matchday.hpp" -#include "game/lineup.hpp" -#include "game/month.hpp" -#include "game/national.hpp" -#include "game/schedule.hpp" -#include "game/table.hpp" -#include "game/table_forecast.hpp" -#include "game/save.hpp" -#include "game/season.hpp" -#include "game/turn.hpp" -#include "game/week.hpp" -#include "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" +// The member functions are defined by topic: +// career_session.cpp construction, career start and manager join +// career_session_club.cpp the club information dialogs (club, player list, player detail) and their services +// career_session_league.cpp the league family: tables, forecasts, friendly opponent table, phase results, running overview +// career_session_statistics.cpp strengths, top scorers, opportunities, other games, balance plan and league pairings +// career_session_transfer.cpp transfers: offer editor, poaching, transfer market +// career_session_desk.cpp the desk: mailbox, settings, advertising, contracts, desk settings, search profile, widgets, layout +// career_session_match.cpp match preparation and the live match: tactics, line-up, live overview, interventions, pitch +// career_session_management.cpp club management: training, training camp, bank, stadium, toto +// (here also: the turn - finish and kick-off -, the desk projection, autosave and save, the presenter hooks) +#include "app/career_session_internal.hpp" namespace bmh::app { namespace { + // Process-wide counter that hands every CareerSession a unique id (see session_id_ in the // constructor); the turn driver stores that id to recognise which session it belongs to. 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; - -// True for the stadium requests that belong to the block-expansion dialog (select, total, -// feature toggle, cancel, confirm, answer tip). -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; -} - -// Fills every rank with 1 and returns 0 unless the first league's round counter is in the -// range [2, matchdays of league 0); inside that range it returns 9 for team ids >= 138 and 0 -// for all other teams. -int national_opportunities_rank(const GameState& 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>=world_layout().league_teams?9:0; -} - -// Reads one byte of the executable's data at 'address': from the game's memory image when the -// address is mapped there, else from the runtime override map, else from the loaded EXE. -uint8_t source_runtime_byte(const GameState& 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; -} -// Writes one byte to the memory image when the address is mapped there, otherwise into the -// runtime override map (the EXE image itself is never modified). -void source_runtime_set_byte(GameState& state,std::map& runtime, - uint32_t address,uint8_t value) { - if(state.memory.has(address))state.memory.set8(address,value); - else runtime[address]=value; -} - -// Little-endian 32-bit read built from four source_runtime_byte reads. -uint32_t source_runtime_u32(const GameState& 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; -} - -// Copies the executable's presentation switches (decorated background, solid panel, text -// gradient, cached backdrop) onto the balance page state. -void apply_balance_source_style(ui::BalanceState& page,const GameState& 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; -} // Little-endian 32-bit read from a saved match-group descriptor (throws via at() when short). uint32_t saved_group_u32(const Bytes& bytes, size_t offset) { @@ -573,7 +477,8 @@ void restore_saved_turn_cursor(TurnDriver& driver, GameState& state, const Datab // It is not inferred from a nonzero cursor, and does not select a policy. driver.loaded_matchday_resume = true; } -} + +} // namespace // 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. @@ -943,3554 +848,6 @@ bool CareerSession::confirm_manager(const ui::SetupOptions& options, const ui::M return true; } -// Club-information modal family (enter, change category, player redraw, national action, -// pending offers): each member refuses to run while another modal owner is open and clears -// 'error' first. The ones that change state work on copies and assign them back only after -// success. -// Enter: opens the club info entry for 'team'; nullopt plus 'error' on an invalid team. -std::optional CareerSession::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 prepare_club_info_entry(g_, team); } - catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } -} - -// Switches the club info category for 'team'; nullopt plus 'error' when it is invalid. -std::optional CareerSession::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 set_club_info_category(g_, team, requested); } - catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } -} - -// Redraws a player detail card; random generators advance only if the redraw succeeded. -std::optional CareerSession::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 = 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; - } -} - -// Applies the national-team add/remove action of a player card on a staged copy; the copy is -// committed only when the engine reports no reason. Returns whether the action was applied. -std::optional CareerSession::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 = 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; - } -} - -// Processes the pending transfer offers of a player card. Rejects a stale revision or a nested -// pending-offer/market dispatch, works on copies and commits them when at least one offer was -// processed. The revision is bumped here unless a calendar advance is active: then the outer -// driver publishes the revision when it returns. -std::optional CareerSession::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 = 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; - } -} - -// Seeds the process-only byte map used by the club modals with their start values from the -// executable; these values are never written to a save. -void CareerSession::initialize_club_modal_runtime() { - // Setup clears the boot-only dialog mode before either creating or loading - // a career. This process flag is deliberately absent from native saves. - club_modal_runtime_.emplace(layout::CompactDialogFrame, 0); - // 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)); -} - -// Collects the executable bytes and rating tables the Sportschau screen reads. -SportschauSourceOptions CareerSession::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_)}; -} - -// Builds the service callbacks of the club modal on a given (staged) state, generators and -// runtime byte map, so the modal can run on a copy and be committed or dropped by the caller. -ClubModalServices CareerSession::staged_club_modal_services(GameState& 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]() -> GameState& { return *g; }; - services.enter_club=[g](int team) { return prepare_club_info_entry(*g,team); }; - services.change_category=[g](int team,int category) { return 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=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=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=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; -} - -// Same services bound to the live state (non-transactional); pending offers go through -// dispatch_club_player_pending_offers. Throws when another modal owner is open. -ClubModalServices CareerSession::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 { -// Writes the process scratch bytes (league, group, date pieces, strength sums) that the -// original leaves behind after drawing the pairings page, so later reads see the same values. -// Bytes go to the memory image when mapped there, else to the runtime map. -void pairings_runtime_draw(GameState& 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)); -} - -// True when 'team' belongs to one of the human managers or to the national team record of a -// national coach; throws FormatError when the manager count is missing or invalid. -bool other_games_source_manager_owned(const GameState& 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; -} - -// Replays the side effects of drawing the other-games page: five ordered team-average -// calculations per displayed club (some of which draw random numbers) and the scratch bytes -// they leave. -void other_games_source_redraw_effects(GameState& 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)); - } - } - } - } -} - -// True when two other-games checkpoints agree on state, random generators, runtime bytes, -// selection and owner identity, i.e. nothing observable changed in between. -bool same_other_games_live_baseline(const CareerSession::OtherGamesCheckpoint& before, - const CareerSession::OtherGamesCheckpoint& after) { - if(save_stream(before.state)!=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; -} - -// Compares the runtime-only fields of two states (callbacks by target type); used to check the -// strengths view left the game unchanged. -bool same_strengths_runtime_state(const GameState& a,const GameState& 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); -} - -// Reinterprets the low byte of 'value' as a signed byte. -int8_t source_byte(int value) { return static_cast(uint8_t(value)); } - -// Builds the "first-end" round range label of the league table from a text template, patching -// the two two-digit numbers in the German or English layout. -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=league_system().english_competitions ? texts[82] : std::string(fixed.begin(),fixed.end()); - const size_t start=league_system().english_competitions ? 0 : 4; - const size_t finish=league_system().english_competitions ? 3 : 7; - if(raw.size() first -// and refreshes the retained range label; throws FormatError when the league is unknown. -void source_table_normalize_range(CareerSession::LeagueFamilyOwner::TableOwner& table, - const GameState& game,int league,const TextDb& texts) { - if(league<0||league>=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; -} - -// True when a table request carries no stray fields (no target child, team, row or dialog reply; -// league id only if the selector variant is allowed) and the expected control index. -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; -} - -// Sets the table aggregation flag bits from the clear bits 4 and 2 of the display-mode word. -void source_table_apply_entry_flags(CareerSession::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); -} - -// Packs a table owner's round range, flags, display word and optional accepted engine table -// (or forecast marker) into the projection context used to render the league table page. -ui::LeagueTableProjectionContext source_table_context( - const CareerSession::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; -} -} - -// League family (table / pairings / strengths and the friendly opponent table): these three -// child screens are linked under one LeagueFamilyOwner carrying a family id. Pattern: each -// entry or transition validates the identity (revision, active manager slot, club, date) and -// the neighbouring child owners, snapshots the native save stream, random seeds and runtime -// bytes into the owner, and every close/suspend compares the live state with that snapshot so -// a stale or tampered request is rejected with an error text and nothing is changed. -// Child numbers: 1 = Table, 2 = Pairings, 3 = Strengths. -// Builds the identity (manager, club, date, default league, settings words) needed to open the -// strengths screen for the active manager; returns an empty optional when anything is missing. -std::optional CareerSession::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; -} - -// Opens the family at 'child' for the identity: checks no family/TeamInfo is active, the -// revision matches, the identity belongs to the active manager and club of today (or to the -// live overview owner), and that Pairings/Strengths entries have a matching child owner. -// Allocates a family id, snapshots the state into a LeagueFamilyOwner and, for the table, builds -// the page. Returns the bound identity, or an empty optional with 'error'. -std::optional CareerSession::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=save_stream(g_); - } - LeagueFamilyOwner owner;owner.identity=identity;owner.child=child;owner.native=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=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; -} - -// Opens the table used to pick a friendly-match opponent (child 1 with friendly_opponent set). -// Needs the strengths request of the active manager and no other child owner; the table -// display word is initialised for that picker. Any failure restores the family checkpoint. -std::optional CareerSession::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>=world_layout().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 {}; - } -} - -// Checks a select_opponent request against the owned table (identity, revision, row, club -// identity key) and returns the runtime team of the chosen row, or an empty optional with 'error'. -// Does not change state. -std::optional CareerSession::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>=world_layout().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; -} - -// The player picked their own club in the opponent table: restores the normal-mode bit of the -// display word, advances the family sequence and keeps the picker open. Empty optional on a -// stale or different-club request. -std::optional CareerSession::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=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; -} - -// Leaves the opponent table: validates a select_opponent (not the own club) or close request, -// restores the display word, validates the new preparation projection and drops the family -// owner while advancing the revision. Failure restores the checkpoint and returns empty. -std::optional CareerSession::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 {}; - } -} - -// Moves the family from one child screen to another: the request, owner and 'next' identity must -// agree (same family id, manager, club, day; sequence increased by one; revision at most one -// ahead). Replaces the owner with a fresh snapshot, building the table page when the target is -// the table. Returns false with 'error' when the transition is stale or mismatched. -bool CareerSession::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=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=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; -} - -// True when the identity (its source_param2 holds the match minute) belongs to the currently -// open live overview: same manager, team, minute and day, and for a phase-result viewer the -// same match group. -bool CareerSession::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))); -} - -// Final close of the family: the long condition re-verifies identity, child owner and that the -// live state, random generators and runtime bytes still equal the owner's snapshot. On success -// it commits staged Pairings changes (if any), draws the random stir unless a phase-result -// viewer owns that draw, resets the child owners and bumps the revision. Returns the new -// preparation projection, or an empty optional with 'error' and no change. -std::optional CareerSession::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_|| - 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||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&&(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 { - GameState 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) - 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 {};} -} - -// Leaves the Strengths child towards Table or Pairings without a full close: checks the owner -// snapshot is unchanged, then drops the strengths owner. False with 'error' when stale. -bool CareerSession::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||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; -} - -// Leaves the Pairings child towards Table or Strengths: after the same snapshot checks it -// commits only the staged page/redraw changes of the draft and drops the draft. False with -// 'error' when stale or the return word is missing. -bool CareerSession::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))|| - 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). - GameState 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; -} - -// Prepares the manager mode word and runtime bytes before a child screen is entered, after -// validating the identity and that no other child owner or dispatch is active. False with -// 'error' otherwise. -bool CareerSession::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; -} - -// Installs (or clears) the turn driver hook that fires at the end of a match phase. The wrapper -// records the current request in phase_result_request_ for the duration of the call, only -// accepts the driver's own groups and state, and requires that any viewer is closed again before -// the engine continues. -void CareerSession::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 GameState& 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; - // Clears the borrowed request pointer when the hook returns or throws. - 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"); - }; -} - -// Live overview group (phase-result viewer, live league table / pairings opened from a running -// match): only valid inside a calendar advance (calendar_advance_active_) with the driver -// waiting at a phase boundary. Pattern: open -> dispatch -> acknowledge; the owner snapshots the -// state and random counters when it opens and the close must find them unchanged. -// Opens the viewer at a phase boundary: copies the current group results into a staged state -// (no simulation, no random draws) and opens the overview on it; on failure the previous state -// is kept. Returns an empty optional with 'error' when no request is pending or a viewer is open. -std::optional CareerSession::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. - GameState 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)*kLeagueResultsStride + 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 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 {}; } -} - -// Forwards a viewer action while the phase-result owner of the pending request is open; empty -// optional with 'error' if the viewer is missing or belongs to another group. -std::optional CareerSession::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); -} - -// Opens the overview from a key press during a running match (not a phase-result viewer). -std::optional CareerSession::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); -} - -// Shared opener. The long guard requires an active calendar advance, no other modal owner or -// dispatch, a request that matches the driver's groups, the live state objects and the active -// manager (revision and scope included). key_slot 0 opens the league table, 1 the league -// pairings. Returns an empty optional with 'error' when the request is stale, nested or -// unauthenticated. -std::optional CareerSession::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 {}; - } - - - // Scope guard: turns calendar_advance_active_ off while the family screens run and restores the - // previous value on exit, so nested family code does not treat itself as inside the advance. - 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 = 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_,{}, {}, - 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 = 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 { - // Cup descriptor (not a league): the overview becomes an other-games detail page bound to the - // active cup entry, found by trying linked-page ordinals until the cup entry and competition - // id match. Anything else throws and is rolled back by the catch block below. - if (request.key_slot != 0 && request.key_slot != 1) - throw FormatError("live overview: invalid cup overview key slot"); - const int entry_index = 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(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(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 >= 138 || 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=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=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(); - // Commit point: the owner now holds its final kind, family identity and revision; the scope - // counter and the revision are advanced only here, after every child owner was opened. - 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) { - // Failure path: restore the family, pairings and other-games checkpoints, drop the overview - // owner and put the scope counter back, so a failed open leaves no trace. - 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 {}; - } -} - -// League table dispatch group (controls, range dialog, forecast acknowledgement, league -// selector, team info). Pattern: validate the request envelope, identity, owner and that the -// live state still equals the owner snapshot; take a checkpoint; apply the change to the -// table owner; refresh the snapshot and identity (sequence + 1, revision + 1); on any failure -// restore the checkpoint and the old revision and return an empty optional with 'error'. -// Projects the table page (or the pending range dialog profile) of the owned table child; -// read-only. Empty optional with 'error' when no table owner exists or the state drifted. -std::optional CareerSession::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(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 {};} -} - -// Applies one of the table's ten controls (index 0-9) to the owned table. Requires a ready -// table, a canonical request envelope and an unchanged snapshot; revision advances by one. -std::optional CareerSession::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|| - 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); - }; - // Controls 0-2 set the aggregation flags and mode bits, 3 computes a forecast table (shown - // after the present acknowledgement), 4-6 toggle display bits (at least one stays set), 7 - // toggles the normal mode, 8 resets the round range to the whole season and 9 starts the - // two-step range dialog. - 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 CareerSession::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)|| - 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=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 {};} -} - -// The forecast page has been shown: adopts the random generator state computed with the -// forecast, returns the table to ready and rebuilds the normal page. -std::optional CareerSession::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|| - 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=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 {};} -} - -// Switches the table to another league (map click) or toggles the league group, after -// checking the target is listed in the bound league map. Works on staged copies of the state, -// runtime bytes and owner and commits them only on success; returns false with 'error' otherwise. -bool CareerSession::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|| - 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 CareerSession::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_|| - 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; - GameState 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; - // Marks the family as inside TeamInfo while the presenter runs; cleared on every exit. - 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)&& - save_stream(before.state)==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; - // The club information enters the club again on every redraw (view toggle, statistics, player - // card), so one entry is the minimum; requiring exactly one threw away the whole visit, also the - // Nein/Radio/Video setting made in it. - if(!live_unchanged||!accepted||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=club_player_detail_context(next,**poach_selection); - if(chosen.selection.runtime_team!=selected_team || chosen.source_slot<0 || - chosen.source_slot>=0xb70 || 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=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=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 {};} -} - -// After a child screen acknowledged its page, re-binds the family owner to the child's new -// identity (same family id and sequence, revision at most one ahead) and refreshes its snapshot. -// False with 'error' when the identity or child owner is stale. -bool CareerSession::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=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; -} - -// Strengths / top scorers / opportunities / other games group: modal desk pages that follow -// open -> dispatch -> acknowledge. Each open_* validates the desk request (menu kind, revision, -// active manager slot, desk stage, no other modal owner) and stores an owner that snapshots the -// native stream and the random counters; each dispatch_* refuses a stale identity or a changed -// snapshot, applies one action on a copy, bumps revision and sequence and returns the new page -// plus the desktop projection. Failures return an empty optional with 'error' and change nothing. -// National-coach desk identity: while a national coach manages the national team the manager's -// team is the national slot (kNoTeam or 0x165); the club identity key is then taken from the -// spare manager record 4 (offset 0x290) instead of the club table. -// Strengths dispatch: one entry point for open, control, league select, group toggle, team info -// and close of the strengths page (also used as a child of the league family). -std::optional CareerSession::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; - // The turn driver marks the claimed turn as Failed until it completes (a guard against replaying - // a half-played turn), so inside the running matchday the stage is not a desk. The Stärken page - // of the live overview (G key, results page after a phase) belongs to that running turn. - const bool running_turn=live_overview_owner_.has_value()&&turn_driver_.stage==TurnDriver::Stage::Failed; - 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&&!running_turn)|| - 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|| - 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; - // Re-entrancy flag: set while this dispatch runs (callbacks may re-enter), cleared on every exit. - 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. - GameState 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 save_stream(before.state)==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,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; - } - GameState 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,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 {};} -} - -// Opens the top scorers page (desk menu 20) for the active manager; refuses while the process -// timer context is active. For a national coach the club identity comes from the spare record. -// Returns the first page (goals, league scope) or an empty optional with 'error'. -std::optional CareerSession::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 == kNoTeam) { - // 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 >= world_layout().league_teams) { - throw FormatError("top scorers: manager team is outside Source league scope"); - } - if (stable_team < 0 || stable_team >= 138 || 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, 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 {}; - } -} - -// Applies one top scorers action: close, metric cycle (goals -> assists -> scorer -> goals) or -// scope toggle. Rejects a stale, replayed or modified owner; commits the new page on success. -std::optional CareerSession::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 || 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 == kNoTeam ? - (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 >= world_layout().league_teams || - 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 = 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 {}; - } -} - -// Statistics menu (desk menu 23): flips the manager's statistics preference flags. Needs the open -// menu owner request of the current revision and the expected current flag byte; allows exactly -// one metric bit (below 0x40) or the pair 0xc0 to change. Returns false with 'error' otherwise. -bool CareerSession::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; -} - -// Opens the opportunities page (desk menu 23) for the active manager. 'national_source_case' -// selects the national-team variant (team 0x165, league 0, identity supplied by the caller as -// 'stable_identity'). Needs the 320x240 desktop underlay. Empty optional with 'error' on failure. -std::optional CareerSession::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!=kNoTeam||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>=138||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=league_system().sizes[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,save_stream(g_),game_,rand_,national_source_case};++next_opportunities_scope_; - return page; - } catch(const std::exception& e){error=e.what();return {};} -} - -// Closes the opportunities page or selects one of its modes (1, 2, 4 or 8) and recomputes the -// rank table; stale or modified owners are rejected. -std::optional CareerSession::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||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!=kNoTeam|| - 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): - 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,save_stream(g_),game_,rand_,national_source_case}; - ++revision;return result; - } catch(const std::exception& e){error=e.what();return {};} -} - -// Opens the other-games overview (desk menu 5): validates the desk request and runs the entry -// changes on a staged copy (season-dependent selector byte, selector 12 insertion or removal), -// then builds the page for the remembered competition. The copy replaces the live state only -// once the page and owner exist. Empty optional with 'error' on failure. -std::optional CareerSession::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"); - - GameState 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) { - 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 >= 138 || 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 = 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 {}; - } -} - -// Applies one action of the other-games overview against the owner snapshot (a team info -// presenter may be supplied); empty optional with 'error' when the request or owner is stale. -std::optional CareerSession::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 || 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 CareerSession 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 >= 138 || 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"); - // Team info branch: the presenter runs against a staged copy (state, both random generators, - // runtime bytes) and the live session must come back unchanged; only then is the staged copy - // committed together with the redrawn page and the owner snapshot is refreshed. - 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"); - - GameState 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>=138||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=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 { - GameState 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; - // Page navigation actions (selector, linked page, previous/next round, display toggle): each is - // validated against what the current page offers, then the page is rebuilt on a staged copy. - 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 = 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 {}; - } -} - -// Balance plan group (desk menu 28): the plan is edited in a draft (BalanceDraft) that holds a -// copy of the state, random generators and runtime bytes. Pattern: open -> edit actions on the -// draft -> close; closing may stage a warning that needs a confirmation, and only the final -// close or confirmation moves the draft into the live state and bumps the revision. -// Opens the balance plan for the active manager's club; empty optional with 'error' on a stale, -// nested or unsupported opening (any other modal owner or dispatch counts as nested). -std::optional CareerSession::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_,{},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)}; - GameState 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=bmh::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 {};} -} - -// Applies one balance action to a copy of the draft: edit a row, cycle the view, take actual -// values, close, or confirm a staged warning close. Rejects a stale identity or a live state -// that differs from the draft's origin. Only a closing action commits the draft and bumps the -// revision; a staged warning keeps the draft open. Empty optional with 'error' on failure. -std::optional CareerSession::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|| - 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=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"); - cycle_balance_view(next.state,draft);break; - case ui::BalanceAction::take_actuals: - if(request.row!=-1||request.value)throw FormatError("balance: malformed reset action"); - 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; - GameState 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=bmh::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=original_badge_fallback(club,&exe_); - if(!notice.badge_fallback&&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 {};} -} - -// League pairings group (desk menu 1): like the balance plan it works on a draft copy -// (LeaguePairingsDraft) that remembers the active match groups and referee profiles of the turn -// driver, so a draft is only valid while those are unchanged. -// Opens the pairings page for the manager; empty optional with 'error' on a stale, nested or -// unsupported opening. -std::optional CareerSession::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_,{}, {}, - 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=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;} -} - -// Refuses to continue while the original's process timer is running (not implemented), then asks -// the pairings source for the active-match packet of the running groups and records the active -// group and phase in the owner. Returns the packet, or nothing when no match group is active. -std::optional CareerSession::validate_normal_pairings_group( - const GameState& 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=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)validate_league_pairings_active_packet_source(state,owner,*packet); - return packet; -} - -// Applies one pairings event (page change, computer tip, team info, close) to a copy of the -// draft. The live state must still equal the draft's origin (live_matches below). On close the -// draft is committed and the revision advances; otherwise a new page is returned and the draft -// refreshed. Empty optional with 'error' when stale, nested or a presenter stops. -std::optional CareerSession::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(); - // True while the live state, random counters, runtime bytes, match groups and referee profiles - // still equal what the draft started from. - 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=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 { -// Transfer editor / market group (helpers first). Projects the engine's transfer offer editor -// owner into the UI state: the quote fields, calculator profiles and, unless the editor is -// closed, the incoming-offer decision panel read from the four offer rows of the market list. -ui::OutgoingTransferEditorState transfer_offer_projection(const GameState& 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; -} -} - -// Public wrapper so other code (loan return offers) can reuse the editor projection. -ui::OutgoingTransferEditorState loan_return_offer_editor_projection( - const GameState& game, const TransferOfferEditorState& owner, uint64_t revision, bool gradient) { - return transfer_offer_projection(game, owner, revision, gradient); -} - -// Maps a UI field edit onto the engine's transfer offer editor edit and returns the new owner. -TransferOfferEditorState edit_transfer_offer_from_ui(GameState& game, - const TransferOfferEditorState& owner, const ui::OutgoingTransferRequest& request, - GameRandom& game_random, WatcomRandom& watcom_random) { - return edit_transfer_offer_editor_source(game, owner, - {TransferOfferEditorField(uint8_t(request.field)), request.value, request.accepted}, - game_random, watcom_random); -} - -// Transfer market request family (open offer, poach, editor events, quote preview, market -// actions): each entry validates the request revision, the active manager slot and the manager's -// club, refuses nested modals (market_dispatch_active_ and the other owners), works on copies of -// the state and both random generators and commits them only on success. The revision is -// advanced only where something observable changed. Failures return an empty optional and an -// error text. -// Opens the buyer's offer editor for a marked market row after checking the row identity -// against the market list in memory; the editor owner and its revision are stored on success. -std::optional CareerSession::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 != 2928 + 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 = 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; } -} - -// Starts a poaching attempt for a squad slot: the attempt draws random numbers, so the revision -// advances whenever the result is not invalid; a ready attempt also opens the offer editor on -// the special poach row and remembers the attempt in poach_. -std::optional CareerSession::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 = 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, 2928 + row, - result.start.player, next_state.memory.u16(::bmh::layout::EditorList + uint32_t(row) * 0x58 + 8), 0, false, true}; - auto owner = 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; } -} - -// Closes the table opened only to choose a poach target: needs an unchanged table owner, then -// restores the display word and drops the family owner without a family close. False with -// 'error' if stale. -bool CareerSession::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 || - 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; -} - -// Poach flow driven by UI callbacks: checks the request is a pristine open_poach request of the -// current revision (320x240 backdrop, nothing else open), then reports attempts-used or -// transfer-ban notices, or lets the player pick a squad player in a table on a cloned session -// and opens the poach from that choice. The UI acknowledges through 'accept'; any failure, -// including a session changed by the acknowledgement, restores the checkpoint and revision. -bool CareerSession::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. - CareerSession 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=club_player_detail_context(next,*selection); - slot=player.source_slot; - if(slot<0 || slot>=0xb70 || 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; - } -} - -// Applies one editor event (field quote change, submit, cancel, team info, player info) to the -// open offer editor: identity and quote must match the owner and the posted row must equal the -// single field change. Runs on copies; the revision rises only if state, runtime bytes or a -// random generator actually changed. A closing editor ends a poach attempt and clears the owner. -std::optional CareerSession::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 = 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=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=resume_transfer_offer_team_info_source(next_state,current,next_rand); - } else if(request.kind==ui::OutgoingTransferRequestKind::player_info) { - const auto selection=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=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 = 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_) finish_poach(next_state, *poach_); - const bool changed = save_stream(next_state) != 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; } -} - -// Quotes a purchase, lender snapshot or squad row preview (the listing identity is re-checked) -// using a copy of the W random stream; the stream and revision are updated only if the quote -// and its projection both succeed. -std::optional CareerSession::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 != 0xb70 + 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 = 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 = 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; - } -} - -// Direct market actions of a human manager: review offers, submit a bid, list a player. Needs -// a request of the current revision for the active manager's club; loans and marked batches are -// not accepted here. The allocator gate comes from the turn driver, never from the presenter. -// The staged copy is committed (revision plus one) only if something changed. -std::optional CareerSession::dispatch_transfer_market( - const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& presenters, - uint64_t& revision, std::string& error, - const std::function& review) { - 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::review_offers) { - if (!review || request.bid.manager != request.manager_slot || request.bid.list_entry < 0 || - request.bid.list_entry >= 40 || request.bid.source_slot != 0xb70 + request.bid.list_entry || - request.squad_row != -1 || !request.selected_players.empty()) { - error = "transfer market: invalid offer review"; return std::nullopt; - } - const auto view = project_transfer_offer_list(g_, request.bid.list_entry); - if (!view.valid || view.player != request.bid.player || view.seller != request.runtime_club || - view.seller_manager != request.manager_slot) { - error = "transfer market: stale seller listing"; return std::nullopt; - } - } else 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 = save_stream(g_); - TransferActionResult result; - if (request.kind == ui::TransferMarketRequestKind::review_offers) { - const auto view = project_transfer_offer_list(next_state, request.bid.list_entry); - result.player = view.player; result.list_entry = view.list_entry; - result.status = TransferActionStatus::pending; - // VERKAUFEN on a listed player: "Wollen Sie vom Transfermarkt holen?". Yes frees the list - // slot (the player stays in the squad), no goes on to the offers. - bool withdrawn = false; - if (request.ask_withdraw && hooks.confirm) { - const std::string question = message_text(next_state, ::bmh::layout::TransferMarket_WithdrawQuestion_TextPointer) + - next_state.player_name(view.player) + - message_text(next_state, ::bmh::layout::TransferMarket_WithdrawQuestion_TextPointer2); - if (hooks.confirm(next_state, request.manager_slot, question)) { - next_state.squad_slots.at(0xb70u + size_t(view.list_entry)) = 0xfff; - withdrawn = true; - } - } - const int selected = !withdrawn && view.offer_count ? review(next_state, view) : -1; - if (selected != -1) { - auto allocator = TransferAllocatorContext::unsupported; - if (turn_driver_.transfer_allocator_context == PendingOfferAllocatorGate::zero) - allocator = TransferAllocatorContext::zero; - else if (turn_driver_.transfer_allocator_context == PendingOfferAllocatorGate::blocked) - allocator = TransferAllocatorContext::blocked; - result = accept_manager_transfer_offer(next_state, request.manager_slot, - view.list_entry, view.player, selected, next_rand, report, allocator); - } - } else if (request.kind == ui::TransferMarketRequestKind::list_player) - result = list_manager_player(next_state, request.manager_slot, request.squad_row, next_rand, report); - else - result = 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 = 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; - } -} - // Finishes the career setup after all managers are chosen: refuses while a modal owner is open // and runs the season setup and first steps with calendar_advance_active_ set (restored by // AdvanceReset). Returns false with 'error' (the engine's reason) on failure. @@ -4763,3305 +1120,6 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request return result; } - -// Mailbox actions on one of the 40 entries for the active manager: keep toggle or delete. The -// request must carry the current revision, the active manager slot and the expected entry bytes -// (stale entries are refused); the manager's bit in the recipient or kept word is flipped and the -// revision advances. Returns false with a player-visible German text in 'error' otherwise. -bool CareerSession::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; -} - -// Returns the mailbox page when the active human manager still has the notification bit set, -// nothing otherwise (no change of state). -std::optional CareerSession::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)] == kNoTeam || !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); -} - -// Acknowledges closing the mailbox for the active manager: clears only that manager's -// notification bit (kept outside the saved data, so the revision is not advanced). -bool CareerSession::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; -} - -// Settings group (desk settings, live settings, settings files). The options grid has 20 rows x 9 -// columns stored as 180 bytes: columns 0-6 are two-state switches, 7 and 8 numeric steppers. -// Write of one cell: refuses while a scoped settings owner is open unless called by it, checks -// the active manager, revision and that the posted raw block still equals the saved one, then -// applies the allowed edit (locks and original limits respected) and bumps the revision. -// Returns false with a player-visible German text in 'error' otherwise. -bool CareerSession::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) { - // The original edits every unlocked switch: the page only stores the value and each - // consumer reads it where it needs it. A switch without a consumer in OpenBMH yet is still - // stored (and saved) and never refused. Locks (bit 7 of the entry-time availability) and - // values other than 0/1 are refused above and below. - if (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 { - // The numeric columns are stored the same way; values from 200 up are blank cells. - if (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; -} - -// Opens the settings page from a running match (the 'S' request): only inside a calendar advance -// with the engine bound to this session, the manager at the active desk and no other modal -// owner. Works on a staged copy of the state and runtime bytes, commits it together with the new -// owner and revision on success; empty optional with 'error' on failure. -std::optional CareerSession::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 CareerSession::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||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_; - // Scope guard: calendar_advance_active_ is off while the nested settings code runs and is - // restored on exit. - 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); - GameState 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"); - GameState 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"); - GameState 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 write / file / -// close actions that must find the owner snapshot unchanged -> close. -// Captures state, runtime bytes, owner and scope counter so the UI flow can roll back. -CareerSession::DeskSettingsCheckpoint CareerSession::desk_settings_checkpoint(uint64_t revision) const { - return {g_,club_modal_runtime_,desk_settings_owner_ ? - std::optional(desk_settings_owner_->owner) : std::nullopt, - desk_settings_owner_ ? desk_settings_owner_->initial_h8 : uint8_t(0), - next_desk_settings_scope_,revision}; -} - -// Loads or saves the 180-byte settings block as a .ein file on a staged state (const: it never -// touches the live state). Validates owner fields, extension, symlink and size; save refuses an -// existing file without the overwrite flag. Returns false with a short error code in 'error'; -// 'loaded' tells whether a load changed the staged state. -bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int manager_slot,int origin_item_id, - GameState& 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!=".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=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; -} - -// Restores a desk settings checkpoint: state, runtime bytes, owner (with a fresh snapshot), -// scope counter and revision. -void CareerSession::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=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; -} - -// Opens the desk settings page from menu item 19: the request must name an enabled menu-19 item -// of the current revision for the active manager and no other owner, dispatch or calendar advance -// may be active. Works on a staged copy that is committed with the owner on success; empty -// optional with 'error' otherwise. -std::optional CareerSession::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 {}; - } - GameState staged=g_;auto runtime=club_modal_runtime_; - std::array raw{}; - for(size_t i=0;i CareerSession::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|| - 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); - GameState 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"); - GameState 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=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; - } - // Close: validates owner and revision. When the stepper at row 7 column 7 changed, the 32-bit - // runtime counter after it is reset (new value 0) or shifted by 60 per step; the live-scene - // flag and other latches are derived from the switches and the owner is dropped. - const auto& close=std::get(action); - if(close.owner!=current.owner||close.owner.revision!=revision) - throw FormatError("desk settings: stale close request"); - GameState 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 {}; - } -} - -// Advertising group: renewal check/answer, offers and spending. Pattern: the UI sends an -// AdvertisingRequest with request id (must increase), revision, manager slot and club; the -// session validates against the active manager, applies the change on the live state inside a -// checkpoint (apply_advertising rolls everything back if validation, the action or the -// acknowledgement fails) and bumps the revision. -// Simple renewal check for the active manager; the revision is bumped unless the contract has -// not expired. Returns nothing with a German 'error' text if stale or invalid. -std::optional CareerSession::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 = bmh::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; -} - -// Answers an offered renewal (renew or decline) for the active manager and bumps the revision; -// false with a German 'error' text if the request is stale. -bool CareerSession::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() || - !bmh::answer_advertising_renewal(g_, manager_slot, contract_slot, renew)) { - error = "Diese Vertragsverlängerung ist nicht mehr aktuell."; - return false; - } - ++revision; - return true; -} - - - -// Copies nearly the whole session (state, random generators, turn driver, every modal owner, -// dispatch flags, scope counters, runtime bytes and the given revision) for rollback and for the -// "nothing changed" comparison below. Also used outside advertising, e.g. around the kickoff. -CareerSession::AdvertisingSessionCheckpoint CareerSession::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; -} - -// Puts back everything advertising_session_checkpoint captured (the caller restores the -// revision itself). -void CareerSession::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); -} - -// True when the live session equals the checkpoint in saved state, random counters, turn driver -// stage, owners, flags, scope counters and revision; used to detect a callback that changed the -// session behind the engine's back. -bool CareerSession::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 save_stream(g_)==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; -} - -// Renewal question with a UI presenter. Refuses a competing owner or dispatch (competing_owner) -// and a stale request (increasing request id, active manager, club, revision, contract bytes). -// The presenter runs on a staged copy; the session is always restored after it, and only the -// staged result of the confirmed answer becomes live (revision plus one). Returns nothing with a -// German 'error' text on failure. -std::optional CareerSession::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 { - GameState staged = g_; - WatcomRandom staged_rand = rand_; - auto renewal = bmh::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 (!bmh::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; - } -} - -// Entry point for advertising requests: runs the renewal or the offer/spending dispatch and then -// the acknowledgement callback; any failure or exception restores the advertising checkpoint and -// the old revision (exceptions are rethrown). -bool CareerSession::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; - } -} - -// Builds an accept_offer request from the page the player saw and applies it; false with 'error' -// if the displayed offer no longer exists. -bool CareerSession::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); -} - -// Builds a set_spending request for budget slots 16-18 from the observed page and applies it; -// the observed amount and delivery weeks are sent as the expected values. -bool CareerSession::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; }); -} - -// Validates an offer or spending request (no modal owner open, active manager and club, current -// revision, a request id greater than the last one) and applies it to the live state. The -// renewal kind is refused here; it goes through dispatch_advertising_renewal. False with a -// German 'error' text otherwise. -bool CareerSession::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 = 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 = 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; -} - -// Contract group (negotiation at the desk). Flow: request_demands creates a quote (contract_quote_) -// that binds the follow-up requests (offer, bonuses, insurance) by quote id, row and player; -// each follow-up must carry a higher request id and the quote's revision. State changes happen on -// staged copies and are committed together with the revision bump. -// Validates request id (must increase), revision, active manager and club (not the national team) -// and the squad row against the player id; rejects with a German 'error' text and returns false. -// On success it fills 'result' (quote id, demands, accepted flag and original feedback text). -bool CareerSession::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; } - // Sets the player-visible error text and returns 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 == kNoTeam) - 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."); - GameState staged_game = g_; - WatcomRandom staged_rand = rand_; - std::array demands{}; - try { demands = contract_demands(staged_game, active, request.row, true, staged_rand); } - catch (const std::exception&) { return reject("Die Gehaltsforderungen konnten nicht ermittelt werden."); } - if (save_stream(staged_game) != 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)); - GameState staged_game = g_; - if (!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."); - GameState staged_game = g_; - const bool accepted = 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."); - GameState staged_game = g_; - WatcomRandom staged_rand = rand_; - bool accepted = false; - try { - accepted = 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; -} - -// Common check for desk setting changes (ticket price, automation): no modal owner open, career -// not complete, optionally the desk phase (no calendar advance or pending dispatch), and the -// identity must match the active manager, revision, club and stable club identity. Sets a short -// error code and returns false otherwise. -bool CareerSession::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 > kNoTeam || 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; -} - -// Writes one desk setting for 'manager': the ticket price (admission 8-25, not for the national -// team) or automation option 'index' (0 = saved formation 0-8 limited to the saved formation -// mask, 1-3 flags, 4 training automation not for the national team). Sets 'error' on a rejected -// value; does not bump the revision (the caller does). -bool CareerSession::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)] == kNoTeam; - 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; -} - -// The stored search profile of a manager slot (all zero for an invalid slot). -SearchProfile CareerSession::search_profile(int manager) const { return bmh::search_profile(g_, manager); } - -// The profile "Vorschlag" proposes for the manager's squad; nothing is stored. -SearchProfile CareerSession::suggest_search_profile(int manager, bool whole_squad) const { - return bmh::suggest_search_profile(g_, manager, whole_squad); -} - -// Stores an edited search profile like the closing dialog does and, with `apply`, returns the transfer-list entries -// that fit it. Only the active manager of a club with a transfer market may do this, and not while another window -// owns the session. The revision rises only when the stored bytes changed. -std::optional CareerSession::dispatch_search_profile(int manager, - const SearchProfile& profile, bool cancelled, bool apply, 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_ || transfer_offer_editor_ || market_dispatch_active_ || - pending_offer_dispatch_active_ || calendar_advance_active_) { error = "search_profile_blocked"; return std::nullopt; } - if (manager < 0 || size_t(manager) >= g_.manager_teams.size() || g_.manager_teams[size_t(manager)] == kNoTeam || - !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != manager || - revision == std::numeric_limits::max()) { error = "invalid_search_profile_owner"; return std::nullopt; } - if (!search_profile_valid(profile)) { error = "invalid_search_profile"; return std::nullopt; } - const auto before = bmh::search_profile(g_, manager); - SearchProfileDispatch result; - result.active = set_search_profile(g_, manager, profile, cancelled); - const auto stored = bmh::search_profile(g_, manager); - result.profile = stored; - if (stored != before) ++revision; - if (apply) result.hits = search_profile_hits(g_, manager); - error.clear(); - return result; -} - -// Validates the owner and the price range (8-25) and applies the ticket price; revision plus one. -bool CareerSession::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; -} - -// Validates the owner and applies one automation switch (formation automation needs a formation -// 1-8 exactly when enabled); revision plus one. -bool CareerSession::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; -} - -// Desk widget click (ticket price or automation option): the request must belong to a visible, -// enabled desk item of the matching kind; the new value is derived here (formation automation -// cycles to the next available formation, flags toggle) and applied; revision plus one. -bool CareerSession::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; - // Refuse malformed saved formation state before projecting widget ownership. - // The desktop renderer cannot project indices outside the stored 0..8 range. - if (g_.manager_options[size_t(active) * 5] > 8) { - error = "invalid_saved_formation_automation"; 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 and enabled MEN drawer/item; the frame bit is optional. - 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.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; -} - -// Desk layout editing (move an item, open or close a quick-bar drawer, send items to or -// restore them from a folder or bin). The desk is 54 item records of 16 bytes per manager. The -// request carries the layout before and after; this function checks that "before" equals the live -// bytes, recomputes the expected "after" for the operation itself, requires an exact match, and -// verifies the resulting desktop projection before committing (revision plus one). Any -// mismatch returns false with a short error code and changes nothing. -bool CareerSession::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; - } - // Each case rebuilds 'expected' (the layout bytes after the operation) from the live layout: - // bounds and optional grid snapping for moves, linked list chain edits (offsets +5/+6) for - // drawers, folders and the bin. - 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_visible=false; - for(size_t item=1;item=int(kItems)) break; - cursor=next; - } - if(owner_visible) break; - } - if(!owner_visible) { error="desk_folder_child_owner_hidden"; 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_visible=false; - for(size_t item=1;item=int(kItems)) break; - cursor=next; - } - if(owner_visible)break; - } - if(!owner_visible) { error="desk_bin_restore_folder_hidden";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; } - GameState 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; -} - -// Lineup requests of the active manager (refused during a calendar advance or pending offer -// dispatch). prepare_lineup builds the lineup entry on a staged copy and accepts it only when -// the first eleven squad rows form a valid authoritative lineup. -bool CareerSession::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) { - GameState 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. - 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; - } - // Swap path: only allowed after prepare_lineup for the same manager and club. The two rows must - // still hold the slots and players the UI saw; injured players and the foreign-player rule are - // refused until their dialogs exist. The swap exchanges squad slots (keeping the role bits with - // the row) and tactic board entries, re-syncs the card row ids and switches the manager's - // formation automation off. - 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; -} - -// Live overview dispatch (pattern open -> dispatch -> acknowledge): applies one action of the -// overview opened by open_running_overview. Requires an active calendar advance, the owner of the -// current revision and an engine that is still bound to this session with unchanged match groups -// and referees. The action variant selects the child: league family navigation or control, -// strengths, pairings or the cup other-games page. Close actions end the owner and return a -// preparation projection; a failure returns an empty optional with 'error'. -std::optional CareerSession::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_; - // Scope guard: calendar_advance_active_ is off while the family code runs and is restored on exit. - 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_,{}, {}, - 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=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; - // The opposite guard: sets calendar_advance_active_ for the nested table/pairings navigation, - // which expects to run inside the advance, and restores the value afterwards. - 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 {}; - } -} - -// Live intervention group (lineup changes during a running match). Pattern: begin stores a -// LiveInterventionCheckpoint (state, match groups, both random generators, revision), the -// substitution requests work against it, finish rerates the team and bumps the revision, abort -// puts everything back. -// Begin: only after minute 2, source mode 2 or 8, for a human manager whose team plays in the -// current match. Mode 2 also runs the lineup entry preparation. Returns false with a German -// 'error' text and no open intervention otherwise. -bool CareerSession::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 { - GameState 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; -} - -// Begin for an automatic intervention caused by a match event (kind 1 or 2): the event must match -// the engine's current group, match, side and teams, the manager must have the automatic -// option on, and the affected player must show the expected status. Opens the lineup entry like -// mode 2; false with 'error' otherwise. -bool CareerSession::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 { - GameState 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; -} - -// Ends an event intervention: the open checkpoint must belong to exactly this event and the -// engine groups must be unchanged. Only consumes the owner and bumps the revision (the rerate -// belongs to the event itself). -bool CareerSession::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; -} - -// Ends a normal intervention: rerates the team on a staged engine copy; on success the staged -// state, groups and generators replace the live ones and the revision advances, on a rerate -// failure or exhausted revision the checkpoint is restored. False with a German 'error' text. -bool CareerSession::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_; - GameState 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; -} - -// Abandons the matching open intervention and restores state, groups, random generators and the -// revision from its checkpoint. Does nothing if no matching intervention is open. -void CareerSession::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(); -} - -// Applies one swap of the open live intervention (mode 2 only): checks owner, revision, manager, -// team and that the rows still hold the shown slots and players, whether it is a same-zone -// exchange or a field/bench substitution, and the injury status of both players (some notices -// are reported as "source_notice" codes in 'error'). False with 'error' on any failure. -bool CareerSession::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 (nationality(g_, slot & 0x0fff) != 0) ++foreign_on_field; - } - foreign_on_field -= nationality(g_, field_player) != 0; - foreign_on_field += 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. - GameState 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; -} - -// Wraps dispatch_live_substitution: applied, a "source_notice" status carrying the original -// notice address parsed from the error text, or rejected with the error text. -LiveSubstitutionResult CareerSession::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)}; -} - -// Sets one tactic option during the open live intervention (source mode 8, after minute 2): the -// intervention owner, revision, manager, team and current match must match, the value must be in -// range and available. Only the manager record bytes change; revision plus one and the open -// intervention's current revision follows. False with a German 'error' text otherwise. -bool CareerSession::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; -} - -// Pitch (lineup screen) group: all pitch actions (swap, move player, weights, formations, -// set piece editor and takers, player orders, marking, page switches). A swap is forwarded to -// dispatch_lineup. Everything else is checked against the display word, the saved set piece -// signature and the expected old values in the request, applied on a staged copy of the state -// and committed with a revision bump. False with a German 'error' text or a short code otherwise. -bool CareerSession::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. - // True when the request belongs to the open live lineup intervention (same manager, team and - // revision); such requests are authorised by that owner instead of by the desk phase. - 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; - // True during the very first lineup window before the first desk exists (driver stage Empty). - 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 { - GameState 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; -} - -// Pitch request during a live intervention: needs the matching open intervention (mode 2) and -// current revision. Formation and weight controls exist only in the initial preparation and are -// refused here; the rest goes to dispatch_pitch. -bool CareerSession::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); -} - -// Result-style wrapper: swaps return the substitution result (with source notices), other pitch -// actions return applied or rejected with the error text. -LiveSubstitutionResult CareerSession::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)}; -} - -// Desk-time swap only; any other pitch kind is refused. -bool CareerSession::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); -} - -// Preparation (match day) projection of the live state at 'revision'; read-only. -ui::PreparationState CareerSession::preparation_projection(uint64_t revision) const { - return preparation_projection(g_, revision); -} - -// Returns the opponent team of the manager's prepared lineup entry (from the captured desk call -// arguments, confirmed against the desk projection), or nothing when the manager is not the -// active prepared one, the day has no ordinary opponent or any check fails. Read-only. -std::optional CareerSession::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 == kNoTeam || 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 = day_competitions(g_, turn_driver_.calendar_entry); - if (competitions == 0x800000) competitions = 0; - const int default_competition = competitions != 0 ? 34 : 33; - GameState 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) * kLeagueResultsStride + 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; -} - -// Builds the preparation projection of 'state' and layers the session-owned extras on top: the -// desktop, the lineup "entry prepared" flag and pitch extras, the bank notices and the stadium -// page including its open dialogs (construction tip, periphery quote, block expansion editor) -// when the stadium owner belongs to this exact manager, club and revision. Read-only. -// Throws FormatError when the manager's league cannot be found. -ui::PreparationState CareerSession::preparation_projection(const GameState& 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; -} - -// Training group: one request changes the types, areas, automation byte or one player's -// intensity or focus of the active manager. The request carries the desired result; it is -// validated against the current projection (stale manager, plan limits, expected values), applied -// on a staged copy and committed with revision plus one. Manual edits clear the matching -// assistant flag and never draw random numbers; initialize and enabling automation run the -// automatic training. Returns false with a short error code in 'error' otherwise. -bool CareerSession::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; - } - - GameState 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) 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; - } -} - // Captures, for every manager slot, the competition id and opponent shown at the desk today // (defaults 33/34, or 32 at season end; no opponent). Only done while the driver is at a desk // stage; the values are kept in source_desk_callargs_ and later used to authenticate lineup @@ -8351,610 +1409,6 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin return true; } -// Training camp group: set_focus changes the four focus bytes of the active manager (an unchanged -// or invalid focus is refused); book books a resort for the week after checking the focus the UI -// saw, the weekly/visit limits and the funds (the booking draws random numbers). Refused while a -// modal owner is open or when the manager slot, club or revision is stale; revision plus one on -// success, short error codes in 'error' otherwise. -bool CareerSession::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 (!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 (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 (!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; -} - -// Bank group: deposit moves, share and fund trades, stock tips and bank credit. Needs the active -// manager, club and current revision and no modal owner open. Every branch validates amounts and -// counts against the manager record and the stock/fund blocks, then applies the change to the -// live state and bumps the revision once. The notices of the last property purchase or credit -// refund are kept for the next projection. Returns false with a short error code otherwise. -bool CareerSession::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; - } - 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 > 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 (!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; } - 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_ = 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 > max_fund_units(g_, request.manager_slot, request.asset_index)) { - error = "invalid_fund_count"; return false; - } - const int32_t additional_cost = 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; } - 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 = 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; -} - -// True when a construction tip dialog is open and the process timer (when running) has no time -// left; read-only. -bool CareerSession::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; -} - -// Stadium group: an owner (stadium_) is opened with a scope id and every later request must echo -// scope and sequence, the manager, club, stable club identity, game mode and revision. All -// actions (data page, periphery quote/build, block expansion editor with its tip, investments) -// run inside the apply lambda below; on failure the stadium checkpoint is restored, on success -// revision, sequence and the owner's revision advance. Exceptions restore the checkpoint and -// the revision and are rethrown. Short error codes in 'error' otherwise. -// Older periphery callers send no scope envelope; a compatibility step fills it in for their four -// original operations only. -bool CareerSession::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 >= 357 || - 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 { - // Performs the validated stadium action and returns true on success; 'invalid' records the - // reason and returns false. - 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 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 = 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 = 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 = 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"); - const auto block_constants=stadium_block_expansion_constants(exe_); - const auto quote_block = [&](StadiumBlockSlot slot, uint32_t total, uint8_t features) { - return 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 = 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; - resolve_stand_block_offer(resolved, request.accept_tip, rand_); - const bool built = 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 = 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; - resolve_stand_block_offer(resolved, request.accept_tip, rand_); - const bool built = 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; - } -} - -// Submits a pools coupon for the active manager; only valid when the coupon has eleven matches. -// Revision plus one; false with a short error code otherwise. -bool CareerSession::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 (!submit_pools_coupon(g_, request.manager_slot, request.stake, request.tips)) { - error = "invalid_toto_coupon"; return false; - } - ++revision; - return true; -} - -} // namespace bmh::app - -namespace bmh::app { - // Group: presenter hooks. Returns the hooks with the allocator gate taken from the turn driver, // so presenters can never decide it. PendingOfferHooks CareerSession::pending_hooks_for_dispatch(PendingOfferHooks hooks) const { diff --git a/src/app/career_session_club.cpp b/src/app/career_session_club.cpp new file mode 100644 index 0000000..5f45b90 --- /dev/null +++ b/src/app/career_session_club.cpp @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: the club information dialogs (club, player list, player detail) and their services. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +// Club-information modal family (enter, change category, player redraw, national action, +// pending offers): each member refuses to run while another modal owner is open and clears +// 'error' first. The ones that change state work on copies and assign them back only after +// success. +// Enter: opens the club info entry for 'team'; nullopt plus 'error' on an invalid team. +std::optional CareerSession::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 prepare_club_info_entry(g_, team); } + catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } +} + +// Switches the club info category for 'team'; nullopt plus 'error' when it is invalid. +std::optional CareerSession::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 set_club_info_category(g_, team, requested); } + catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } +} + +// Redraws a player detail card; random generators advance only if the redraw succeeded. +std::optional CareerSession::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 = 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; + } +} + +// Applies the national-team add/remove action of a player card on a staged copy; the copy is +// committed only when the engine reports no reason. Returns whether the action was applied. +std::optional CareerSession::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 = 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; + } +} + +// Processes the pending transfer offers of a player card. Rejects a stale revision or a nested +// pending-offer/market dispatch, works on copies and commits them when at least one offer was +// processed. The revision is bumped here unless a calendar advance is active: then the outer +// driver publishes the revision when it returns. +std::optional CareerSession::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 = 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; + } +} + +// Seeds the process-only byte map used by the club modals with their start values from the +// executable; these values are never written to a save. +void CareerSession::initialize_club_modal_runtime() { + // Setup clears the boot-only dialog mode before either creating or loading + // a career. This process flag is deliberately absent from native saves. + club_modal_runtime_.emplace(layout::CompactDialogFrame, 0); + // 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)); +} + +// Collects the executable bytes and rating tables the Sportschau screen reads. +SportschauSourceOptions CareerSession::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_)}; +} + +// Builds the service callbacks of the club modal on a given (staged) state, generators and +// runtime byte map, so the modal can run on a copy and be committed or dropped by the caller. +ClubModalServices CareerSession::staged_club_modal_services(GameState& 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]() -> GameState& { return *g; }; + services.enter_club=[g](int team) { return prepare_club_info_entry(*g,team); }; + services.change_category=[g](int team,int category) { return 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=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=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=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; +} + +// Same services bound to the live state (non-transactional); pending offers go through +// dispatch_club_player_pending_offers. Throws when another modal owner is open. +ClubModalServices CareerSession::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 bmh::app diff --git a/src/app/career_session_desk.cpp b/src/app/career_session_desk.cpp new file mode 100644 index 0000000..762bfca --- /dev/null +++ b/src/app/career_session_desk.cpp @@ -0,0 +1,1605 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: the desk: mailbox, settings, advertising, contracts, desk settings, search profile, widgets, layout. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +// Mailbox actions on one of the 40 entries for the active manager: keep toggle or delete. The +// request must carry the current revision, the active manager slot and the expected entry bytes +// (stale entries are refused); the manager's bit in the recipient or kept word is flipped and the +// revision advances. Returns false with a player-visible German text in 'error' otherwise. +bool CareerSession::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; +} + +// Returns the mailbox page when the active human manager still has the notification bit set, +// nothing otherwise (no change of state). +std::optional CareerSession::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)] == kNoTeam || !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); +} + +// Acknowledges closing the mailbox for the active manager: clears only that manager's +// notification bit (kept outside the saved data, so the revision is not advanced). +bool CareerSession::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; +} + +// Settings group (desk settings, live settings, settings files). The options grid has 20 rows x 9 +// columns stored as 180 bytes: columns 0-6 are two-state switches, 7 and 8 numeric steppers. +// Write of one cell: refuses while a scoped settings owner is open unless called by it, checks +// the active manager, revision and that the posted raw block still equals the saved one, then +// applies the allowed edit (locks and original limits respected) and bumps the revision. +// Returns false with a player-visible German text in 'error' otherwise. +bool CareerSession::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) { + // The original edits every unlocked switch: the page only stores the value and each + // consumer reads it where it needs it. A switch without a consumer in OpenBMH yet is still + // stored (and saved) and never refused. Locks (bit 7 of the entry-time availability) and + // values other than 0/1 are refused above and below. + if (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 { + // The numeric columns are stored the same way; values from 200 up are blank cells. + if (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; +} + +// Opens the settings page from a running match (the 'S' request): only inside a calendar advance +// with the engine bound to this session, the manager at the active desk and no other modal +// owner. Works on a staged copy of the state and runtime bytes, commits it together with the new +// owner and revision on success; empty optional with 'error' on failure. +std::optional CareerSession::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 CareerSession::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||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_; + // Scope guard: calendar_advance_active_ is off while the nested settings code runs and is + // restored on exit. + 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); + GameState 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"); + GameState 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"); + GameState 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 write / file / +// close actions that must find the owner snapshot unchanged -> close. +// Captures state, runtime bytes, owner and scope counter so the UI flow can roll back. +CareerSession::DeskSettingsCheckpoint CareerSession::desk_settings_checkpoint(uint64_t revision) const { + return {g_,club_modal_runtime_,desk_settings_owner_ ? + std::optional(desk_settings_owner_->owner) : std::nullopt, + desk_settings_owner_ ? desk_settings_owner_->initial_h8 : uint8_t(0), + next_desk_settings_scope_,revision}; +} + +// Loads or saves the 180-byte settings block as a .ein file on a staged state (const: it never +// touches the live state). Validates owner fields, extension, symlink and size; save refuses an +// existing file without the overwrite flag. Returns false with a short error code in 'error'; +// 'loaded' tells whether a load changed the staged state. +bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int manager_slot,int origin_item_id, + GameState& 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!=".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=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; +} + +// Restores a desk settings checkpoint: state, runtime bytes, owner (with a fresh snapshot), +// scope counter and revision. +void CareerSession::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=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; +} + +// Opens the desk settings page from menu item 19: the request must name an enabled menu-19 item +// of the current revision for the active manager and no other owner, dispatch or calendar advance +// may be active. Works on a staged copy that is committed with the owner on success; empty +// optional with 'error' otherwise. +std::optional CareerSession::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 {}; + } + GameState staged=g_;auto runtime=club_modal_runtime_; + std::array raw{}; + for(size_t i=0;i CareerSession::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|| + 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); + GameState 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"); + GameState 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=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; + } + // Close: validates owner and revision. When the stepper at row 7 column 7 changed, the 32-bit + // runtime counter after it is reset (new value 0) or shifted by 60 per step; the live-scene + // flag and other latches are derived from the switches and the owner is dropped. + const auto& close=std::get(action); + if(close.owner!=current.owner||close.owner.revision!=revision) + throw FormatError("desk settings: stale close request"); + GameState 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 {}; + } +} + +// Advertising group: renewal check/answer, offers and spending. Pattern: the UI sends an +// AdvertisingRequest with request id (must increase), revision, manager slot and club; the +// session validates against the active manager, applies the change on the live state inside a +// checkpoint (apply_advertising rolls everything back if validation, the action or the +// acknowledgement fails) and bumps the revision. +// Simple renewal check for the active manager; the revision is bumped unless the contract has +// not expired. Returns nothing with a German 'error' text if stale or invalid. +std::optional CareerSession::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 = bmh::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; +} + +// Answers an offered renewal (renew or decline) for the active manager and bumps the revision; +// false with a German 'error' text if the request is stale. +bool CareerSession::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() || + !bmh::answer_advertising_renewal(g_, manager_slot, contract_slot, renew)) { + error = "Diese Vertragsverlängerung ist nicht mehr aktuell."; + return false; + } + ++revision; + return true; +} + +// Copies nearly the whole session (state, random generators, turn driver, every modal owner, +// dispatch flags, scope counters, runtime bytes and the given revision) for rollback and for the +// "nothing changed" comparison below. Also used outside advertising, e.g. around the kickoff. +CareerSession::AdvertisingSessionCheckpoint CareerSession::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; +} + +// Puts back everything advertising_session_checkpoint captured (the caller restores the +// revision itself). +void CareerSession::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); +} + +// True when the live session equals the checkpoint in saved state, random counters, turn driver +// stage, owners, flags, scope counters and revision; used to detect a callback that changed the +// session behind the engine's back. +bool CareerSession::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 save_stream(g_)==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; +} + +// Renewal question with a UI presenter. Refuses a competing owner or dispatch (competing_owner) +// and a stale request (increasing request id, active manager, club, revision, contract bytes). +// The presenter runs on a staged copy; the session is always restored after it, and only the +// staged result of the confirmed answer becomes live (revision plus one). Returns nothing with a +// German 'error' text on failure. +std::optional CareerSession::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 { + GameState staged = g_; + WatcomRandom staged_rand = rand_; + auto renewal = bmh::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 (!bmh::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; + } +} + +// Entry point for advertising requests: runs the renewal or the offer/spending dispatch and then +// the acknowledgement callback; any failure or exception restores the advertising checkpoint and +// the old revision (exceptions are rethrown). +bool CareerSession::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; + } +} + +// Builds an accept_offer request from the page the player saw and applies it; false with 'error' +// if the displayed offer no longer exists. +bool CareerSession::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); +} + +// Builds a set_spending request for budget slots 16-18 from the observed page and applies it; +// the observed amount and delivery weeks are sent as the expected values. +bool CareerSession::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; }); +} + +// Validates an offer or spending request (no modal owner open, active manager and club, current +// revision, a request id greater than the last one) and applies it to the live state. The +// renewal kind is refused here; it goes through dispatch_advertising_renewal. False with a +// German 'error' text otherwise. +bool CareerSession::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 = 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 = 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; +} + +// Contract group (negotiation at the desk). Flow: request_demands creates a quote (contract_quote_) +// that binds the follow-up requests (offer, bonuses, insurance) by quote id, row and player; +// each follow-up must carry a higher request id and the quote's revision. State changes happen on +// staged copies and are committed together with the revision bump. +// Validates request id (must increase), revision, active manager and club (not the national team) +// and the squad row against the player id; rejects with a German 'error' text and returns false. +// On success it fills 'result' (quote id, demands, accepted flag and original feedback text). +bool CareerSession::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; } + // Sets the player-visible error text and returns 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 == kNoTeam) + 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."); + GameState staged_game = g_; + WatcomRandom staged_rand = rand_; + std::array demands{}; + try { demands = contract_demands(staged_game, active, request.row, true, staged_rand); } + catch (const std::exception&) { return reject("Die Gehaltsforderungen konnten nicht ermittelt werden."); } + if (save_stream(staged_game) != 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)); + GameState staged_game = g_; + if (!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."); + GameState staged_game = g_; + const bool accepted = 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."); + GameState staged_game = g_; + WatcomRandom staged_rand = rand_; + bool accepted = false; + try { + accepted = 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; +} + +// Common check for desk setting changes (ticket price, automation): no modal owner open, career +// not complete, optionally the desk phase (no calendar advance or pending dispatch), and the +// identity must match the active manager, revision, club and stable club identity. Sets a short +// error code and returns false otherwise. +bool CareerSession::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 > kNoTeam || 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; +} + +// Writes one desk setting for 'manager': the ticket price (admission 8-25, not for the national +// team) or automation option 'index' (0 = saved formation 0-8 limited to the saved formation +// mask, 1-3 flags, 4 training automation not for the national team). Sets 'error' on a rejected +// value; does not bump the revision (the caller does). +bool CareerSession::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)] == kNoTeam; + 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; +} + +// The stored search profile of a manager slot (all zero for an invalid slot). +SearchProfile CareerSession::search_profile(int manager) const { return bmh::search_profile(g_, manager); } + +// The profile "Vorschlag" proposes for the manager's squad; nothing is stored. +SearchProfile CareerSession::suggest_search_profile(int manager, bool whole_squad) const { + return bmh::suggest_search_profile(g_, manager, whole_squad); +} + +// Stores an edited search profile like the closing dialog does and, with `apply`, returns the transfer-list entries +// that fit it. Only the active manager of a club with a transfer market may do this, and not while another window +// owns the session. The revision rises only when the stored bytes changed. +std::optional CareerSession::dispatch_search_profile(int manager, + const SearchProfile& profile, bool cancelled, bool apply, 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_ || transfer_offer_editor_ || market_dispatch_active_ || + pending_offer_dispatch_active_ || calendar_advance_active_) { error = "search_profile_blocked"; return std::nullopt; } + if (manager < 0 || size_t(manager) >= g_.manager_teams.size() || g_.manager_teams[size_t(manager)] == kNoTeam || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != manager || + revision == std::numeric_limits::max()) { error = "invalid_search_profile_owner"; return std::nullopt; } + if (!search_profile_valid(profile)) { error = "invalid_search_profile"; return std::nullopt; } + const auto before = bmh::search_profile(g_, manager); + SearchProfileDispatch result; + result.active = set_search_profile(g_, manager, profile, cancelled); + const auto stored = bmh::search_profile(g_, manager); + result.profile = stored; + if (stored != before) ++revision; + if (apply) result.hits = search_profile_hits(g_, manager); + error.clear(); + return result; +} + +// Validates the owner and the price range (8-25) and applies the ticket price; revision plus one. +bool CareerSession::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; +} + +// Validates the owner and applies one automation switch (formation automation needs a formation +// 1-8 exactly when enabled); revision plus one. +bool CareerSession::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; +} + +// Desk widget click (ticket price or automation option): the request must belong to a visible, +// enabled desk item of the matching kind; the new value is derived here (formation automation +// cycles to the next available formation, flags toggle) and applied; revision plus one. +bool CareerSession::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; + // Refuse malformed saved formation state before projecting widget ownership. + // The desktop renderer cannot project indices outside the stored 0..8 range. + if (g_.manager_options[size_t(active) * 5] > 8) { + error = "invalid_saved_formation_automation"; 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 and enabled MEN drawer/item; the frame bit is optional. + 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.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; +} + +// Desk layout editing (move an item, open or close a quick-bar drawer, send items to or +// restore them from a folder or bin). The desk is 54 item records of 16 bytes per manager. The +// request carries the layout before and after; this function checks that "before" equals the live +// bytes, recomputes the expected "after" for the operation itself, requires an exact match, and +// verifies the resulting desktop projection before committing (revision plus one). Any +// mismatch returns false with a short error code and changes nothing. +bool CareerSession::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; + } + // Each case rebuilds 'expected' (the layout bytes after the operation) from the live layout: + // bounds and optional grid snapping for moves, linked list chain edits (offsets +5/+6) for + // drawers, folders and the bin. + 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_visible=false; + for(size_t item=1;item=int(kItems)) break; + cursor=next; + } + if(owner_visible) break; + } + if(!owner_visible) { error="desk_folder_child_owner_hidden"; 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_visible=false; + for(size_t item=1;item=int(kItems)) break; + cursor=next; + } + if(owner_visible)break; + } + if(!owner_visible) { error="desk_bin_restore_folder_hidden";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; } + GameState staged=g_; + for(size_t i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "formats/fbm.hpp" +#include "formats/savestate.hpp" +#include "game/career.hpp" +#include "game/cup.hpp" +#include "game/driver.hpp" +#include "game/desk.hpp" +#include "game/desk_actions.hpp" +#include "game/match.hpp" +#include "game/messages.hpp" +#include "game/prediction.hpp" +#include "game/schedule.hpp" +#include "game/bank_credit.hpp" +#include "game/matchday_setup.hpp" +#include "game/matchday.hpp" +#include "game/lineup.hpp" +#include "game/month.hpp" +#include "game/national.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "game/table_forecast.hpp" +#include "game/save.hpp" +#include "game/season.hpp" +#include "game/turn.hpp" +#include "game/week.hpp" +#include "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::app { +namespace { + +// Reads one byte of the executable's data at 'address': from the game's memory image when the +// address is mapped there, else from the runtime override map, else from the loaded EXE. +uint8_t source_runtime_byte(const GameState& 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; +} + +// Writes one byte to the memory image when the address is mapped there, otherwise into the +// runtime override map (the EXE image itself is never modified). +void source_runtime_set_byte(GameState& state,std::map& runtime, + uint32_t address,uint8_t value) { + if(state.memory.has(address))state.memory.set8(address,value); + else runtime[address]=value; +} + +// Little-endian 32-bit read built from four source_runtime_byte reads. +uint32_t source_runtime_u32(const GameState& 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; +} + +// Writes the process scratch bytes (league, group, date pieces, strength sums) that the +// original leaves behind after drawing the pairings page, so later reads see the same values. +// Bytes go to the memory image when mapped there, else to the runtime map. +void pairings_runtime_draw(GameState& 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)); +} + +// Compares the runtime-only fields of two states (callbacks by target type); used to check the +// strengths view left the game unchanged. +bool same_strengths_runtime_state(const GameState& a,const GameState& 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); +} + +// Reinterprets the low byte of 'value' as a signed byte. +int8_t source_byte(int value) { return static_cast(uint8_t(value)); } + +// True when a table request carries no stray fields (no target child, team, row or dialog reply; +// league id only if the selector variant is allowed) and the expected control index. +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; +} + +} // namespace + +} // namespace bmh::app diff --git a/src/app/career_session_league.cpp b/src/app/career_session_league.cpp new file mode 100644 index 0000000..f7934b7 --- /dev/null +++ b/src/app/career_session_league.cpp @@ -0,0 +1,1318 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: the league family: tables, forecasts, friendly opponent table, phase results, running overview. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +namespace { + +// Builds the "first-end" round range label of the league table from a text template, patching +// the two two-digit numbers in the German or English layout. +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=league_system().english_competitions ? texts[82] : std::string(fixed.begin(),fixed.end()); + const size_t start=league_system().english_competitions ? 0 : 4; + const size_t finish=league_system().english_competitions ? 3 : 7; + if(raw.size() first +// and refreshes the retained range label; throws FormatError when the league is unknown. +void source_table_normalize_range(CareerSession::LeagueFamilyOwner::TableOwner& table, + const GameState& game,int league,const TextDb& texts) { + if(league<0||league>=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; +} + +// Sets the table aggregation flag bits from the clear bits 4 and 2 of the display-mode word. +void source_table_apply_entry_flags(CareerSession::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); +} + +// Packs a table owner's round range, flags, display word and optional accepted engine table +// (or forecast marker) into the projection context used to render the league table page. +ui::LeagueTableProjectionContext source_table_context( + const CareerSession::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; +} + +} // namespace + +// League family (table / pairings / strengths and the friendly opponent table): these three +// child screens are linked under one LeagueFamilyOwner carrying a family id. Pattern: each +// entry or transition validates the identity (revision, active manager slot, club, date) and +// the neighbouring child owners, snapshots the native save stream, random seeds and runtime +// bytes into the owner, and every close/suspend compares the live state with that snapshot so +// a stale or tampered request is rejected with an error text and nothing is changed. +// Child numbers: 1 = Table, 2 = Pairings, 3 = Strengths. +// Builds the identity (manager, club, date, default league, settings words) needed to open the +// strengths screen for the active manager; returns an empty optional when anything is missing. +std::optional CareerSession::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; +} + +// Opens the family at 'child' for the identity: checks no family/TeamInfo is active, the +// revision matches, the identity belongs to the active manager and club of today (or to the +// live overview owner), and that Pairings/Strengths entries have a matching child owner. +// Allocates a family id, snapshots the state into a LeagueFamilyOwner and, for the table, builds +// the page. Returns the bound identity, or an empty optional with 'error'. +std::optional CareerSession::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=save_stream(g_); + } + LeagueFamilyOwner owner;owner.identity=identity;owner.child=child;owner.native=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=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; +} + +// Opens the table used to pick a friendly-match opponent (child 1 with friendly_opponent set). +// Needs the strengths request of the active manager and no other child owner; the table +// display word is initialised for that picker. Any failure restores the family checkpoint. +std::optional CareerSession::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>=world_layout().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 {}; + } +} + +// Checks a select_opponent request against the owned table (identity, revision, row, club +// identity key) and returns the runtime team of the chosen row, or an empty optional with 'error'. +// Does not change state. +std::optional CareerSession::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>=world_layout().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; +} + +// The player picked their own club in the opponent table: restores the normal-mode bit of the +// display word, advances the family sequence and keeps the picker open. Empty optional on a +// stale or different-club request. +std::optional CareerSession::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=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; +} + +// Leaves the opponent table: validates a select_opponent (not the own club) or close request, +// restores the display word, validates the new preparation projection and drops the family +// owner while advancing the revision. Failure restores the checkpoint and returns empty. +std::optional CareerSession::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 {}; + } +} + +// Moves the family from one child screen to another: the request, owner and 'next' identity must +// agree (same family id, manager, club, day; sequence increased by one; revision at most one +// ahead). Replaces the owner with a fresh snapshot, building the table page when the target is +// the table. Returns false with 'error' when the transition is stale or mismatched. +bool CareerSession::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=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=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; +} + +// True when the identity (its source_param2 holds the match minute) belongs to the currently +// open live overview: same manager, team, minute and day, and for a phase-result viewer the +// same match group. +bool CareerSession::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))); +} + +// Final close of the family: the long condition re-verifies identity, child owner and that the +// live state, random generators and runtime bytes still equal the owner's snapshot. On success +// it commits staged Pairings changes (if any), draws the random stir unless a phase-result +// viewer owns that draw, resets the child owners and bumps the revision. Returns the new +// preparation projection, or an empty optional with 'error' and no change. +std::optional CareerSession::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_|| + 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||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&&(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 { + GameState 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) + 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 {};} +} + +// Leaves the Strengths child towards Table or Pairings without a full close: checks the owner +// snapshot is unchanged, then drops the strengths owner. False with 'error' when stale. +bool CareerSession::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||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; +} + +// Leaves the Pairings child towards Table or Strengths: after the same snapshot checks it +// commits only the staged page/redraw changes of the draft and drops the draft. False with +// 'error' when stale or the return word is missing. +bool CareerSession::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))|| + 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). + GameState 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; +} + +// Prepares the manager mode word and runtime bytes before a child screen is entered, after +// validating the identity and that no other child owner or dispatch is active. False with +// 'error' otherwise. +bool CareerSession::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; +} + +// Installs (or clears) the turn driver hook that fires at the end of a match phase. The wrapper +// records the current request in phase_result_request_ for the duration of the call, only +// accepts the driver's own groups and state, and requires that any viewer is closed again before +// the engine continues. +void CareerSession::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 GameState& 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; + // Clears the borrowed request pointer when the hook returns or throws. + 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"); + }; +} + +// Live overview group (phase-result viewer, live league table / pairings opened from a running +// match): only valid inside a calendar advance (calendar_advance_active_) with the driver +// waiting at a phase boundary. Pattern: open -> dispatch -> acknowledge; the owner snapshots the +// state and random counters when it opens and the close must find them unchanged. +// Opens the viewer at a phase boundary: copies the current group results into a staged state +// (no simulation, no random draws) and opens the overview on it; on failure the previous state +// is kept. Returns an empty optional with 'error' when no request is pending or a viewer is open. +std::optional CareerSession::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. + GameState 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)*kLeagueResultsStride + 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 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 {}; } +} + +// Forwards a viewer action while the phase-result owner of the pending request is open; empty +// optional with 'error' if the viewer is missing or belongs to another group. +std::optional CareerSession::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); +} + +// Opens the overview from a key press during a running match (not a phase-result viewer). +std::optional CareerSession::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); +} + +// Shared opener. The long guard requires an active calendar advance, no other modal owner or +// dispatch, a request that matches the driver's groups, the live state objects and the active +// manager (revision and scope included). key_slot 0 opens the league table, 1 the league +// pairings. Returns an empty optional with 'error' when the request is stale, nested or +// unauthenticated. +std::optional CareerSession::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 {}; + } + + + // Scope guard: turns calendar_advance_active_ off while the family screens run and restores the + // previous value on exit, so nested family code does not treat itself as inside the advance. + 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 = 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_,{}, {}, + 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 = 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 { + // Cup descriptor (not a league): the overview becomes an other-games detail page bound to the + // active cup entry, found by trying linked-page ordinals until the cup entry and competition + // id match. Anything else throws and is rolled back by the catch block below. + if (request.key_slot != 0 && request.key_slot != 1) + throw FormatError("live overview: invalid cup overview key slot"); + const int entry_index = 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(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(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 >= 138 || 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=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=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(); + // Commit point: the owner now holds its final kind, family identity and revision; the scope + // counter and the revision are advanced only here, after every child owner was opened. + 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) { + // Failure path: restore the family, pairings and other-games checkpoints, drop the overview + // owner and put the scope counter back, so a failed open leaves no trace. + 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 {}; + } +} + +// League table dispatch group (controls, range dialog, forecast acknowledgement, league +// selector, team info). Pattern: validate the request envelope, identity, owner and that the +// live state still equals the owner snapshot; take a checkpoint; apply the change to the +// table owner; refresh the snapshot and identity (sequence + 1, revision + 1); on any failure +// restore the checkpoint and the old revision and return an empty optional with 'error'. +// Projects the table page (or the pending range dialog profile) of the owned table child; +// read-only. Empty optional with 'error' when no table owner exists or the state drifted. +std::optional CareerSession::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(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 {};} +} + +// Applies one of the table's ten controls (index 0-9) to the owned table. Requires a ready +// table, a canonical request envelope and an unchanged snapshot; revision advances by one. +std::optional CareerSession::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|| + 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); + }; + // Controls 0-2 set the aggregation flags and mode bits, 3 computes a forecast table (shown + // after the present acknowledgement), 4-6 toggle display bits (at least one stays set), 7 + // toggles the normal mode, 8 resets the round range to the whole season and 9 starts the + // two-step range dialog. + 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 CareerSession::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)|| + 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=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 {};} +} + +// The forecast page has been shown: adopts the random generator state computed with the +// forecast, returns the table to ready and rebuilds the normal page. +std::optional CareerSession::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|| + 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=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 {};} +} + +// Switches the table to another league (map click) or toggles the league group, after +// checking the target is listed in the bound league map. Works on staged copies of the state, +// runtime bytes and owner and commits them only on success; returns false with 'error' otherwise. +bool CareerSession::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|| + 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 CareerSession::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_|| + 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; + GameState 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; + // Marks the family as inside TeamInfo while the presenter runs; cleared on every exit. + 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)&& + save_stream(before.state)==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; + // The club information enters the club again on every redraw (view toggle, statistics, player + // card), so one entry is the minimum; requiring exactly one threw away the whole visit, also the + // Nein/Radio/Video setting made in it. + if(!live_unchanged||!accepted||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=club_player_detail_context(next,**poach_selection); + if(chosen.selection.runtime_team!=selected_team || chosen.source_slot<0 || + chosen.source_slot>=0xb70 || 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=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=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 {};} +} + +// After a child screen acknowledged its page, re-binds the family owner to the child's new +// identity (same family id and sequence, revision at most one ahead) and refreshes its snapshot. +// False with 'error' when the identity or child owner is stale. +bool CareerSession::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=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; +} + +} // namespace bmh::app diff --git a/src/app/career_session_management.cpp b/src/app/career_session_management.cpp new file mode 100644 index 0000000..64d08f6 --- /dev/null +++ b/src/app/career_session_management.cpp @@ -0,0 +1,803 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: club management: training, training camp, bank, stadium, toto. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +namespace { + +constexpr uint8_t kBlockSeat = 1; + +constexpr uint8_t kBlockRoof = 2; + +constexpr uint8_t kBlockFeatures = kBlockSeat | kBlockRoof; + +// True for the stadium requests that belong to the block-expansion dialog (select, total, +// feature toggle, cancel, confirm, answer tip). +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; +} + +} // namespace + +// Training group: one request changes the types, areas, automation byte or one player's +// intensity or focus of the active manager. The request carries the desired result; it is +// validated against the current projection (stale manager, plan limits, expected values), applied +// on a staged copy and committed with revision plus one. Manual edits clear the matching +// assistant flag and never draw random numbers; initialize and enabling automation run the +// automatic training. Returns false with a short error code in 'error' otherwise. +bool CareerSession::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; + } + + GameState 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) 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; + } +} + +// Training camp group: set_focus changes the four focus bytes of the active manager (an unchanged +// or invalid focus is refused); book books a resort for the week after checking the focus the UI +// saw, the weekly/visit limits and the funds (the booking draws random numbers). Refused while a +// modal owner is open or when the manager slot, club or revision is stale; revision plus one on +// success, short error codes in 'error' otherwise. +bool CareerSession::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 (!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 (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 (!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; +} + +// Bank group: deposit moves, share and fund trades, stock tips and bank credit. Needs the active +// manager, club and current revision and no modal owner open. Every branch validates amounts and +// counts against the manager record and the stock/fund blocks, then applies the change to the +// live state and bumps the revision once. The notices of the last property purchase or credit +// refund are kept for the next projection. Returns false with a short error code otherwise. +bool CareerSession::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; + } + 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 > 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 (!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; } + 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_ = 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 > max_fund_units(g_, request.manager_slot, request.asset_index)) { + error = "invalid_fund_count"; return false; + } + const int32_t additional_cost = 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; } + 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 = 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; +} + +// True when a construction tip dialog is open and the process timer (when running) has no time +// left; read-only. +bool CareerSession::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; +} + +// Stadium group: an owner (stadium_) is opened with a scope id and every later request must echo +// scope and sequence, the manager, club, stable club identity, game mode and revision. All +// actions (data page, periphery quote/build, block expansion editor with its tip, investments) +// run inside the apply lambda below; on failure the stadium checkpoint is restored, on success +// revision, sequence and the owner's revision advance. Exceptions restore the checkpoint and +// the revision and are rethrown. Short error codes in 'error' otherwise. +// Older periphery callers send no scope envelope; a compatibility step fills it in for their four +// original operations only. +bool CareerSession::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 >= 357 || + 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 { + // Performs the validated stadium action and returns true on success; 'invalid' records the + // reason and returns false. + 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 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 = 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 = 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 = 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"); + const auto block_constants=stadium_block_expansion_constants(exe_); + const auto quote_block = [&](StadiumBlockSlot slot, uint32_t total, uint8_t features) { + return 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 = 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; + resolve_stand_block_offer(resolved, request.accept_tip, rand_); + const bool built = 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 = 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; + resolve_stand_block_offer(resolved, request.accept_tip, rand_); + const bool built = 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; + } +} + +// Submits a pools coupon for the active manager; only valid when the coupon has eleven matches. +// Revision plus one; false with a short error code otherwise. +bool CareerSession::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 (!submit_pools_coupon(g_, request.manager_slot, request.stake, request.tips)) { + error = "invalid_toto_coupon"; return false; + } + ++revision; + return true; +} + +} // namespace bmh::app diff --git a/src/app/career_session_match.cpp b/src/app/career_session_match.cpp new file mode 100644 index 0000000..7388c7f --- /dev/null +++ b/src/app/career_session_match.cpp @@ -0,0 +1,1530 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: match preparation and the live match: tactics, line-up, live overview, interventions, pitch. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +// Sets one tactic option (index 0-7, value within the executable's limit) for the active +// manager; touches only the manager record option bytes, never the tactics board or random +// generators. False with a German 'error' text when stale or invalid; revision plus one. +bool CareerSession::dispatch_tactics(const ui::TacticsRequest& 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(); + 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 = "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; +} + +// Lineup requests of the active manager (refused during a calendar advance or pending offer +// dispatch). prepare_lineup builds the lineup entry on a staged copy and accepts it only when +// the first eleven squad rows form a valid authoritative lineup. +bool CareerSession::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) { + GameState 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. + 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; + } + // Swap path: only allowed after prepare_lineup for the same manager and club. The two rows must + // still hold the slots and players the UI saw; injured players and the foreign-player rule are + // refused until their dialogs exist. The swap exchanges squad slots (keeping the role bits with + // the row) and tactic board entries, re-syncs the card row ids and switches the manager's + // formation automation off. + 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; +} + +// Live overview dispatch (pattern open -> dispatch -> acknowledge): applies one action of the +// overview opened by open_running_overview. Requires an active calendar advance, the owner of the +// current revision and an engine that is still bound to this session with unchanged match groups +// and referees. The action variant selects the child: league family navigation or control, +// strengths, pairings or the cup other-games page. Close actions end the owner and return a +// preparation projection; a failure returns an empty optional with 'error'. +std::optional CareerSession::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_; + // Scope guard: calendar_advance_active_ is off while the family code runs and is restored on exit. + 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_,{}, {}, + 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=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; + // The opposite guard: sets calendar_advance_active_ for the nested table/pairings navigation, + // which expects to run inside the advance, and restores the value afterwards. + 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 {}; + } +} + +// Live intervention group (lineup changes during a running match). Pattern: begin stores a +// LiveInterventionCheckpoint (state, match groups, both random generators, revision), the +// substitution requests work against it, finish rerates the team and bumps the revision, abort +// puts everything back. +// Begin: only after minute 2, source mode 2 or 8, for a human manager whose team plays in the +// current match. Mode 2 also runs the lineup entry preparation. Returns false with a German +// 'error' text and no open intervention otherwise. +bool CareerSession::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 { + GameState 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; +} + +// Begin for an automatic intervention caused by a match event (kind 1 or 2): the event must match +// the engine's current group, match, side and teams, the manager must have the automatic +// option on, and the affected player must show the expected status. Opens the lineup entry like +// mode 2; false with 'error' otherwise. +bool CareerSession::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 { + GameState 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; +} + +// Ends an event intervention: the open checkpoint must belong to exactly this event and the +// engine groups must be unchanged. Only consumes the owner and bumps the revision (the rerate +// belongs to the event itself). +bool CareerSession::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; +} + +// Ends a normal intervention: rerates the team on a staged engine copy; on success the staged +// state, groups and generators replace the live ones and the revision advances, on a rerate +// failure or exhausted revision the checkpoint is restored. False with a German 'error' text. +bool CareerSession::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_; + GameState 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; +} + +// Abandons the matching open intervention and restores state, groups, random generators and the +// revision from its checkpoint. Does nothing if no matching intervention is open. +void CareerSession::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(); +} + +// Applies one swap of the open live intervention (mode 2 only): checks owner, revision, manager, +// team and that the rows still hold the shown slots and players, whether it is a same-zone +// exchange or a field/bench substitution, and the injury status of both players (some notices +// are reported as "source_notice" codes in 'error'). False with 'error' on any failure. +bool CareerSession::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 (nationality(g_, slot & 0x0fff) != 0) ++foreign_on_field; + } + foreign_on_field -= nationality(g_, field_player) != 0; + foreign_on_field += 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. + GameState 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; +} + +// Wraps dispatch_live_substitution: applied, a "source_notice" status carrying the original +// notice address parsed from the error text, or rejected with the error text. +LiveSubstitutionResult CareerSession::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)}; +} + +// Sets one tactic option during the open live intervention (source mode 8, after minute 2): the +// intervention owner, revision, manager, team and current match must match, the value must be in +// range and available. Only the manager record bytes change; revision plus one and the open +// intervention's current revision follows. False with a German 'error' text otherwise. +bool CareerSession::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; +} + +// Pitch (lineup screen) group: all pitch actions (swap, move player, weights, formations, +// set piece editor and takers, player orders, marking, page switches). A swap is forwarded to +// dispatch_lineup. Everything else is checked against the display word, the saved set piece +// signature and the expected old values in the request, applied on a staged copy of the state +// and committed with a revision bump. False with a German 'error' text or a short code otherwise. +bool CareerSession::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. + // True when the request belongs to the open live lineup intervention (same manager, team and + // revision); such requests are authorised by that owner instead of by the desk phase. + 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; + // True during the very first lineup window before the first desk exists (driver stage Empty). + 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 { + GameState 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; +} + +// Pitch request during a live intervention: needs the matching open intervention (mode 2) and +// current revision. Formation and weight controls exist only in the initial preparation and are +// refused here; the rest goes to dispatch_pitch. +bool CareerSession::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); +} + +// Result-style wrapper: swaps return the substitution result (with source notices), other pitch +// actions return applied or rejected with the error text. +LiveSubstitutionResult CareerSession::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)}; +} + +// Desk-time swap only; any other pitch kind is refused. +bool CareerSession::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); +} + +// Preparation (match day) projection of the live state at 'revision'; read-only. +ui::PreparationState CareerSession::preparation_projection(uint64_t revision) const { + return preparation_projection(g_, revision); +} + +// Returns the opponent team of the manager's prepared lineup entry (from the captured desk call +// arguments, confirmed against the desk projection), or nothing when the manager is not the +// active prepared one, the day has no ordinary opponent or any check fails. Read-only. +std::optional CareerSession::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 == kNoTeam || 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 = day_competitions(g_, turn_driver_.calendar_entry); + if (competitions == 0x800000) competitions = 0; + const int default_competition = competitions != 0 ? 34 : 33; + GameState 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) * kLeagueResultsStride + 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; +} + +// Builds the preparation projection of 'state' and layers the session-owned extras on top: the +// desktop, the lineup "entry prepared" flag and pitch extras, the bank notices and the stadium +// page including its open dialogs (construction tip, periphery quote, block expansion editor) +// when the stadium owner belongs to this exact manager, club and revision. Read-only. +// Throws FormatError when the manager's league cannot be found. +ui::PreparationState CareerSession::preparation_projection(const GameState& 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; +} + +} // namespace bmh::app diff --git a/src/app/career_session_statistics.cpp b/src/app/career_session_statistics.cpp new file mode 100644 index 0000000..2016c61 --- /dev/null +++ b/src/app/career_session_statistics.cpp @@ -0,0 +1,1346 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: strengths, top scorers, opportunities, other games, balance plan and league pairings. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +namespace { + +// Fills every rank with 1 and returns 0 unless the first league's round counter is in the +// range [2, matchdays of league 0); inside that range it returns 9 for team ids >= 138 and 0 +// for all other teams. +int national_opportunities_rank(const GameState& 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>=world_layout().league_teams?9:0; +} + +// Copies the executable's presentation switches (decorated background, solid panel, text +// gradient, cached backdrop) onto the balance page state. +void apply_balance_source_style(ui::BalanceState& page,const GameState& 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; +} + +// True when 'team' belongs to one of the human managers or to the national team record of a +// national coach; throws FormatError when the manager count is missing or invalid. +bool other_games_source_manager_owned(const GameState& 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; +} + +// Replays the side effects of drawing the other-games page: five ordered team-average +// calculations per displayed club (some of which draw random numbers) and the scratch bytes +// they leave. +void other_games_source_redraw_effects(GameState& 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)); + } + } + } + } +} + +// True when two other-games checkpoints agree on state, random generators, runtime bytes, +// selection and owner identity, i.e. nothing observable changed in between. +bool same_other_games_live_baseline(const CareerSession::OtherGamesCheckpoint& before, + const CareerSession::OtherGamesCheckpoint& after) { + if(save_stream(before.state)!=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; +} + +} // namespace + +// Strengths / top scorers / opportunities / other games group: modal desk pages that follow +// open -> dispatch -> acknowledge. Each open_* validates the desk request (menu kind, revision, +// active manager slot, desk stage, no other modal owner) and stores an owner that snapshots the +// native stream and the random counters; each dispatch_* refuses a stale identity or a changed +// snapshot, applies one action on a copy, bumps revision and sequence and returns the new page +// plus the desktop projection. Failures return an empty optional with 'error' and change nothing. +// National-coach desk identity: while a national coach manages the national team the manager's +// team is the national slot (kNoTeam or 0x165); the club identity key is then taken from the +// spare manager record 4 (offset 0x290) instead of the club table. +// Strengths dispatch: one entry point for open, control, league select, group toggle, team info +// and close of the strengths page (also used as a child of the league family). +std::optional CareerSession::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; + // The turn driver marks the claimed turn as Failed until it completes (a guard against replaying + // a half-played turn), so inside the running matchday the stage is not a desk. The Stärken page + // of the live overview (G key, results page after a phase) belongs to that running turn. + const bool running_turn=live_overview_owner_.has_value()&&turn_driver_.stage==TurnDriver::Stage::Failed; + 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&&!running_turn)|| + 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|| + 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; + // Re-entrancy flag: set while this dispatch runs (callbacks may re-enter), cleared on every exit. + 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. + GameState 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 save_stream(before.state)==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,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; + } + GameState 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,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 {};} +} + +// Opens the top scorers page (desk menu 20) for the active manager; refuses while the process +// timer context is active. For a national coach the club identity comes from the spare record. +// Returns the first page (goals, league scope) or an empty optional with 'error'. +std::optional CareerSession::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 == kNoTeam) { + // 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 >= world_layout().league_teams) { + throw FormatError("top scorers: manager team is outside Source league scope"); + } + if (stable_team < 0 || stable_team >= 138 || 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, 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 {}; + } +} + +// Applies one top scorers action: close, metric cycle (goals -> assists -> scorer -> goals) or +// scope toggle. Rejects a stale, replayed or modified owner; commits the new page on success. +std::optional CareerSession::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 || 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 == kNoTeam ? + (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 >= world_layout().league_teams || + 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 = 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 {}; + } +} + +// Statistics menu (desk menu 23): flips the manager's statistics preference flags. Needs the open +// menu owner request of the current revision and the expected current flag byte; allows exactly +// one metric bit (below 0x40) or the pair 0xc0 to change. Returns false with 'error' otherwise. +bool CareerSession::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; +} + +// Opens the opportunities page (desk menu 23) for the active manager. 'national_source_case' +// selects the national-team variant (team 0x165, league 0, identity supplied by the caller as +// 'stable_identity'). Needs the 320x240 desktop underlay. Empty optional with 'error' on failure. +std::optional CareerSession::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!=kNoTeam||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>=138||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=league_system().sizes[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,save_stream(g_),game_,rand_,national_source_case};++next_opportunities_scope_; + return page; + } catch(const std::exception& e){error=e.what();return {};} +} + +// Closes the opportunities page or selects one of its modes (1, 2, 4 or 8) and recomputes the +// rank table; stale or modified owners are rejected. +std::optional CareerSession::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||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!=kNoTeam|| + 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): + 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,save_stream(g_),game_,rand_,national_source_case}; + ++revision;return result; + } catch(const std::exception& e){error=e.what();return {};} +} + +// Opens the other-games overview (desk menu 5): validates the desk request and runs the entry +// changes on a staged copy (season-dependent selector byte, selector 12 insertion or removal), +// then builds the page for the remembered competition. The copy replaces the live state only +// once the page and owner exist. Empty optional with 'error' on failure. +std::optional CareerSession::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"); + + GameState 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) { + 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 >= 138 || 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 = 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 {}; + } +} + +// Applies one action of the other-games overview against the owner snapshot (a team info +// presenter may be supplied); empty optional with 'error' when the request or owner is stale. +std::optional CareerSession::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 || 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 CareerSession 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 >= 138 || 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"); + // Team info branch: the presenter runs against a staged copy (state, both random generators, + // runtime bytes) and the live session must come back unchanged; only then is the staged copy + // committed together with the redrawn page and the owner snapshot is refreshed. + 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"); + + GameState 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>=138||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=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 { + GameState 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; + // Page navigation actions (selector, linked page, previous/next round, display toggle): each is + // validated against what the current page offers, then the page is rebuilt on a staged copy. + 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 = 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 {}; + } +} + +// Balance plan group (desk menu 28): the plan is edited in a draft (BalanceDraft) that holds a +// copy of the state, random generators and runtime bytes. Pattern: open -> edit actions on the +// draft -> close; closing may stage a warning that needs a confirmation, and only the final +// close or confirmation moves the draft into the live state and bumps the revision. +// Opens the balance plan for the active manager's club; empty optional with 'error' on a stale, +// nested or unsupported opening (any other modal owner or dispatch counts as nested). +std::optional CareerSession::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_,{},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)}; + GameState 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=bmh::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 {};} +} + +// Applies one balance action to a copy of the draft: edit a row, cycle the view, take actual +// values, close, or confirm a staged warning close. Rejects a stale identity or a live state +// that differs from the draft's origin. Only a closing action commits the draft and bumps the +// revision; a staged warning keeps the draft open. Empty optional with 'error' on failure. +std::optional CareerSession::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|| + 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=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"); + cycle_balance_view(next.state,draft);break; + case ui::BalanceAction::take_actuals: + if(request.row!=-1||request.value)throw FormatError("balance: malformed reset action"); + 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; + GameState 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=bmh::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=original_badge_fallback(club,&exe_); + if(!notice.badge_fallback&&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 {};} +} + +// League pairings group (desk menu 1): like the balance plan it works on a draft copy +// (LeaguePairingsDraft) that remembers the active match groups and referee profiles of the turn +// driver, so a draft is only valid while those are unchanged. +// Opens the pairings page for the manager; empty optional with 'error' on a stale, nested or +// unsupported opening. +std::optional CareerSession::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_,{}, {}, + 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=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;} +} + +// Refuses to continue while the original's process timer is running (not implemented), then asks +// the pairings source for the active-match packet of the running groups and records the active +// group and phase in the owner. Returns the packet, or nothing when no match group is active. +std::optional CareerSession::validate_normal_pairings_group( + const GameState& 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=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)validate_league_pairings_active_packet_source(state,owner,*packet); + return packet; +} + +// Applies one pairings event (page change, computer tip, team info, close) to a copy of the +// draft. The live state must still equal the draft's origin (live_matches below). On close the +// draft is committed and the revision advances; otherwise a new page is returned and the draft +// refreshed. Empty optional with 'error' when stale, nested or a presenter stops. +std::optional CareerSession::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(); + // True while the live state, random counters, runtime bytes, match groups and referee profiles + // still equal what the draft started from. + 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=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 bmh::app diff --git a/src/app/career_session_transfer.cpp b/src/app/career_session_transfer.cpp new file mode 100644 index 0000000..bcfc0eb --- /dev/null +++ b/src/app/career_session_transfer.cpp @@ -0,0 +1,669 @@ +// SPDX-License-Identifier: GPL-3.0-only +// CareerSession: transfers: offer editor, poaching, transfer market. +// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp) +#include "app/career_session_internal.hpp" + +namespace bmh::app { +namespace { + +// Transfer editor / market group (helpers first). Projects the engine's transfer offer editor +// owner into the UI state: the quote fields, calculator profiles and, unless the editor is +// closed, the incoming-offer decision panel read from the four offer rows of the market list. +ui::OutgoingTransferEditorState transfer_offer_projection(const GameState& 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; +} + +} // namespace + +// Public wrapper so other code (loan return offers) can reuse the editor projection. +ui::OutgoingTransferEditorState loan_return_offer_editor_projection( + const GameState& game, const TransferOfferEditorState& owner, uint64_t revision, bool gradient) { + return transfer_offer_projection(game, owner, revision, gradient); +} + +// Maps a UI field edit onto the engine's transfer offer editor edit and returns the new owner. +TransferOfferEditorState edit_transfer_offer_from_ui(GameState& game, + const TransferOfferEditorState& owner, const ui::OutgoingTransferRequest& request, + GameRandom& game_random, WatcomRandom& watcom_random) { + return edit_transfer_offer_editor_source(game, owner, + {TransferOfferEditorField(uint8_t(request.field)), request.value, request.accepted}, + game_random, watcom_random); +} + +// Transfer market request family (open offer, poach, editor events, quote preview, market +// actions): each entry validates the request revision, the active manager slot and the manager's +// club, refuses nested modals (market_dispatch_active_ and the other owners), works on copies of +// the state and both random generators and commits them only on success. The revision is +// advanced only where something observable changed. Failures return an empty optional and an +// error text. +// Opens the buyer's offer editor for a marked market row after checking the row identity +// against the market list in memory; the editor owner and its revision are stored on success. +std::optional CareerSession::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 != 2928 + 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 = 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; } +} + +// Starts a poaching attempt for a squad slot: the attempt draws random numbers, so the revision +// advances whenever the result is not invalid; a ready attempt also opens the offer editor on +// the special poach row and remembers the attempt in poach_. +std::optional CareerSession::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 = 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, 2928 + row, + result.start.player, next_state.memory.u16(::bmh::layout::EditorList + uint32_t(row) * 0x58 + 8), 0, false, true}; + auto owner = 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; } +} + +// Closes the table opened only to choose a poach target: needs an unchanged table owner, then +// restores the display word and drops the family owner without a family close. False with +// 'error' if stale. +bool CareerSession::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 || + 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; +} + +// Poach flow driven by UI callbacks: checks the request is a pristine open_poach request of the +// current revision (320x240 backdrop, nothing else open), then reports attempts-used or +// transfer-ban notices, or lets the player pick a squad player in a table on a cloned session +// and opens the poach from that choice. The UI acknowledges through 'accept'; any failure, +// including a session changed by the acknowledgement, restores the checkpoint and revision. +bool CareerSession::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. + CareerSession 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=club_player_detail_context(next,*selection); + slot=player.source_slot; + if(slot<0 || slot>=0xb70 || 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; + } +} + +// Applies one editor event (field quote change, submit, cancel, team info, player info) to the +// open offer editor: identity and quote must match the owner and the posted row must equal the +// single field change. Runs on copies; the revision rises only if state, runtime bytes or a +// random generator actually changed. A closing editor ends a poach attempt and clears the owner. +std::optional CareerSession::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 = 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=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=resume_transfer_offer_team_info_source(next_state,current,next_rand); + } else if(request.kind==ui::OutgoingTransferRequestKind::player_info) { + const auto selection=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=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 = 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_) finish_poach(next_state, *poach_); + const bool changed = save_stream(next_state) != 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; } +} + +// Quotes a purchase, lender snapshot or squad row preview (the listing identity is re-checked) +// using a copy of the W random stream; the stream and revision are updated only if the quote +// and its projection both succeed. +std::optional CareerSession::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 != 0xb70 + 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 = 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 = 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; + } +} + +// Direct market actions of a human manager: review offers, submit a bid, list a player. Needs +// a request of the current revision for the active manager's club; loans and marked batches are +// not accepted here. The allocator gate comes from the turn driver, never from the presenter. +// The staged copy is committed (revision plus one) only if something changed. +std::optional CareerSession::dispatch_transfer_market( + const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& presenters, + uint64_t& revision, std::string& error, + const std::function& review) { + 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::review_offers) { + if (!review || request.bid.manager != request.manager_slot || request.bid.list_entry < 0 || + request.bid.list_entry >= 40 || request.bid.source_slot != 0xb70 + request.bid.list_entry || + request.squad_row != -1 || !request.selected_players.empty()) { + error = "transfer market: invalid offer review"; return std::nullopt; + } + const auto view = project_transfer_offer_list(g_, request.bid.list_entry); + if (!view.valid || view.player != request.bid.player || view.seller != request.runtime_club || + view.seller_manager != request.manager_slot) { + error = "transfer market: stale seller listing"; return std::nullopt; + } + } else 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 = save_stream(g_); + TransferActionResult result; + if (request.kind == ui::TransferMarketRequestKind::review_offers) { + const auto view = project_transfer_offer_list(next_state, request.bid.list_entry); + result.player = view.player; result.list_entry = view.list_entry; + result.status = TransferActionStatus::pending; + // VERKAUFEN on a listed player: "Wollen Sie vom Transfermarkt holen?". Yes frees the list + // slot (the player stays in the squad), no goes on to the offers. + bool withdrawn = false; + if (request.ask_withdraw && hooks.confirm) { + const std::string question = message_text(next_state, ::bmh::layout::TransferMarket_WithdrawQuestion_TextPointer) + + next_state.player_name(view.player) + + message_text(next_state, ::bmh::layout::TransferMarket_WithdrawQuestion_TextPointer2); + if (hooks.confirm(next_state, request.manager_slot, question)) { + next_state.squad_slots.at(0xb70u + size_t(view.list_entry)) = 0xfff; + withdrawn = true; + } + } + const int selected = !withdrawn && view.offer_count ? review(next_state, view) : -1; + if (selected != -1) { + auto allocator = TransferAllocatorContext::unsupported; + if (turn_driver_.transfer_allocator_context == PendingOfferAllocatorGate::zero) + allocator = TransferAllocatorContext::zero; + else if (turn_driver_.transfer_allocator_context == PendingOfferAllocatorGate::blocked) + allocator = TransferAllocatorContext::blocked; + result = accept_manager_transfer_offer(next_state, request.manager_slot, + view.list_entry, view.player, selected, next_rand, report, allocator); + } + } else if (request.kind == ui::TransferMarketRequestKind::list_player) + result = list_manager_player(next_state, request.manager_slot, request.squad_row, next_rand, report); + else + result = 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 = 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; + } +} + +} // namespace bmh::app